Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
24 #include <curses.h>
25 #include <panel.h>
26 #include <locale.h>
27 #include <sha1.h>
28 #include <sha2.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #include <string.h>
35 #include <err.h>
36 #include <unistd.h>
37 #include <limits.h>
38 #include <wchar.h>
39 #include <time.h>
40 #include <pthread.h>
41 #include <libgen.h>
42 #include <regex.h>
43 #include <sched.h>
45 #include "got_version.h"
46 #include "got_error.h"
47 #include "got_object.h"
48 #include "got_reference.h"
49 #include "got_repository.h"
50 #include "got_diff.h"
51 #include "got_opentemp.h"
52 #include "got_utf8.h"
53 #include "got_cancel.h"
54 #include "got_commit_graph.h"
55 #include "got_blame.h"
56 #include "got_privsep.h"
57 #include "got_path.h"
58 #include "got_worktree.h"
60 #ifndef MIN
61 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
62 #endif
64 #ifndef MAX
65 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
66 #endif
68 #define CTRL(x) ((x) & 0x1f)
70 #ifndef nitems
71 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
72 #endif
74 struct tog_cmd {
75 const char *name;
76 const struct got_error *(*cmd_main)(int, char *[]);
77 void (*cmd_usage)(void);
78 };
80 __dead static void usage(int, int);
81 __dead static void usage_log(void);
82 __dead static void usage_diff(void);
83 __dead static void usage_blame(void);
84 __dead static void usage_tree(void);
85 __dead static void usage_ref(void);
87 static const struct got_error* cmd_log(int, char *[]);
88 static const struct got_error* cmd_diff(int, char *[]);
89 static const struct got_error* cmd_blame(int, char *[]);
90 static const struct got_error* cmd_tree(int, char *[]);
91 static const struct got_error* cmd_ref(int, char *[]);
93 static const struct tog_cmd tog_commands[] = {
94 { "log", cmd_log, usage_log },
95 { "diff", cmd_diff, usage_diff },
96 { "blame", cmd_blame, usage_blame },
97 { "tree", cmd_tree, usage_tree },
98 { "ref", cmd_ref, usage_ref },
99 };
101 enum tog_view_type {
102 TOG_VIEW_DIFF,
103 TOG_VIEW_LOG,
104 TOG_VIEW_BLAME,
105 TOG_VIEW_TREE,
106 TOG_VIEW_REF,
107 TOG_VIEW_HELP
108 };
110 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
111 enum tog_keymap_type {
112 TOG_KEYMAP_KEYS = -2,
113 TOG_KEYMAP_GLOBAL,
114 TOG_KEYMAP_DIFF,
115 TOG_KEYMAP_LOG,
116 TOG_KEYMAP_BLAME,
117 TOG_KEYMAP_TREE,
118 TOG_KEYMAP_REF,
119 TOG_KEYMAP_HELP
120 };
122 enum tog_view_mode {
123 TOG_VIEW_SPLIT_NONE,
124 TOG_VIEW_SPLIT_VERT,
125 TOG_VIEW_SPLIT_HRZN
126 };
128 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
130 #define TOG_EOF_STRING "(END)"
132 struct commit_queue_entry {
133 TAILQ_ENTRY(commit_queue_entry) entry;
134 struct got_object_id *id;
135 struct got_commit_object *commit;
136 int idx;
137 };
138 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
139 struct commit_queue {
140 int ncommits;
141 struct commit_queue_head head;
142 };
144 struct tog_color {
145 STAILQ_ENTRY(tog_color) entry;
146 regex_t regex;
147 short colorpair;
148 };
149 STAILQ_HEAD(tog_colors, tog_color);
151 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
152 static struct got_reflist_object_id_map *tog_refs_idmap;
153 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
155 static const struct got_error *
156 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
157 struct got_reference* re2)
159 const char *name1 = got_ref_get_name(re1);
160 const char *name2 = got_ref_get_name(re2);
161 int isbackup1, isbackup2;
163 /* Sort backup refs towards the bottom of the list. */
164 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
165 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
166 if (!isbackup1 && isbackup2) {
167 *cmp = -1;
168 return NULL;
169 } else if (isbackup1 && !isbackup2) {
170 *cmp = 1;
171 return NULL;
174 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
175 return NULL;
178 static const struct got_error *
179 tog_load_refs(struct got_repository *repo, int sort_by_date)
181 const struct got_error *err;
183 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
184 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
185 repo);
186 if (err)
187 return err;
189 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
190 repo);
193 static void
194 tog_free_refs(void)
196 if (tog_refs_idmap) {
197 got_reflist_object_id_map_free(tog_refs_idmap);
198 tog_refs_idmap = NULL;
200 got_ref_list_free(&tog_refs);
203 static const struct got_error *
204 add_color(struct tog_colors *colors, const char *pattern,
205 int idx, short color)
207 const struct got_error *err = NULL;
208 struct tog_color *tc;
209 int regerr = 0;
211 if (idx < 1 || idx > COLOR_PAIRS - 1)
212 return NULL;
214 init_pair(idx, color, -1);
216 tc = calloc(1, sizeof(*tc));
217 if (tc == NULL)
218 return got_error_from_errno("calloc");
219 regerr = regcomp(&tc->regex, pattern,
220 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
221 if (regerr) {
222 static char regerr_msg[512];
223 static char err_msg[512];
224 regerror(regerr, &tc->regex, regerr_msg,
225 sizeof(regerr_msg));
226 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
227 regerr_msg);
228 err = got_error_msg(GOT_ERR_REGEX, err_msg);
229 free(tc);
230 return err;
232 tc->colorpair = idx;
233 STAILQ_INSERT_HEAD(colors, tc, entry);
234 return NULL;
237 static void
238 free_colors(struct tog_colors *colors)
240 struct tog_color *tc;
242 while (!STAILQ_EMPTY(colors)) {
243 tc = STAILQ_FIRST(colors);
244 STAILQ_REMOVE_HEAD(colors, entry);
245 regfree(&tc->regex);
246 free(tc);
250 static struct tog_color *
251 get_color(struct tog_colors *colors, int colorpair)
253 struct tog_color *tc = NULL;
255 STAILQ_FOREACH(tc, colors, entry) {
256 if (tc->colorpair == colorpair)
257 return tc;
260 return NULL;
263 static int
264 default_color_value(const char *envvar)
266 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
267 return COLOR_MAGENTA;
268 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
269 return COLOR_CYAN;
270 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
271 return COLOR_YELLOW;
272 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
273 return COLOR_GREEN;
274 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
275 return COLOR_MAGENTA;
276 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
277 return COLOR_MAGENTA;
278 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
279 return COLOR_CYAN;
280 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
281 return COLOR_GREEN;
282 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
283 return COLOR_GREEN;
284 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
285 return COLOR_CYAN;
286 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
287 return COLOR_YELLOW;
288 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
289 return COLOR_GREEN;
290 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
291 return COLOR_MAGENTA;
292 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
293 return COLOR_YELLOW;
294 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
295 return COLOR_CYAN;
297 return -1;
300 static int
301 get_color_value(const char *envvar)
303 const char *val = getenv(envvar);
305 if (val == NULL)
306 return default_color_value(envvar);
308 if (strcasecmp(val, "black") == 0)
309 return COLOR_BLACK;
310 if (strcasecmp(val, "red") == 0)
311 return COLOR_RED;
312 if (strcasecmp(val, "green") == 0)
313 return COLOR_GREEN;
314 if (strcasecmp(val, "yellow") == 0)
315 return COLOR_YELLOW;
316 if (strcasecmp(val, "blue") == 0)
317 return COLOR_BLUE;
318 if (strcasecmp(val, "magenta") == 0)
319 return COLOR_MAGENTA;
320 if (strcasecmp(val, "cyan") == 0)
321 return COLOR_CYAN;
322 if (strcasecmp(val, "white") == 0)
323 return COLOR_WHITE;
324 if (strcasecmp(val, "default") == 0)
325 return -1;
327 return default_color_value(envvar);
330 struct tog_diff_view_state {
331 struct got_object_id *id1, *id2;
332 const char *label1, *label2;
333 FILE *f, *f1, *f2;
334 int fd1, fd2;
335 int lineno;
336 int first_displayed_line;
337 int last_displayed_line;
338 int eof;
339 int diff_context;
340 int ignore_whitespace;
341 int force_text_diff;
342 struct got_repository *repo;
343 struct got_diff_line *lines;
344 size_t nlines;
345 int matched_line;
346 int selected_line;
348 /* passed from log or blame view; may be NULL */
349 struct tog_view *parent_view;
350 };
352 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
353 static volatile sig_atomic_t tog_thread_error;
355 struct tog_log_thread_args {
356 pthread_cond_t need_commits;
357 pthread_cond_t commit_loaded;
358 int commits_needed;
359 int load_all;
360 struct got_commit_graph *graph;
361 struct commit_queue *real_commits;
362 const char *in_repo_path;
363 struct got_object_id *start_id;
364 struct got_repository *repo;
365 int *pack_fds;
366 int log_complete;
367 sig_atomic_t *quit;
368 struct commit_queue_entry **first_displayed_entry;
369 struct commit_queue_entry **selected_entry;
370 int *searching;
371 int *search_next_done;
372 regex_t *regex;
373 int *limiting;
374 int limit_match;
375 regex_t *limit_regex;
376 struct commit_queue *limit_commits;
377 };
379 struct tog_log_view_state {
380 struct commit_queue *commits;
381 struct commit_queue_entry *first_displayed_entry;
382 struct commit_queue_entry *last_displayed_entry;
383 struct commit_queue_entry *selected_entry;
384 struct commit_queue real_commits;
385 int selected;
386 char *in_repo_path;
387 char *head_ref_name;
388 int log_branches;
389 struct got_repository *repo;
390 struct got_object_id *start_id;
391 sig_atomic_t quit;
392 pthread_t thread;
393 struct tog_log_thread_args thread_args;
394 struct commit_queue_entry *matched_entry;
395 struct commit_queue_entry *search_entry;
396 struct tog_colors colors;
397 int use_committer;
398 int limit_view;
399 regex_t limit_regex;
400 struct commit_queue limit_commits;
401 };
403 #define TOG_COLOR_DIFF_MINUS 1
404 #define TOG_COLOR_DIFF_PLUS 2
405 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
406 #define TOG_COLOR_DIFF_META 4
407 #define TOG_COLOR_TREE_SUBMODULE 5
408 #define TOG_COLOR_TREE_SYMLINK 6
409 #define TOG_COLOR_TREE_DIRECTORY 7
410 #define TOG_COLOR_TREE_EXECUTABLE 8
411 #define TOG_COLOR_COMMIT 9
412 #define TOG_COLOR_AUTHOR 10
413 #define TOG_COLOR_DATE 11
414 #define TOG_COLOR_REFS_HEADS 12
415 #define TOG_COLOR_REFS_TAGS 13
416 #define TOG_COLOR_REFS_REMOTES 14
417 #define TOG_COLOR_REFS_BACKUP 15
419 struct tog_blame_cb_args {
420 struct tog_blame_line *lines; /* one per line */
421 int nlines;
423 struct tog_view *view;
424 struct got_object_id *commit_id;
425 int *quit;
426 };
428 struct tog_blame_thread_args {
429 const char *path;
430 struct got_repository *repo;
431 struct tog_blame_cb_args *cb_args;
432 int *complete;
433 got_cancel_cb cancel_cb;
434 void *cancel_arg;
435 };
437 struct tog_blame {
438 FILE *f;
439 off_t filesize;
440 struct tog_blame_line *lines;
441 int nlines;
442 off_t *line_offsets;
443 pthread_t thread;
444 struct tog_blame_thread_args thread_args;
445 struct tog_blame_cb_args cb_args;
446 const char *path;
447 int *pack_fds;
448 };
450 struct tog_blame_view_state {
451 int first_displayed_line;
452 int last_displayed_line;
453 int selected_line;
454 int last_diffed_line;
455 int blame_complete;
456 int eof;
457 int done;
458 struct got_object_id_queue blamed_commits;
459 struct got_object_qid *blamed_commit;
460 char *path;
461 struct got_repository *repo;
462 struct got_object_id *commit_id;
463 struct got_object_id *id_to_log;
464 struct tog_blame blame;
465 int matched_line;
466 struct tog_colors colors;
467 };
469 struct tog_parent_tree {
470 TAILQ_ENTRY(tog_parent_tree) entry;
471 struct got_tree_object *tree;
472 struct got_tree_entry *first_displayed_entry;
473 struct got_tree_entry *selected_entry;
474 int selected;
475 };
477 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
479 struct tog_tree_view_state {
480 char *tree_label;
481 struct got_object_id *commit_id;/* commit which this tree belongs to */
482 struct got_tree_object *root; /* the commit's root tree entry */
483 struct got_tree_object *tree; /* currently displayed (sub-)tree */
484 struct got_tree_entry *first_displayed_entry;
485 struct got_tree_entry *last_displayed_entry;
486 struct got_tree_entry *selected_entry;
487 int ndisplayed, selected, show_ids;
488 struct tog_parent_trees parents; /* parent trees of current sub-tree */
489 char *head_ref_name;
490 struct got_repository *repo;
491 struct got_tree_entry *matched_entry;
492 struct tog_colors colors;
493 };
495 struct tog_reflist_entry {
496 TAILQ_ENTRY(tog_reflist_entry) entry;
497 struct got_reference *ref;
498 int idx;
499 };
501 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
503 struct tog_ref_view_state {
504 struct tog_reflist_head refs;
505 struct tog_reflist_entry *first_displayed_entry;
506 struct tog_reflist_entry *last_displayed_entry;
507 struct tog_reflist_entry *selected_entry;
508 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
509 struct got_repository *repo;
510 struct tog_reflist_entry *matched_entry;
511 struct tog_colors colors;
512 };
514 struct tog_help_view_state {
515 FILE *f;
516 off_t *line_offsets;
517 size_t nlines;
518 int lineno;
519 int first_displayed_line;
520 int last_displayed_line;
521 int eof;
522 int matched_line;
523 int selected_line;
524 int all;
525 enum tog_keymap_type type;
526 };
528 #define GENERATE_HELP \
529 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
530 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
531 KEY_("k C-p Up", "Move cursor or page up one line"), \
532 KEY_("j C-n Down", "Move cursor or page down one line"), \
533 KEY_("C-b b PgUp", "Scroll the view up one page"), \
534 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
535 KEY_("C-u u", "Scroll the view up one half page"), \
536 KEY_("C-d d", "Scroll the view down one half page"), \
537 KEY_("g", "Go to line N (default: first line)"), \
538 KEY_("Home =", "Go to the first line"), \
539 KEY_("G", "Go to line N (default: last line)"), \
540 KEY_("End *", "Go to the last line"), \
541 KEY_("l Right", "Scroll the view right"), \
542 KEY_("h Left", "Scroll the view left"), \
543 KEY_("$", "Scroll view to the rightmost position"), \
544 KEY_("0", "Scroll view to the leftmost position"), \
545 KEY_("-", "Decrease size of the focussed split"), \
546 KEY_("+", "Increase size of the focussed split"), \
547 KEY_("Tab", "Switch focus between views"), \
548 KEY_("F", "Toggle fullscreen mode"), \
549 KEY_("S", "Switch split-screen layout"), \
550 KEY_("/", "Open prompt to enter search term"), \
551 KEY_("n", "Find next line/token matching the current search term"), \
552 KEY_("N", "Find previous line/token matching the current search term"),\
553 KEY_("q", "Quit the focussed view; Quit help screen"), \
554 KEY_("Q", "Quit tog"), \
556 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
557 KEY_("< ,", "Move cursor up one commit"), \
558 KEY_("> .", "Move cursor down one commit"), \
559 KEY_("Enter", "Open diff view of the selected commit"), \
560 KEY_("B", "Reload the log view and toggle display of merged commits"), \
561 KEY_("R", "Open ref view of all repository references"), \
562 KEY_("T", "Display tree view of the repository from the selected" \
563 " commit"), \
564 KEY_("@", "Toggle between displaying author and committer name"), \
565 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
566 KEY_("C-g Backspace", "Cancel current search or log operation"), \
567 KEY_("C-l", "Reload the log view with new commits in the repository"), \
569 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
570 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
571 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
572 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
573 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
574 " data"), \
575 KEY_("(", "Go to the previous file in the diff"), \
576 KEY_(")", "Go to the next file in the diff"), \
577 KEY_("{", "Go to the previous hunk in the diff"), \
578 KEY_("}", "Go to the next hunk in the diff"), \
579 KEY_("[", "Decrease the number of context lines"), \
580 KEY_("]", "Increase the number of context lines"), \
581 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
583 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
584 KEY_("Enter", "Display diff view of the selected line's commit"), \
585 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
586 KEY_("L", "Open log view for the currently selected annotated line"), \
587 KEY_("C", "Reload view with the previously blamed commit"), \
588 KEY_("c", "Reload view with the version of the file found in the" \
589 " selected line's commit"), \
590 KEY_("p", "Reload view with the version of the file found in the" \
591 " selected line's parent commit"), \
593 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
594 KEY_("Enter", "Enter selected directory or open blame view of the" \
595 " selected file"), \
596 KEY_("L", "Open log view for the selected entry"), \
597 KEY_("R", "Open ref view of all repository references"), \
598 KEY_("i", "Show object IDs for all tree entries"), \
599 KEY_("Backspace", "Return to the parent directory"), \
601 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
602 KEY_("Enter", "Display log view of the selected reference"), \
603 KEY_("T", "Display tree view of the selected reference"), \
604 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
605 KEY_("m", "Toggle display of last modified date for each reference"), \
606 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
607 KEY_("C-l", "Reload view with all repository references")
609 struct tog_key_map {
610 const char *keys;
611 const char *info;
612 enum tog_keymap_type type;
613 };
615 /* curses io for tog regress */
616 struct tog_io {
617 FILE *cin;
618 FILE *cout;
619 FILE *f;
620 int wait_for_ui;
621 } tog_io;
622 static int using_mock_io;
624 #define TOG_SCREEN_DUMP "SCREENDUMP"
625 #define TOG_SCREEN_DUMP_LEN (sizeof(TOG_SCREEN_DUMP) - 1)
626 #define TOG_KEY_SCRDUMP SHRT_MIN
628 /*
629 * We implement two types of views: parent views and child views.
631 * The 'Tab' key switches focus between a parent view and its child view.
632 * Child views are shown side-by-side to their parent view, provided
633 * there is enough screen estate.
635 * When a new view is opened from within a parent view, this new view
636 * becomes a child view of the parent view, replacing any existing child.
638 * When a new view is opened from within a child view, this new view
639 * becomes a parent view which will obscure the views below until the
640 * user quits the new parent view by typing 'q'.
642 * This list of views contains parent views only.
643 * Child views are only pointed to by their parent view.
644 */
645 TAILQ_HEAD(tog_view_list_head, tog_view);
647 struct tog_view {
648 TAILQ_ENTRY(tog_view) entry;
649 WINDOW *window;
650 PANEL *panel;
651 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
652 int resized_y, resized_x; /* begin_y/x based on user resizing */
653 int maxx, x; /* max column and current start column */
654 int lines, cols; /* copies of LINES and COLS */
655 int nscrolled, offset; /* lines scrolled and hsplit line offset */
656 int gline, hiline; /* navigate to and highlight this nG line */
657 int ch, count; /* current keymap and count prefix */
658 int resized; /* set when in a resize event */
659 int focussed; /* Only set on one parent or child view at a time. */
660 int dying;
661 struct tog_view *parent;
662 struct tog_view *child;
664 /*
665 * This flag is initially set on parent views when a new child view
666 * is created. It gets toggled when the 'Tab' key switches focus
667 * between parent and child.
668 * The flag indicates whether focus should be passed on to our child
669 * view if this parent view gets picked for focus after another parent
670 * view was closed. This prevents child views from losing focus in such
671 * situations.
672 */
673 int focus_child;
675 enum tog_view_mode mode;
676 /* type-specific state */
677 enum tog_view_type type;
678 union {
679 struct tog_diff_view_state diff;
680 struct tog_log_view_state log;
681 struct tog_blame_view_state blame;
682 struct tog_tree_view_state tree;
683 struct tog_ref_view_state ref;
684 struct tog_help_view_state help;
685 } state;
687 const struct got_error *(*show)(struct tog_view *);
688 const struct got_error *(*input)(struct tog_view **,
689 struct tog_view *, int);
690 const struct got_error *(*reset)(struct tog_view *);
691 const struct got_error *(*resize)(struct tog_view *, int);
692 const struct got_error *(*close)(struct tog_view *);
694 const struct got_error *(*search_start)(struct tog_view *);
695 const struct got_error *(*search_next)(struct tog_view *);
696 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
697 int **, int **, int **, int **);
698 int search_started;
699 int searching;
700 #define TOG_SEARCH_FORWARD 1
701 #define TOG_SEARCH_BACKWARD 2
702 int search_next_done;
703 #define TOG_SEARCH_HAVE_MORE 1
704 #define TOG_SEARCH_NO_MORE 2
705 #define TOG_SEARCH_HAVE_NONE 3
706 regex_t regex;
707 regmatch_t regmatch;
708 const char *action;
709 };
711 static const struct got_error *open_diff_view(struct tog_view *,
712 struct got_object_id *, struct got_object_id *,
713 const char *, const char *, int, int, int, struct tog_view *,
714 struct got_repository *);
715 static const struct got_error *show_diff_view(struct tog_view *);
716 static const struct got_error *input_diff_view(struct tog_view **,
717 struct tog_view *, int);
718 static const struct got_error *reset_diff_view(struct tog_view *);
719 static const struct got_error* close_diff_view(struct tog_view *);
720 static const struct got_error *search_start_diff_view(struct tog_view *);
721 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
722 size_t *, int **, int **, int **, int **);
723 static const struct got_error *search_next_view_match(struct tog_view *);
725 static const struct got_error *open_log_view(struct tog_view *,
726 struct got_object_id *, struct got_repository *,
727 const char *, const char *, int);
728 static const struct got_error * show_log_view(struct tog_view *);
729 static const struct got_error *input_log_view(struct tog_view **,
730 struct tog_view *, int);
731 static const struct got_error *resize_log_view(struct tog_view *, int);
732 static const struct got_error *close_log_view(struct tog_view *);
733 static const struct got_error *search_start_log_view(struct tog_view *);
734 static const struct got_error *search_next_log_view(struct tog_view *);
736 static const struct got_error *open_blame_view(struct tog_view *, char *,
737 struct got_object_id *, struct got_repository *);
738 static const struct got_error *show_blame_view(struct tog_view *);
739 static const struct got_error *input_blame_view(struct tog_view **,
740 struct tog_view *, int);
741 static const struct got_error *reset_blame_view(struct tog_view *);
742 static const struct got_error *close_blame_view(struct tog_view *);
743 static const struct got_error *search_start_blame_view(struct tog_view *);
744 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
745 size_t *, int **, int **, int **, int **);
747 static const struct got_error *open_tree_view(struct tog_view *,
748 struct got_object_id *, const char *, struct got_repository *);
749 static const struct got_error *show_tree_view(struct tog_view *);
750 static const struct got_error *input_tree_view(struct tog_view **,
751 struct tog_view *, int);
752 static const struct got_error *close_tree_view(struct tog_view *);
753 static const struct got_error *search_start_tree_view(struct tog_view *);
754 static const struct got_error *search_next_tree_view(struct tog_view *);
756 static const struct got_error *open_ref_view(struct tog_view *,
757 struct got_repository *);
758 static const struct got_error *show_ref_view(struct tog_view *);
759 static const struct got_error *input_ref_view(struct tog_view **,
760 struct tog_view *, int);
761 static const struct got_error *close_ref_view(struct tog_view *);
762 static const struct got_error *search_start_ref_view(struct tog_view *);
763 static const struct got_error *search_next_ref_view(struct tog_view *);
765 static const struct got_error *open_help_view(struct tog_view *,
766 struct tog_view *);
767 static const struct got_error *show_help_view(struct tog_view *);
768 static const struct got_error *input_help_view(struct tog_view **,
769 struct tog_view *, int);
770 static const struct got_error *reset_help_view(struct tog_view *);
771 static const struct got_error* close_help_view(struct tog_view *);
772 static const struct got_error *search_start_help_view(struct tog_view *);
773 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
774 size_t *, int **, int **, int **, int **);
776 static volatile sig_atomic_t tog_sigwinch_received;
777 static volatile sig_atomic_t tog_sigpipe_received;
778 static volatile sig_atomic_t tog_sigcont_received;
779 static volatile sig_atomic_t tog_sigint_received;
780 static volatile sig_atomic_t tog_sigterm_received;
782 static void
783 tog_sigwinch(int signo)
785 tog_sigwinch_received = 1;
788 static void
789 tog_sigpipe(int signo)
791 tog_sigpipe_received = 1;
794 static void
795 tog_sigcont(int signo)
797 tog_sigcont_received = 1;
800 static void
801 tog_sigint(int signo)
803 tog_sigint_received = 1;
806 static void
807 tog_sigterm(int signo)
809 tog_sigterm_received = 1;
812 static int
813 tog_fatal_signal_received(void)
815 return (tog_sigpipe_received ||
816 tog_sigint_received || tog_sigterm_received);
819 static const struct got_error *
820 view_close(struct tog_view *view)
822 const struct got_error *err = NULL, *child_err = NULL;
824 if (view->child) {
825 child_err = view_close(view->child);
826 view->child = NULL;
828 if (view->close)
829 err = view->close(view);
830 if (view->panel)
831 del_panel(view->panel);
832 if (view->window)
833 delwin(view->window);
834 free(view);
835 return err ? err : child_err;
838 static struct tog_view *
839 view_open(int nlines, int ncols, int begin_y, int begin_x,
840 enum tog_view_type type)
842 struct tog_view *view = calloc(1, sizeof(*view));
844 if (view == NULL)
845 return NULL;
847 view->type = type;
848 view->lines = LINES;
849 view->cols = COLS;
850 view->nlines = nlines ? nlines : LINES - begin_y;
851 view->ncols = ncols ? ncols : COLS - begin_x;
852 view->begin_y = begin_y;
853 view->begin_x = begin_x;
854 view->window = newwin(nlines, ncols, begin_y, begin_x);
855 if (view->window == NULL) {
856 view_close(view);
857 return NULL;
859 view->panel = new_panel(view->window);
860 if (view->panel == NULL ||
861 set_panel_userptr(view->panel, view) != OK) {
862 view_close(view);
863 return NULL;
866 keypad(view->window, TRUE);
867 return view;
870 static int
871 view_split_begin_x(int begin_x)
873 if (begin_x > 0 || COLS < 120)
874 return 0;
875 return (COLS - MAX(COLS / 2, 80));
878 /* XXX Stub till we decide what to do. */
879 static int
880 view_split_begin_y(int lines)
882 return lines * HSPLIT_SCALE;
885 static const struct got_error *view_resize(struct tog_view *);
887 static const struct got_error *
888 view_splitscreen(struct tog_view *view)
890 const struct got_error *err = NULL;
892 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
893 if (view->resized_y && view->resized_y < view->lines)
894 view->begin_y = view->resized_y;
895 else
896 view->begin_y = view_split_begin_y(view->nlines);
897 view->begin_x = 0;
898 } else if (!view->resized) {
899 if (view->resized_x && view->resized_x < view->cols - 1 &&
900 view->cols > 119)
901 view->begin_x = view->resized_x;
902 else
903 view->begin_x = view_split_begin_x(0);
904 view->begin_y = 0;
906 view->nlines = LINES - view->begin_y;
907 view->ncols = COLS - view->begin_x;
908 view->lines = LINES;
909 view->cols = COLS;
910 err = view_resize(view);
911 if (err)
912 return err;
914 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
915 view->parent->nlines = view->begin_y;
917 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
918 return got_error_from_errno("mvwin");
920 return NULL;
923 static const struct got_error *
924 view_fullscreen(struct tog_view *view)
926 const struct got_error *err = NULL;
928 view->begin_x = 0;
929 view->begin_y = view->resized ? view->begin_y : 0;
930 view->nlines = view->resized ? view->nlines : LINES;
931 view->ncols = COLS;
932 view->lines = LINES;
933 view->cols = COLS;
934 err = view_resize(view);
935 if (err)
936 return err;
938 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
939 return got_error_from_errno("mvwin");
941 return NULL;
944 static int
945 view_is_parent_view(struct tog_view *view)
947 return view->parent == NULL;
950 static int
951 view_is_splitscreen(struct tog_view *view)
953 return view->begin_x > 0 || view->begin_y > 0;
956 static int
957 view_is_fullscreen(struct tog_view *view)
959 return view->nlines == LINES && view->ncols == COLS;
962 static int
963 view_is_hsplit_top(struct tog_view *view)
965 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
966 view_is_splitscreen(view->child);
969 static void
970 view_border(struct tog_view *view)
972 PANEL *panel;
973 const struct tog_view *view_above;
975 if (view->parent)
976 return view_border(view->parent);
978 panel = panel_above(view->panel);
979 if (panel == NULL)
980 return;
982 view_above = panel_userptr(panel);
983 if (view->mode == TOG_VIEW_SPLIT_HRZN)
984 mvwhline(view->window, view_above->begin_y - 1,
985 view->begin_x, got_locale_is_utf8() ?
986 ACS_HLINE : '-', view->ncols);
987 else
988 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
989 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
992 static const struct got_error *view_init_hsplit(struct tog_view *, int);
993 static const struct got_error *request_log_commits(struct tog_view *);
994 static const struct got_error *offset_selection_down(struct tog_view *);
995 static void offset_selection_up(struct tog_view *);
996 static void view_get_split(struct tog_view *, int *, int *);
998 static const struct got_error *
999 view_resize(struct tog_view *view)
1001 const struct got_error *err = NULL;
1002 int dif, nlines, ncols;
1004 dif = LINES - view->lines; /* line difference */
1006 if (view->lines > LINES)
1007 nlines = view->nlines - (view->lines - LINES);
1008 else
1009 nlines = view->nlines + (LINES - view->lines);
1010 if (view->cols > COLS)
1011 ncols = view->ncols - (view->cols - COLS);
1012 else
1013 ncols = view->ncols + (COLS - view->cols);
1015 if (view->child) {
1016 int hs = view->child->begin_y;
1018 if (!view_is_fullscreen(view))
1019 view->child->begin_x = view_split_begin_x(view->begin_x);
1020 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1021 view->child->begin_x == 0) {
1022 ncols = COLS;
1024 view_fullscreen(view->child);
1025 if (view->child->focussed)
1026 show_panel(view->child->panel);
1027 else
1028 show_panel(view->panel);
1029 } else {
1030 ncols = view->child->begin_x;
1032 view_splitscreen(view->child);
1033 show_panel(view->child->panel);
1036 * XXX This is ugly and needs to be moved into the above
1037 * logic but "works" for now and my attempts at moving it
1038 * break either 'tab' or 'F' key maps in horizontal splits.
1040 if (hs) {
1041 err = view_splitscreen(view->child);
1042 if (err)
1043 return err;
1044 if (dif < 0) { /* top split decreased */
1045 err = offset_selection_down(view);
1046 if (err)
1047 return err;
1049 view_border(view);
1050 update_panels();
1051 doupdate();
1052 show_panel(view->child->panel);
1053 nlines = view->nlines;
1055 } else if (view->parent == NULL)
1056 ncols = COLS;
1058 if (view->resize && dif > 0) {
1059 err = view->resize(view, dif);
1060 if (err)
1061 return err;
1064 if (wresize(view->window, nlines, ncols) == ERR)
1065 return got_error_from_errno("wresize");
1066 if (replace_panel(view->panel, view->window) == ERR)
1067 return got_error_from_errno("replace_panel");
1068 wclear(view->window);
1070 view->nlines = nlines;
1071 view->ncols = ncols;
1072 view->lines = LINES;
1073 view->cols = COLS;
1075 return NULL;
1078 static const struct got_error *
1079 resize_log_view(struct tog_view *view, int increase)
1081 struct tog_log_view_state *s = &view->state.log;
1082 const struct got_error *err = NULL;
1083 int n = 0;
1085 if (s->selected_entry)
1086 n = s->selected_entry->idx + view->lines - s->selected;
1089 * Request commits to account for the increased
1090 * height so we have enough to populate the view.
1092 if (s->commits->ncommits < n) {
1093 view->nscrolled = n - s->commits->ncommits + increase + 1;
1094 err = request_log_commits(view);
1097 return err;
1100 static void
1101 view_adjust_offset(struct tog_view *view, int n)
1103 if (n == 0)
1104 return;
1106 if (view->parent && view->parent->offset) {
1107 if (view->parent->offset + n >= 0)
1108 view->parent->offset += n;
1109 else
1110 view->parent->offset = 0;
1111 } else if (view->offset) {
1112 if (view->offset - n >= 0)
1113 view->offset -= n;
1114 else
1115 view->offset = 0;
1119 static const struct got_error *
1120 view_resize_split(struct tog_view *view, int resize)
1122 const struct got_error *err = NULL;
1123 struct tog_view *v = NULL;
1125 if (view->parent)
1126 v = view->parent;
1127 else
1128 v = view;
1130 if (!v->child || !view_is_splitscreen(v->child))
1131 return NULL;
1133 v->resized = v->child->resized = resize; /* lock for resize event */
1135 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1136 if (v->child->resized_y)
1137 v->child->begin_y = v->child->resized_y;
1138 if (view->parent)
1139 v->child->begin_y -= resize;
1140 else
1141 v->child->begin_y += resize;
1142 if (v->child->begin_y < 3) {
1143 view->count = 0;
1144 v->child->begin_y = 3;
1145 } else if (v->child->begin_y > LINES - 1) {
1146 view->count = 0;
1147 v->child->begin_y = LINES - 1;
1149 v->ncols = COLS;
1150 v->child->ncols = COLS;
1151 view_adjust_offset(view, resize);
1152 err = view_init_hsplit(v, v->child->begin_y);
1153 if (err)
1154 return err;
1155 v->child->resized_y = v->child->begin_y;
1156 } else {
1157 if (v->child->resized_x)
1158 v->child->begin_x = v->child->resized_x;
1159 if (view->parent)
1160 v->child->begin_x -= resize;
1161 else
1162 v->child->begin_x += resize;
1163 if (v->child->begin_x < 11) {
1164 view->count = 0;
1165 v->child->begin_x = 11;
1166 } else if (v->child->begin_x > COLS - 1) {
1167 view->count = 0;
1168 v->child->begin_x = COLS - 1;
1170 v->child->resized_x = v->child->begin_x;
1173 v->child->mode = v->mode;
1174 v->child->nlines = v->lines - v->child->begin_y;
1175 v->child->ncols = v->cols - v->child->begin_x;
1176 v->focus_child = 1;
1178 err = view_fullscreen(v);
1179 if (err)
1180 return err;
1181 err = view_splitscreen(v->child);
1182 if (err)
1183 return err;
1185 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1186 err = offset_selection_down(v->child);
1187 if (err)
1188 return err;
1191 if (v->resize)
1192 err = v->resize(v, 0);
1193 else if (v->child->resize)
1194 err = v->child->resize(v->child, 0);
1196 v->resized = v->child->resized = 0;
1198 return err;
1201 static void
1202 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1204 struct tog_view *v = src->child ? src->child : src;
1206 dst->resized_x = v->resized_x;
1207 dst->resized_y = v->resized_y;
1210 static const struct got_error *
1211 view_close_child(struct tog_view *view)
1213 const struct got_error *err = NULL;
1215 if (view->child == NULL)
1216 return NULL;
1218 err = view_close(view->child);
1219 view->child = NULL;
1220 return err;
1223 static const struct got_error *
1224 view_set_child(struct tog_view *view, struct tog_view *child)
1226 const struct got_error *err = NULL;
1228 view->child = child;
1229 child->parent = view;
1231 err = view_resize(view);
1232 if (err)
1233 return err;
1235 if (view->child->resized_x || view->child->resized_y)
1236 err = view_resize_split(view, 0);
1238 return err;
1241 static const struct got_error *view_dispatch_request(struct tog_view **,
1242 struct tog_view *, enum tog_view_type, int, int);
1244 static const struct got_error *
1245 view_request_new(struct tog_view **requested, struct tog_view *view,
1246 enum tog_view_type request)
1248 struct tog_view *new_view = NULL;
1249 const struct got_error *err;
1250 int y = 0, x = 0;
1252 *requested = NULL;
1254 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1255 view_get_split(view, &y, &x);
1257 err = view_dispatch_request(&new_view, view, request, y, x);
1258 if (err)
1259 return err;
1261 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1262 request != TOG_VIEW_HELP) {
1263 err = view_init_hsplit(view, y);
1264 if (err)
1265 return err;
1268 view->focussed = 0;
1269 new_view->focussed = 1;
1270 new_view->mode = view->mode;
1271 new_view->nlines = request == TOG_VIEW_HELP ?
1272 view->lines : view->lines - y;
1274 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1275 view_transfer_size(new_view, view);
1276 err = view_close_child(view);
1277 if (err)
1278 return err;
1279 err = view_set_child(view, new_view);
1280 if (err)
1281 return err;
1282 view->focus_child = 1;
1283 } else
1284 *requested = new_view;
1286 return NULL;
1289 static void
1290 tog_resizeterm(void)
1292 int cols, lines;
1293 struct winsize size;
1295 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1296 cols = 80; /* Default */
1297 lines = 24;
1298 } else {
1299 cols = size.ws_col;
1300 lines = size.ws_row;
1302 resize_term(lines, cols);
1305 static const struct got_error *
1306 view_search_start(struct tog_view *view, int fast_refresh)
1308 const struct got_error *err = NULL;
1309 struct tog_view *v = view;
1310 char pattern[1024];
1311 int ret;
1313 if (view->search_started) {
1314 regfree(&view->regex);
1315 view->searching = 0;
1316 memset(&view->regmatch, 0, sizeof(view->regmatch));
1318 view->search_started = 0;
1320 if (view->nlines < 1)
1321 return NULL;
1323 if (view_is_hsplit_top(view))
1324 v = view->child;
1325 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1326 v = view->parent;
1328 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1329 wclrtoeol(v->window);
1331 nodelay(v->window, FALSE); /* block for search term input */
1332 nocbreak();
1333 echo();
1334 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1335 wrefresh(v->window);
1336 cbreak();
1337 noecho();
1338 nodelay(v->window, TRUE);
1339 if (!fast_refresh && !using_mock_io)
1340 halfdelay(10);
1341 if (ret == ERR)
1342 return NULL;
1344 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1345 err = view->search_start(view);
1346 if (err) {
1347 regfree(&view->regex);
1348 return err;
1350 view->search_started = 1;
1351 view->searching = TOG_SEARCH_FORWARD;
1352 view->search_next_done = 0;
1353 view->search_next(view);
1356 return NULL;
1359 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1360 static const struct got_error *
1361 switch_split(struct tog_view *view)
1363 const struct got_error *err = NULL;
1364 struct tog_view *v = NULL;
1366 if (view->parent)
1367 v = view->parent;
1368 else
1369 v = view;
1371 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1372 v->mode = TOG_VIEW_SPLIT_VERT;
1373 else
1374 v->mode = TOG_VIEW_SPLIT_HRZN;
1376 if (!v->child)
1377 return NULL;
1378 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1379 v->mode = TOG_VIEW_SPLIT_NONE;
1381 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1382 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1383 v->child->begin_y = v->child->resized_y;
1384 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1385 v->child->begin_x = v->child->resized_x;
1388 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1389 v->ncols = COLS;
1390 v->child->ncols = COLS;
1391 v->child->nscrolled = LINES - v->child->nlines;
1393 err = view_init_hsplit(v, v->child->begin_y);
1394 if (err)
1395 return err;
1397 v->child->mode = v->mode;
1398 v->child->nlines = v->lines - v->child->begin_y;
1399 v->focus_child = 1;
1401 err = view_fullscreen(v);
1402 if (err)
1403 return err;
1404 err = view_splitscreen(v->child);
1405 if (err)
1406 return err;
1408 if (v->mode == TOG_VIEW_SPLIT_NONE)
1409 v->mode = TOG_VIEW_SPLIT_VERT;
1410 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1411 err = offset_selection_down(v);
1412 if (err)
1413 return err;
1414 err = offset_selection_down(v->child);
1415 if (err)
1416 return err;
1417 } else {
1418 offset_selection_up(v);
1419 offset_selection_up(v->child);
1421 if (v->resize)
1422 err = v->resize(v, 0);
1423 else if (v->child->resize)
1424 err = v->child->resize(v->child, 0);
1426 return err;
1430 * Strip trailing whitespace from str starting at byte *n;
1431 * if *n < 0, use strlen(str). Return new str length in *n.
1433 static void
1434 strip_trailing_ws(char *str, int *n)
1436 size_t x = *n;
1438 if (str == NULL || *str == '\0')
1439 return;
1441 if (x < 0)
1442 x = strlen(str);
1444 while (x-- > 0 && isspace((unsigned char)str[x]))
1445 str[x] = '\0';
1447 *n = x + 1;
1451 * Extract visible substring of line y from the curses screen
1452 * and strip trailing whitespace. If vline is set and locale is
1453 * UTF-8, overwrite line[vline] with '|' because the ACS_VLINE
1454 * character is written out as 'x'. Write the line to file f.
1456 static const struct got_error *
1457 view_write_line(FILE *f, int y, int vline)
1459 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1460 int r, w;
1462 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1463 if (r == ERR)
1464 return got_error_fmt(GOT_ERR_RANGE,
1465 "failed to extract line %d", y);
1468 * In some views, lines are padded with blanks to COLS width.
1469 * Strip them so we can diff without the -b flag when testing.
1471 strip_trailing_ws(line, &r);
1473 if (vline > 0 && got_locale_is_utf8())
1474 line[vline] = '|';
1476 w = fprintf(f, "%s\n", line);
1477 if (w != r + 1) /* \n */
1478 return got_ferror(f, GOT_ERR_IO);
1480 return NULL;
1484 * Capture the visible curses screen by writing each line to the
1485 * file at the path set via the TOG_SCR_DUMP environment variable.
1487 static const struct got_error *
1488 screendump(struct tog_view *view)
1490 const struct got_error *err;
1491 FILE *f = NULL;
1492 const char *path;
1493 int i;
1495 path = getenv("TOG_SCR_DUMP");
1496 if (path == NULL || *path == '\0')
1497 return got_error_msg(GOT_ERR_BAD_PATH,
1498 "TOG_SCR_DUMP path not set to capture screen dump");
1499 f = fopen(path, "wex");
1500 if (f == NULL)
1501 return got_error_from_errno_fmt("fopen: %s", path);
1503 if ((view->child && view->child->begin_x) ||
1504 (view->parent && view->begin_x)) {
1505 int ncols = view->child ? view->ncols : view->parent->ncols;
1507 /* vertical splitscreen */
1508 for (i = 0; i < view->nlines; ++i) {
1509 err = view_write_line(f, i, ncols - 1);
1510 if (err)
1511 goto done;
1513 } else {
1514 int hline = 0;
1516 /* fullscreen or horizontal splitscreen */
1517 if ((view->child && view->child->begin_y) ||
1518 (view->parent && view->begin_y)) /* hsplit */
1519 hline = view->child ?
1520 view->child->begin_y : view->begin_y;
1522 for (i = 0; i < view->lines; i++) {
1523 if (hline && got_locale_is_utf8() && i == hline - 1) {
1524 int c;
1526 /* ACS_HLINE writes out as 'q', overwrite it */
1527 for (c = 0; c < view->cols; ++c)
1528 fputc('-', f);
1529 fputc('\n', f);
1530 continue;
1533 err = view_write_line(f, i, 0);
1534 if (err)
1535 goto done;
1539 done:
1540 if (f && fclose(f) == EOF && err == NULL)
1541 err = got_ferror(f, GOT_ERR_IO);
1542 return err;
1546 * Compute view->count from numeric input. Assign total to view->count and
1547 * return first non-numeric key entered.
1549 static int
1550 get_compound_key(struct tog_view *view, int c)
1552 struct tog_view *v = view;
1553 int x, n = 0;
1555 if (view_is_hsplit_top(view))
1556 v = view->child;
1557 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1558 v = view->parent;
1560 view->count = 0;
1561 cbreak(); /* block for input */
1562 nodelay(view->window, FALSE);
1563 wmove(v->window, v->nlines - 1, 0);
1564 wclrtoeol(v->window);
1565 waddch(v->window, ':');
1567 do {
1568 x = getcurx(v->window);
1569 if (x != ERR && x < view->ncols) {
1570 waddch(v->window, c);
1571 wrefresh(v->window);
1575 * Don't overflow. Max valid request should be the greatest
1576 * between the longest and total lines; cap at 10 million.
1578 if (n >= 9999999)
1579 n = 9999999;
1580 else
1581 n = n * 10 + (c - '0');
1582 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1584 if (c == 'G' || c == 'g') { /* nG key map */
1585 view->gline = view->hiline = n;
1586 n = 0;
1587 c = 0;
1590 /* Massage excessive or inapplicable values at the input handler. */
1591 view->count = n;
1593 return c;
1596 static void
1597 action_report(struct tog_view *view)
1599 struct tog_view *v = view;
1601 if (view_is_hsplit_top(view))
1602 v = view->child;
1603 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1604 v = view->parent;
1606 wmove(v->window, v->nlines - 1, 0);
1607 wclrtoeol(v->window);
1608 wprintw(v->window, ":%s", view->action);
1609 wrefresh(v->window);
1612 * Clear action status report. Only clear in blame view
1613 * once annotating is complete, otherwise it's too fast.
1615 if (view->type == TOG_VIEW_BLAME) {
1616 if (view->state.blame.blame_complete)
1617 view->action = NULL;
1618 } else
1619 view->action = NULL;
1623 * Read the next line from the test script and assign
1624 * key instruction to *ch. If at EOF, set the *done flag.
1626 static const struct got_error *
1627 tog_read_script_key(FILE *script, int *ch, int *done)
1629 const struct got_error *err = NULL;
1630 char *line = NULL;
1631 size_t linesz = 0;
1633 *ch = -1;
1635 if (tog_io.wait_for_ui)
1636 goto done;
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;
1647 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1648 tog_io.wait_for_ui = 1;
1649 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1650 *ch = KEY_ENTER;
1651 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1652 *ch = KEY_RIGHT;
1653 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1654 *ch = KEY_LEFT;
1655 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1656 *ch = KEY_DOWN;
1657 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1658 *ch = KEY_UP;
1659 else if (strncasecmp(line, TOG_SCREEN_DUMP, TOG_SCREEN_DUMP_LEN) == 0)
1660 *ch = TOG_KEY_SCRDUMP;
1661 else
1662 *ch = *line;
1664 done:
1665 free(line);
1666 return err;
1669 static const struct got_error *
1670 view_input(struct tog_view **new, int *done, struct tog_view *view,
1671 struct tog_view_list_head *views, int fast_refresh)
1673 const struct got_error *err = NULL;
1674 struct tog_view *v;
1675 int ch, errcode;
1677 *new = NULL;
1679 if (view->action)
1680 action_report(view);
1682 /* Clear "no matches" indicator. */
1683 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1684 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1685 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1686 view->count = 0;
1689 if (view->searching && !view->search_next_done) {
1690 errcode = pthread_mutex_unlock(&tog_mutex);
1691 if (errcode)
1692 return got_error_set_errno(errcode,
1693 "pthread_mutex_unlock");
1694 sched_yield();
1695 errcode = pthread_mutex_lock(&tog_mutex);
1696 if (errcode)
1697 return got_error_set_errno(errcode,
1698 "pthread_mutex_lock");
1699 view->search_next(view);
1700 return NULL;
1703 /* Allow threads to make progress while we are waiting for input. */
1704 errcode = pthread_mutex_unlock(&tog_mutex);
1705 if (errcode)
1706 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1708 if (using_mock_io) {
1709 err = tog_read_script_key(tog_io.f, &ch, done);
1710 if (err) {
1711 errcode = pthread_mutex_lock(&tog_mutex);
1712 return err;
1714 } else if (view->count && --view->count) {
1715 cbreak();
1716 nodelay(view->window, TRUE);
1717 ch = wgetch(view->window);
1718 /* let C-g or backspace abort unfinished count */
1719 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1720 view->count = 0;
1721 else
1722 ch = view->ch;
1723 } else {
1724 ch = wgetch(view->window);
1725 if (ch >= '1' && ch <= '9')
1726 view->ch = ch = get_compound_key(view, ch);
1728 if (view->hiline && ch != ERR && ch != 0)
1729 view->hiline = 0; /* key pressed, clear line highlight */
1730 nodelay(view->window, TRUE);
1731 errcode = pthread_mutex_lock(&tog_mutex);
1732 if (errcode)
1733 return got_error_set_errno(errcode, "pthread_mutex_lock");
1735 if (tog_sigwinch_received || tog_sigcont_received) {
1736 tog_resizeterm();
1737 tog_sigwinch_received = 0;
1738 tog_sigcont_received = 0;
1739 TAILQ_FOREACH(v, views, entry) {
1740 err = view_resize(v);
1741 if (err)
1742 return err;
1743 err = v->input(new, v, KEY_RESIZE);
1744 if (err)
1745 return err;
1746 if (v->child) {
1747 err = view_resize(v->child);
1748 if (err)
1749 return err;
1750 err = v->child->input(new, v->child,
1751 KEY_RESIZE);
1752 if (err)
1753 return err;
1754 if (v->child->resized_x || v->child->resized_y) {
1755 err = view_resize_split(v, 0);
1756 if (err)
1757 return err;
1763 switch (ch) {
1764 case '?':
1765 case 'H':
1766 case KEY_F(1):
1767 if (view->type == TOG_VIEW_HELP)
1768 err = view->reset(view);
1769 else
1770 err = view_request_new(new, view, TOG_VIEW_HELP);
1771 break;
1772 case '\t':
1773 view->count = 0;
1774 if (view->child) {
1775 view->focussed = 0;
1776 view->child->focussed = 1;
1777 view->focus_child = 1;
1778 } else if (view->parent) {
1779 view->focussed = 0;
1780 view->parent->focussed = 1;
1781 view->parent->focus_child = 0;
1782 if (!view_is_splitscreen(view)) {
1783 if (view->parent->resize) {
1784 err = view->parent->resize(view->parent,
1785 0);
1786 if (err)
1787 return err;
1789 offset_selection_up(view->parent);
1790 err = view_fullscreen(view->parent);
1791 if (err)
1792 return err;
1795 break;
1796 case 'q':
1797 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1798 if (view->parent->resize) {
1799 /* might need more commits to fill fullscreen */
1800 err = view->parent->resize(view->parent, 0);
1801 if (err)
1802 break;
1804 offset_selection_up(view->parent);
1806 err = view->input(new, view, ch);
1807 view->dying = 1;
1808 break;
1809 case 'Q':
1810 *done = 1;
1811 break;
1812 case 'F':
1813 view->count = 0;
1814 if (view_is_parent_view(view)) {
1815 if (view->child == NULL)
1816 break;
1817 if (view_is_splitscreen(view->child)) {
1818 view->focussed = 0;
1819 view->child->focussed = 1;
1820 err = view_fullscreen(view->child);
1821 } else {
1822 err = view_splitscreen(view->child);
1823 if (!err)
1824 err = view_resize_split(view, 0);
1826 if (err)
1827 break;
1828 err = view->child->input(new, view->child,
1829 KEY_RESIZE);
1830 } else {
1831 if (view_is_splitscreen(view)) {
1832 view->parent->focussed = 0;
1833 view->focussed = 1;
1834 err = view_fullscreen(view);
1835 } else {
1836 err = view_splitscreen(view);
1837 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1838 err = view_resize(view->parent);
1839 if (!err)
1840 err = view_resize_split(view, 0);
1842 if (err)
1843 break;
1844 err = view->input(new, view, KEY_RESIZE);
1846 if (err)
1847 break;
1848 if (view->resize) {
1849 err = view->resize(view, 0);
1850 if (err)
1851 break;
1853 if (view->parent)
1854 err = offset_selection_down(view->parent);
1855 if (!err)
1856 err = offset_selection_down(view);
1857 break;
1858 case 'S':
1859 view->count = 0;
1860 err = switch_split(view);
1861 break;
1862 case '-':
1863 err = view_resize_split(view, -1);
1864 break;
1865 case '+':
1866 err = view_resize_split(view, 1);
1867 break;
1868 case KEY_RESIZE:
1869 break;
1870 case '/':
1871 view->count = 0;
1872 if (view->search_start)
1873 view_search_start(view, fast_refresh);
1874 else
1875 err = view->input(new, view, ch);
1876 break;
1877 case 'N':
1878 case 'n':
1879 if (view->search_started && view->search_next) {
1880 view->searching = (ch == 'n' ?
1881 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1882 view->search_next_done = 0;
1883 view->search_next(view);
1884 } else
1885 err = view->input(new, view, ch);
1886 break;
1887 case 'A':
1888 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1889 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1890 view->action = "Patience diff algorithm";
1891 } else {
1892 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1893 view->action = "Myers diff algorithm";
1895 TAILQ_FOREACH(v, views, entry) {
1896 if (v->reset) {
1897 err = v->reset(v);
1898 if (err)
1899 return err;
1901 if (v->child && v->child->reset) {
1902 err = v->child->reset(v->child);
1903 if (err)
1904 return err;
1907 break;
1908 case TOG_KEY_SCRDUMP:
1909 err = screendump(view);
1910 break;
1911 default:
1912 err = view->input(new, view, ch);
1913 break;
1916 return err;
1919 static int
1920 view_needs_focus_indication(struct tog_view *view)
1922 if (view_is_parent_view(view)) {
1923 if (view->child == NULL || view->child->focussed)
1924 return 0;
1925 if (!view_is_splitscreen(view->child))
1926 return 0;
1927 } else if (!view_is_splitscreen(view))
1928 return 0;
1930 return view->focussed;
1933 static const struct got_error *
1934 tog_io_close(void)
1936 const struct got_error *err = NULL;
1938 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1939 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1940 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1941 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1942 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1943 err = got_ferror(tog_io.f, GOT_ERR_IO);
1945 return err;
1948 static const struct got_error *
1949 view_loop(struct tog_view *view)
1951 const struct got_error *err = NULL;
1952 struct tog_view_list_head views;
1953 struct tog_view *new_view;
1954 char *mode;
1955 int fast_refresh = 10;
1956 int done = 0, errcode;
1958 mode = getenv("TOG_VIEW_SPLIT_MODE");
1959 if (!mode || !(*mode == 'h' || *mode == 'H'))
1960 view->mode = TOG_VIEW_SPLIT_VERT;
1961 else
1962 view->mode = TOG_VIEW_SPLIT_HRZN;
1964 errcode = pthread_mutex_lock(&tog_mutex);
1965 if (errcode)
1966 return got_error_set_errno(errcode, "pthread_mutex_lock");
1968 TAILQ_INIT(&views);
1969 TAILQ_INSERT_HEAD(&views, view, entry);
1971 view->focussed = 1;
1972 err = view->show(view);
1973 if (err)
1974 return err;
1975 update_panels();
1976 doupdate();
1977 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1978 !tog_fatal_signal_received()) {
1979 /* Refresh fast during initialization, then become slower. */
1980 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
1981 halfdelay(10); /* switch to once per second */
1983 err = view_input(&new_view, &done, view, &views, fast_refresh);
1984 if (err)
1985 break;
1987 if (view->dying && view == TAILQ_FIRST(&views) &&
1988 TAILQ_NEXT(view, entry) == NULL)
1989 done = 1;
1990 if (done) {
1991 struct tog_view *v;
1994 * When we quit, scroll the screen up a single line
1995 * so we don't lose any information.
1997 TAILQ_FOREACH(v, &views, entry) {
1998 wmove(v->window, 0, 0);
1999 wdeleteln(v->window);
2000 wnoutrefresh(v->window);
2001 if (v->child && !view_is_fullscreen(v)) {
2002 wmove(v->child->window, 0, 0);
2003 wdeleteln(v->child->window);
2004 wnoutrefresh(v->child->window);
2007 doupdate();
2010 if (view->dying) {
2011 struct tog_view *v, *prev = NULL;
2013 if (view_is_parent_view(view))
2014 prev = TAILQ_PREV(view, tog_view_list_head,
2015 entry);
2016 else if (view->parent)
2017 prev = view->parent;
2019 if (view->parent) {
2020 view->parent->child = NULL;
2021 view->parent->focus_child = 0;
2022 /* Restore fullscreen line height. */
2023 view->parent->nlines = view->parent->lines;
2024 err = view_resize(view->parent);
2025 if (err)
2026 break;
2027 /* Make resized splits persist. */
2028 view_transfer_size(view->parent, view);
2029 } else
2030 TAILQ_REMOVE(&views, view, entry);
2032 err = view_close(view);
2033 if (err)
2034 goto done;
2036 view = NULL;
2037 TAILQ_FOREACH(v, &views, entry) {
2038 if (v->focussed)
2039 break;
2041 if (view == NULL && new_view == NULL) {
2042 /* No view has focus. Try to pick one. */
2043 if (prev)
2044 view = prev;
2045 else if (!TAILQ_EMPTY(&views)) {
2046 view = TAILQ_LAST(&views,
2047 tog_view_list_head);
2049 if (view) {
2050 if (view->focus_child) {
2051 view->child->focussed = 1;
2052 view = view->child;
2053 } else
2054 view->focussed = 1;
2058 if (new_view) {
2059 struct tog_view *v, *t;
2060 /* Only allow one parent view per type. */
2061 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2062 if (v->type != new_view->type)
2063 continue;
2064 TAILQ_REMOVE(&views, v, entry);
2065 err = view_close(v);
2066 if (err)
2067 goto done;
2068 break;
2070 TAILQ_INSERT_TAIL(&views, new_view, entry);
2071 view = new_view;
2073 if (view && !done) {
2074 if (view_is_parent_view(view)) {
2075 if (view->child && view->child->focussed)
2076 view = view->child;
2077 } else {
2078 if (view->parent && view->parent->focussed)
2079 view = view->parent;
2081 show_panel(view->panel);
2082 if (view->child && view_is_splitscreen(view->child))
2083 show_panel(view->child->panel);
2084 if (view->parent && view_is_splitscreen(view)) {
2085 err = view->parent->show(view->parent);
2086 if (err)
2087 goto done;
2089 err = view->show(view);
2090 if (err)
2091 goto done;
2092 if (view->child) {
2093 err = view->child->show(view->child);
2094 if (err)
2095 goto done;
2097 update_panels();
2098 doupdate();
2101 done:
2102 while (!TAILQ_EMPTY(&views)) {
2103 const struct got_error *close_err;
2104 view = TAILQ_FIRST(&views);
2105 TAILQ_REMOVE(&views, view, entry);
2106 close_err = view_close(view);
2107 if (close_err && err == NULL)
2108 err = close_err;
2111 errcode = pthread_mutex_unlock(&tog_mutex);
2112 if (errcode && err == NULL)
2113 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2115 return err;
2118 __dead static void
2119 usage_log(void)
2121 endwin();
2122 fprintf(stderr,
2123 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2124 getprogname());
2125 exit(1);
2128 /* Create newly allocated wide-character string equivalent to a byte string. */
2129 static const struct got_error *
2130 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2132 char *vis = NULL;
2133 const struct got_error *err = NULL;
2135 *ws = NULL;
2136 *wlen = mbstowcs(NULL, s, 0);
2137 if (*wlen == (size_t)-1) {
2138 int vislen;
2139 if (errno != EILSEQ)
2140 return got_error_from_errno("mbstowcs");
2142 /* byte string invalid in current encoding; try to "fix" it */
2143 err = got_mbsavis(&vis, &vislen, s);
2144 if (err)
2145 return err;
2146 *wlen = mbstowcs(NULL, vis, 0);
2147 if (*wlen == (size_t)-1) {
2148 err = got_error_from_errno("mbstowcs"); /* give up */
2149 goto done;
2153 *ws = calloc(*wlen + 1, sizeof(**ws));
2154 if (*ws == NULL) {
2155 err = got_error_from_errno("calloc");
2156 goto done;
2159 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2160 err = got_error_from_errno("mbstowcs");
2161 done:
2162 free(vis);
2163 if (err) {
2164 free(*ws);
2165 *ws = NULL;
2166 *wlen = 0;
2168 return err;
2171 static const struct got_error *
2172 expand_tab(char **ptr, const char *src)
2174 char *dst;
2175 size_t len, n, idx = 0, sz = 0;
2177 *ptr = NULL;
2178 n = len = strlen(src);
2179 dst = malloc(n + 1);
2180 if (dst == NULL)
2181 return got_error_from_errno("malloc");
2183 while (idx < len && src[idx]) {
2184 const char c = src[idx];
2186 if (c == '\t') {
2187 size_t nb = TABSIZE - sz % TABSIZE;
2188 char *p;
2190 p = realloc(dst, n + nb);
2191 if (p == NULL) {
2192 free(dst);
2193 return got_error_from_errno("realloc");
2196 dst = p;
2197 n += nb;
2198 memset(dst + sz, ' ', nb);
2199 sz += nb;
2200 } else
2201 dst[sz++] = src[idx];
2202 ++idx;
2205 dst[sz] = '\0';
2206 *ptr = dst;
2207 return NULL;
2211 * Advance at most n columns from wline starting at offset off.
2212 * Return the index to the first character after the span operation.
2213 * Return the combined column width of all spanned wide character in
2214 * *rcol.
2216 static int
2217 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2219 int width, i, cols = 0;
2221 if (n == 0) {
2222 *rcol = cols;
2223 return off;
2226 for (i = off; wline[i] != L'\0'; ++i) {
2227 if (wline[i] == L'\t')
2228 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2229 else
2230 width = wcwidth(wline[i]);
2232 if (width == -1) {
2233 width = 1;
2234 wline[i] = L'.';
2237 if (cols + width > n)
2238 break;
2239 cols += width;
2242 *rcol = cols;
2243 return i;
2247 * Format a line for display, ensuring that it won't overflow a width limit.
2248 * With scrolling, the width returned refers to the scrolled version of the
2249 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2251 static const struct got_error *
2252 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2253 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2255 const struct got_error *err = NULL;
2256 int cols;
2257 wchar_t *wline = NULL;
2258 char *exstr = NULL;
2259 size_t wlen;
2260 int i, scrollx;
2262 *wlinep = NULL;
2263 *widthp = 0;
2265 if (expand) {
2266 err = expand_tab(&exstr, line);
2267 if (err)
2268 return err;
2271 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2272 free(exstr);
2273 if (err)
2274 return err;
2276 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2278 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2279 wline[wlen - 1] = L'\0';
2280 wlen--;
2282 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2283 wline[wlen - 1] = L'\0';
2284 wlen--;
2287 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2288 wline[i] = L'\0';
2290 if (widthp)
2291 *widthp = cols;
2292 if (scrollxp)
2293 *scrollxp = scrollx;
2294 if (err)
2295 free(wline);
2296 else
2297 *wlinep = wline;
2298 return err;
2301 static const struct got_error*
2302 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2303 struct got_object_id *id, struct got_repository *repo)
2305 static const struct got_error *err = NULL;
2306 struct got_reflist_entry *re;
2307 char *s;
2308 const char *name;
2310 *refs_str = NULL;
2312 TAILQ_FOREACH(re, refs, entry) {
2313 struct got_tag_object *tag = NULL;
2314 struct got_object_id *ref_id;
2315 int cmp;
2317 name = got_ref_get_name(re->ref);
2318 if (strcmp(name, GOT_REF_HEAD) == 0)
2319 continue;
2320 if (strncmp(name, "refs/", 5) == 0)
2321 name += 5;
2322 if (strncmp(name, "got/", 4) == 0 &&
2323 strncmp(name, "got/backup/", 11) != 0)
2324 continue;
2325 if (strncmp(name, "heads/", 6) == 0)
2326 name += 6;
2327 if (strncmp(name, "remotes/", 8) == 0) {
2328 name += 8;
2329 s = strstr(name, "/" GOT_REF_HEAD);
2330 if (s != NULL && s[strlen(s)] == '\0')
2331 continue;
2333 err = got_ref_resolve(&ref_id, repo, re->ref);
2334 if (err)
2335 break;
2336 if (strncmp(name, "tags/", 5) == 0) {
2337 err = got_object_open_as_tag(&tag, repo, ref_id);
2338 if (err) {
2339 if (err->code != GOT_ERR_OBJ_TYPE) {
2340 free(ref_id);
2341 break;
2343 /* Ref points at something other than a tag. */
2344 err = NULL;
2345 tag = NULL;
2348 cmp = got_object_id_cmp(tag ?
2349 got_object_tag_get_object_id(tag) : ref_id, id);
2350 free(ref_id);
2351 if (tag)
2352 got_object_tag_close(tag);
2353 if (cmp != 0)
2354 continue;
2355 s = *refs_str;
2356 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2357 s ? ", " : "", name) == -1) {
2358 err = got_error_from_errno("asprintf");
2359 free(s);
2360 *refs_str = NULL;
2361 break;
2363 free(s);
2366 return err;
2369 static const struct got_error *
2370 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2371 int col_tab_align)
2373 char *smallerthan;
2375 smallerthan = strchr(author, '<');
2376 if (smallerthan && smallerthan[1] != '\0')
2377 author = smallerthan + 1;
2378 author[strcspn(author, "@>")] = '\0';
2379 return format_line(wauthor, author_width, NULL, author, 0, limit,
2380 col_tab_align, 0);
2383 static const struct got_error *
2384 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2385 struct got_object_id *id, const size_t date_display_cols,
2386 int author_display_cols)
2388 struct tog_log_view_state *s = &view->state.log;
2389 const struct got_error *err = NULL;
2390 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2391 char *logmsg0 = NULL, *logmsg = NULL;
2392 char *author = NULL;
2393 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2394 int author_width, logmsg_width;
2395 char *newline, *line = NULL;
2396 int col, limit, scrollx;
2397 const int avail = view->ncols;
2398 struct tm tm;
2399 time_t committer_time;
2400 struct tog_color *tc;
2402 committer_time = got_object_commit_get_committer_time(commit);
2403 if (gmtime_r(&committer_time, &tm) == NULL)
2404 return got_error_from_errno("gmtime_r");
2405 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2406 return got_error(GOT_ERR_NO_SPACE);
2408 if (avail <= date_display_cols)
2409 limit = MIN(sizeof(datebuf) - 1, avail);
2410 else
2411 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2412 tc = get_color(&s->colors, TOG_COLOR_DATE);
2413 if (tc)
2414 wattr_on(view->window,
2415 COLOR_PAIR(tc->colorpair), NULL);
2416 waddnstr(view->window, datebuf, limit);
2417 if (tc)
2418 wattr_off(view->window,
2419 COLOR_PAIR(tc->colorpair), NULL);
2420 col = limit;
2421 if (col > avail)
2422 goto done;
2424 if (avail >= 120) {
2425 char *id_str;
2426 err = got_object_id_str(&id_str, id);
2427 if (err)
2428 goto done;
2429 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2430 if (tc)
2431 wattr_on(view->window,
2432 COLOR_PAIR(tc->colorpair), NULL);
2433 wprintw(view->window, "%.8s ", id_str);
2434 if (tc)
2435 wattr_off(view->window,
2436 COLOR_PAIR(tc->colorpair), NULL);
2437 free(id_str);
2438 col += 9;
2439 if (col > avail)
2440 goto done;
2443 if (s->use_committer)
2444 author = strdup(got_object_commit_get_committer(commit));
2445 else
2446 author = strdup(got_object_commit_get_author(commit));
2447 if (author == NULL) {
2448 err = got_error_from_errno("strdup");
2449 goto done;
2451 err = format_author(&wauthor, &author_width, author, avail - col, col);
2452 if (err)
2453 goto done;
2454 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2455 if (tc)
2456 wattr_on(view->window,
2457 COLOR_PAIR(tc->colorpair), NULL);
2458 waddwstr(view->window, wauthor);
2459 col += author_width;
2460 while (col < avail && author_width < author_display_cols + 2) {
2461 waddch(view->window, ' ');
2462 col++;
2463 author_width++;
2465 if (tc)
2466 wattr_off(view->window,
2467 COLOR_PAIR(tc->colorpair), NULL);
2468 if (col > avail)
2469 goto done;
2471 err = got_object_commit_get_logmsg(&logmsg0, commit);
2472 if (err)
2473 goto done;
2474 logmsg = logmsg0;
2475 while (*logmsg == '\n')
2476 logmsg++;
2477 newline = strchr(logmsg, '\n');
2478 if (newline)
2479 *newline = '\0';
2480 limit = avail - col;
2481 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2482 limit--; /* for the border */
2483 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2484 limit, col, 1);
2485 if (err)
2486 goto done;
2487 waddwstr(view->window, &wlogmsg[scrollx]);
2488 col += MAX(logmsg_width, 0);
2489 while (col < avail) {
2490 waddch(view->window, ' ');
2491 col++;
2493 done:
2494 free(logmsg0);
2495 free(wlogmsg);
2496 free(author);
2497 free(wauthor);
2498 free(line);
2499 return err;
2502 static struct commit_queue_entry *
2503 alloc_commit_queue_entry(struct got_commit_object *commit,
2504 struct got_object_id *id)
2506 struct commit_queue_entry *entry;
2507 struct got_object_id *dup;
2509 entry = calloc(1, sizeof(*entry));
2510 if (entry == NULL)
2511 return NULL;
2513 dup = got_object_id_dup(id);
2514 if (dup == NULL) {
2515 free(entry);
2516 return NULL;
2519 entry->id = dup;
2520 entry->commit = commit;
2521 return entry;
2524 static void
2525 pop_commit(struct commit_queue *commits)
2527 struct commit_queue_entry *entry;
2529 entry = TAILQ_FIRST(&commits->head);
2530 TAILQ_REMOVE(&commits->head, entry, entry);
2531 got_object_commit_close(entry->commit);
2532 commits->ncommits--;
2533 free(entry->id);
2534 free(entry);
2537 static void
2538 free_commits(struct commit_queue *commits)
2540 while (!TAILQ_EMPTY(&commits->head))
2541 pop_commit(commits);
2544 static const struct got_error *
2545 match_commit(int *have_match, struct got_object_id *id,
2546 struct got_commit_object *commit, regex_t *regex)
2548 const struct got_error *err = NULL;
2549 regmatch_t regmatch;
2550 char *id_str = NULL, *logmsg = NULL;
2552 *have_match = 0;
2554 err = got_object_id_str(&id_str, id);
2555 if (err)
2556 return err;
2558 err = got_object_commit_get_logmsg(&logmsg, commit);
2559 if (err)
2560 goto done;
2562 if (regexec(regex, got_object_commit_get_author(commit), 1,
2563 &regmatch, 0) == 0 ||
2564 regexec(regex, got_object_commit_get_committer(commit), 1,
2565 &regmatch, 0) == 0 ||
2566 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2567 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2568 *have_match = 1;
2569 done:
2570 free(id_str);
2571 free(logmsg);
2572 return err;
2575 static const struct got_error *
2576 queue_commits(struct tog_log_thread_args *a)
2578 const struct got_error *err = NULL;
2581 * We keep all commits open throughout the lifetime of the log
2582 * view in order to avoid having to re-fetch commits from disk
2583 * while updating the display.
2585 do {
2586 struct got_object_id id;
2587 struct got_commit_object *commit;
2588 struct commit_queue_entry *entry;
2589 int limit_match = 0;
2590 int errcode;
2592 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2593 NULL, NULL);
2594 if (err)
2595 break;
2597 err = got_object_open_as_commit(&commit, a->repo, &id);
2598 if (err)
2599 break;
2600 entry = alloc_commit_queue_entry(commit, &id);
2601 if (entry == NULL) {
2602 err = got_error_from_errno("alloc_commit_queue_entry");
2603 break;
2606 errcode = pthread_mutex_lock(&tog_mutex);
2607 if (errcode) {
2608 err = got_error_set_errno(errcode,
2609 "pthread_mutex_lock");
2610 break;
2613 entry->idx = a->real_commits->ncommits;
2614 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2615 a->real_commits->ncommits++;
2617 if (*a->limiting) {
2618 err = match_commit(&limit_match, &id, commit,
2619 a->limit_regex);
2620 if (err)
2621 break;
2623 if (limit_match) {
2624 struct commit_queue_entry *matched;
2626 matched = alloc_commit_queue_entry(
2627 entry->commit, entry->id);
2628 if (matched == NULL) {
2629 err = got_error_from_errno(
2630 "alloc_commit_queue_entry");
2631 break;
2633 matched->commit = entry->commit;
2634 got_object_commit_retain(entry->commit);
2636 matched->idx = a->limit_commits->ncommits;
2637 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2638 matched, entry);
2639 a->limit_commits->ncommits++;
2643 * This is how we signal log_thread() that we
2644 * have found a match, and that it should be
2645 * counted as a new entry for the view.
2647 a->limit_match = limit_match;
2650 if (*a->searching == TOG_SEARCH_FORWARD &&
2651 !*a->search_next_done) {
2652 int have_match;
2653 err = match_commit(&have_match, &id, commit, a->regex);
2654 if (err)
2655 break;
2657 if (*a->limiting) {
2658 if (limit_match && have_match)
2659 *a->search_next_done =
2660 TOG_SEARCH_HAVE_MORE;
2661 } else if (have_match)
2662 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2665 errcode = pthread_mutex_unlock(&tog_mutex);
2666 if (errcode && err == NULL)
2667 err = got_error_set_errno(errcode,
2668 "pthread_mutex_unlock");
2669 if (err)
2670 break;
2671 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2673 return err;
2676 static void
2677 select_commit(struct tog_log_view_state *s)
2679 struct commit_queue_entry *entry;
2680 int ncommits = 0;
2682 entry = s->first_displayed_entry;
2683 while (entry) {
2684 if (ncommits == s->selected) {
2685 s->selected_entry = entry;
2686 break;
2688 entry = TAILQ_NEXT(entry, entry);
2689 ncommits++;
2693 static const struct got_error *
2694 draw_commits(struct tog_view *view)
2696 const struct got_error *err = NULL;
2697 struct tog_log_view_state *s = &view->state.log;
2698 struct commit_queue_entry *entry = s->selected_entry;
2699 int limit = view->nlines;
2700 int width;
2701 int ncommits, author_cols = 4;
2702 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2703 char *refs_str = NULL;
2704 wchar_t *wline;
2705 struct tog_color *tc;
2706 static const size_t date_display_cols = 12;
2708 if (view_is_hsplit_top(view))
2709 --limit; /* account for border */
2711 if (s->selected_entry &&
2712 !(view->searching && view->search_next_done == 0)) {
2713 struct got_reflist_head *refs;
2714 err = got_object_id_str(&id_str, s->selected_entry->id);
2715 if (err)
2716 return err;
2717 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2718 s->selected_entry->id);
2719 if (refs) {
2720 err = build_refs_str(&refs_str, refs,
2721 s->selected_entry->id, s->repo);
2722 if (err)
2723 goto done;
2727 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2728 halfdelay(10); /* disable fast refresh */
2730 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2731 if (asprintf(&ncommits_str, " [%d/%d] %s",
2732 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2733 (view->searching && !view->search_next_done) ?
2734 "searching..." : "loading...") == -1) {
2735 err = got_error_from_errno("asprintf");
2736 goto done;
2738 } else {
2739 const char *search_str = NULL;
2740 const char *limit_str = NULL;
2742 if (view->searching) {
2743 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2744 search_str = "no more matches";
2745 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2746 search_str = "no matches found";
2747 else if (!view->search_next_done)
2748 search_str = "searching...";
2751 if (s->limit_view && s->commits->ncommits == 0)
2752 limit_str = "no matches found";
2754 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2755 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2756 search_str ? search_str : (refs_str ? refs_str : ""),
2757 limit_str ? limit_str : "") == -1) {
2758 err = got_error_from_errno("asprintf");
2759 goto done;
2763 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2764 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2765 "........................................",
2766 s->in_repo_path, ncommits_str) == -1) {
2767 err = got_error_from_errno("asprintf");
2768 header = NULL;
2769 goto done;
2771 } else if (asprintf(&header, "commit %s%s",
2772 id_str ? id_str : "........................................",
2773 ncommits_str) == -1) {
2774 err = got_error_from_errno("asprintf");
2775 header = NULL;
2776 goto done;
2778 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2779 if (err)
2780 goto done;
2782 werase(view->window);
2784 if (view_needs_focus_indication(view))
2785 wstandout(view->window);
2786 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2787 if (tc)
2788 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2789 waddwstr(view->window, wline);
2790 while (width < view->ncols) {
2791 waddch(view->window, ' ');
2792 width++;
2794 if (tc)
2795 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2796 if (view_needs_focus_indication(view))
2797 wstandend(view->window);
2798 free(wline);
2799 if (limit <= 1)
2800 goto done;
2802 /* Grow author column size if necessary, and set view->maxx. */
2803 entry = s->first_displayed_entry;
2804 ncommits = 0;
2805 view->maxx = 0;
2806 while (entry) {
2807 struct got_commit_object *c = entry->commit;
2808 char *author, *eol, *msg, *msg0;
2809 wchar_t *wauthor, *wmsg;
2810 int width;
2811 if (ncommits >= limit - 1)
2812 break;
2813 if (s->use_committer)
2814 author = strdup(got_object_commit_get_committer(c));
2815 else
2816 author = strdup(got_object_commit_get_author(c));
2817 if (author == NULL) {
2818 err = got_error_from_errno("strdup");
2819 goto done;
2821 err = format_author(&wauthor, &width, author, COLS,
2822 date_display_cols);
2823 if (author_cols < width)
2824 author_cols = width;
2825 free(wauthor);
2826 free(author);
2827 if (err)
2828 goto done;
2829 err = got_object_commit_get_logmsg(&msg0, c);
2830 if (err)
2831 goto done;
2832 msg = msg0;
2833 while (*msg == '\n')
2834 ++msg;
2835 if ((eol = strchr(msg, '\n')))
2836 *eol = '\0';
2837 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2838 date_display_cols + author_cols, 0);
2839 if (err)
2840 goto done;
2841 view->maxx = MAX(view->maxx, width);
2842 free(msg0);
2843 free(wmsg);
2844 ncommits++;
2845 entry = TAILQ_NEXT(entry, entry);
2848 entry = s->first_displayed_entry;
2849 s->last_displayed_entry = s->first_displayed_entry;
2850 ncommits = 0;
2851 while (entry) {
2852 if (ncommits >= limit - 1)
2853 break;
2854 if (ncommits == s->selected)
2855 wstandout(view->window);
2856 err = draw_commit(view, entry->commit, entry->id,
2857 date_display_cols, author_cols);
2858 if (ncommits == s->selected)
2859 wstandend(view->window);
2860 if (err)
2861 goto done;
2862 ncommits++;
2863 s->last_displayed_entry = entry;
2864 entry = TAILQ_NEXT(entry, entry);
2867 view_border(view);
2868 done:
2869 free(id_str);
2870 free(refs_str);
2871 free(ncommits_str);
2872 free(header);
2873 return err;
2876 static void
2877 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2879 struct commit_queue_entry *entry;
2880 int nscrolled = 0;
2882 entry = TAILQ_FIRST(&s->commits->head);
2883 if (s->first_displayed_entry == entry)
2884 return;
2886 entry = s->first_displayed_entry;
2887 while (entry && nscrolled < maxscroll) {
2888 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2889 if (entry) {
2890 s->first_displayed_entry = entry;
2891 nscrolled++;
2896 static const struct got_error *
2897 trigger_log_thread(struct tog_view *view, int wait)
2899 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2900 int errcode;
2902 if (!using_mock_io)
2903 halfdelay(1); /* fast refresh while loading commits */
2905 while (!ta->log_complete && !tog_thread_error &&
2906 (ta->commits_needed > 0 || ta->load_all)) {
2907 /* Wake the log thread. */
2908 errcode = pthread_cond_signal(&ta->need_commits);
2909 if (errcode)
2910 return got_error_set_errno(errcode,
2911 "pthread_cond_signal");
2914 * The mutex will be released while the view loop waits
2915 * in wgetch(), at which time the log thread will run.
2917 if (!wait)
2918 break;
2920 /* Display progress update in log view. */
2921 show_log_view(view);
2922 update_panels();
2923 doupdate();
2925 /* Wait right here while next commit is being loaded. */
2926 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2927 if (errcode)
2928 return got_error_set_errno(errcode,
2929 "pthread_cond_wait");
2931 /* Display progress update in log view. */
2932 show_log_view(view);
2933 update_panels();
2934 doupdate();
2937 return NULL;
2940 static const struct got_error *
2941 request_log_commits(struct tog_view *view)
2943 struct tog_log_view_state *state = &view->state.log;
2944 const struct got_error *err = NULL;
2946 if (state->thread_args.log_complete)
2947 return NULL;
2949 state->thread_args.commits_needed += view->nscrolled;
2950 err = trigger_log_thread(view, 1);
2951 view->nscrolled = 0;
2953 return err;
2956 static const struct got_error *
2957 log_scroll_down(struct tog_view *view, int maxscroll)
2959 struct tog_log_view_state *s = &view->state.log;
2960 const struct got_error *err = NULL;
2961 struct commit_queue_entry *pentry;
2962 int nscrolled = 0, ncommits_needed;
2964 if (s->last_displayed_entry == NULL)
2965 return NULL;
2967 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2968 if (s->commits->ncommits < ncommits_needed &&
2969 !s->thread_args.log_complete) {
2971 * Ask the log thread for required amount of commits.
2973 s->thread_args.commits_needed +=
2974 ncommits_needed - s->commits->ncommits;
2975 err = trigger_log_thread(view, 1);
2976 if (err)
2977 return err;
2980 do {
2981 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2982 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2983 break;
2985 s->last_displayed_entry = pentry ?
2986 pentry : s->last_displayed_entry;
2988 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2989 if (pentry == NULL)
2990 break;
2991 s->first_displayed_entry = pentry;
2992 } while (++nscrolled < maxscroll);
2994 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2995 view->nscrolled += nscrolled;
2996 else
2997 view->nscrolled = 0;
2999 return err;
3002 static const struct got_error *
3003 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3004 struct got_commit_object *commit, struct got_object_id *commit_id,
3005 struct tog_view *log_view, struct got_repository *repo)
3007 const struct got_error *err;
3008 struct got_object_qid *parent_id;
3009 struct tog_view *diff_view;
3011 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3012 if (diff_view == NULL)
3013 return got_error_from_errno("view_open");
3015 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3016 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3017 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3018 if (err == NULL)
3019 *new_view = diff_view;
3020 return err;
3023 static const struct got_error *
3024 tree_view_visit_subtree(struct tog_tree_view_state *s,
3025 struct got_tree_object *subtree)
3027 struct tog_parent_tree *parent;
3029 parent = calloc(1, sizeof(*parent));
3030 if (parent == NULL)
3031 return got_error_from_errno("calloc");
3033 parent->tree = s->tree;
3034 parent->first_displayed_entry = s->first_displayed_entry;
3035 parent->selected_entry = s->selected_entry;
3036 parent->selected = s->selected;
3037 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3038 s->tree = subtree;
3039 s->selected = 0;
3040 s->first_displayed_entry = NULL;
3041 return NULL;
3044 static const struct got_error *
3045 tree_view_walk_path(struct tog_tree_view_state *s,
3046 struct got_commit_object *commit, const char *path)
3048 const struct got_error *err = NULL;
3049 struct got_tree_object *tree = NULL;
3050 const char *p;
3051 char *slash, *subpath = NULL;
3053 /* Walk the path and open corresponding tree objects. */
3054 p = path;
3055 while (*p) {
3056 struct got_tree_entry *te;
3057 struct got_object_id *tree_id;
3058 char *te_name;
3060 while (p[0] == '/')
3061 p++;
3063 /* Ensure the correct subtree entry is selected. */
3064 slash = strchr(p, '/');
3065 if (slash == NULL)
3066 te_name = strdup(p);
3067 else
3068 te_name = strndup(p, slash - p);
3069 if (te_name == NULL) {
3070 err = got_error_from_errno("strndup");
3071 break;
3073 te = got_object_tree_find_entry(s->tree, te_name);
3074 if (te == NULL) {
3075 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3076 free(te_name);
3077 break;
3079 free(te_name);
3080 s->first_displayed_entry = s->selected_entry = te;
3082 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3083 break; /* jump to this file's entry */
3085 slash = strchr(p, '/');
3086 if (slash)
3087 subpath = strndup(path, slash - path);
3088 else
3089 subpath = strdup(path);
3090 if (subpath == NULL) {
3091 err = got_error_from_errno("strdup");
3092 break;
3095 err = got_object_id_by_path(&tree_id, s->repo, commit,
3096 subpath);
3097 if (err)
3098 break;
3100 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3101 free(tree_id);
3102 if (err)
3103 break;
3105 err = tree_view_visit_subtree(s, tree);
3106 if (err) {
3107 got_object_tree_close(tree);
3108 break;
3110 if (slash == NULL)
3111 break;
3112 free(subpath);
3113 subpath = NULL;
3114 p = slash;
3117 free(subpath);
3118 return err;
3121 static const struct got_error *
3122 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3123 struct commit_queue_entry *entry, const char *path,
3124 const char *head_ref_name, struct got_repository *repo)
3126 const struct got_error *err = NULL;
3127 struct tog_tree_view_state *s;
3128 struct tog_view *tree_view;
3130 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3131 if (tree_view == NULL)
3132 return got_error_from_errno("view_open");
3134 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3135 if (err)
3136 return err;
3137 s = &tree_view->state.tree;
3139 *new_view = tree_view;
3141 if (got_path_is_root_dir(path))
3142 return NULL;
3144 return tree_view_walk_path(s, entry->commit, path);
3147 static const struct got_error *
3148 block_signals_used_by_main_thread(void)
3150 sigset_t sigset;
3151 int errcode;
3153 if (sigemptyset(&sigset) == -1)
3154 return got_error_from_errno("sigemptyset");
3156 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3157 if (sigaddset(&sigset, SIGWINCH) == -1)
3158 return got_error_from_errno("sigaddset");
3159 if (sigaddset(&sigset, SIGCONT) == -1)
3160 return got_error_from_errno("sigaddset");
3161 if (sigaddset(&sigset, SIGINT) == -1)
3162 return got_error_from_errno("sigaddset");
3163 if (sigaddset(&sigset, SIGTERM) == -1)
3164 return got_error_from_errno("sigaddset");
3166 /* ncurses handles SIGTSTP */
3167 if (sigaddset(&sigset, SIGTSTP) == -1)
3168 return got_error_from_errno("sigaddset");
3170 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3171 if (errcode)
3172 return got_error_set_errno(errcode, "pthread_sigmask");
3174 return NULL;
3177 static void *
3178 log_thread(void *arg)
3180 const struct got_error *err = NULL;
3181 int errcode = 0;
3182 struct tog_log_thread_args *a = arg;
3183 int done = 0;
3186 * Sync startup with main thread such that we begin our
3187 * work once view_input() has released the mutex.
3189 errcode = pthread_mutex_lock(&tog_mutex);
3190 if (errcode) {
3191 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3192 return (void *)err;
3195 err = block_signals_used_by_main_thread();
3196 if (err) {
3197 pthread_mutex_unlock(&tog_mutex);
3198 goto done;
3201 while (!done && !err && !tog_fatal_signal_received()) {
3202 errcode = pthread_mutex_unlock(&tog_mutex);
3203 if (errcode) {
3204 err = got_error_set_errno(errcode,
3205 "pthread_mutex_unlock");
3206 goto done;
3208 err = queue_commits(a);
3209 if (err) {
3210 if (err->code != GOT_ERR_ITER_COMPLETED)
3211 goto done;
3212 err = NULL;
3213 done = 1;
3214 } else if (a->commits_needed > 0 && !a->load_all) {
3215 if (*a->limiting) {
3216 if (a->limit_match)
3217 a->commits_needed--;
3218 } else
3219 a->commits_needed--;
3222 errcode = pthread_mutex_lock(&tog_mutex);
3223 if (errcode) {
3224 err = got_error_set_errno(errcode,
3225 "pthread_mutex_lock");
3226 goto done;
3227 } else if (*a->quit)
3228 done = 1;
3229 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3230 *a->first_displayed_entry =
3231 TAILQ_FIRST(&a->limit_commits->head);
3232 *a->selected_entry = *a->first_displayed_entry;
3233 } else if (*a->first_displayed_entry == NULL) {
3234 *a->first_displayed_entry =
3235 TAILQ_FIRST(&a->real_commits->head);
3236 *a->selected_entry = *a->first_displayed_entry;
3239 errcode = pthread_cond_signal(&a->commit_loaded);
3240 if (errcode) {
3241 err = got_error_set_errno(errcode,
3242 "pthread_cond_signal");
3243 pthread_mutex_unlock(&tog_mutex);
3244 goto done;
3247 if (done)
3248 a->commits_needed = 0;
3249 else {
3250 if (a->commits_needed == 0 && !a->load_all) {
3251 errcode = pthread_cond_wait(&a->need_commits,
3252 &tog_mutex);
3253 if (errcode) {
3254 err = got_error_set_errno(errcode,
3255 "pthread_cond_wait");
3256 pthread_mutex_unlock(&tog_mutex);
3257 goto done;
3259 if (*a->quit)
3260 done = 1;
3264 a->log_complete = 1;
3265 errcode = pthread_mutex_unlock(&tog_mutex);
3266 if (errcode)
3267 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3268 done:
3269 if (err) {
3270 tog_thread_error = 1;
3271 pthread_cond_signal(&a->commit_loaded);
3273 return (void *)err;
3276 static const struct got_error *
3277 stop_log_thread(struct tog_log_view_state *s)
3279 const struct got_error *err = NULL, *thread_err = NULL;
3280 int errcode;
3282 if (s->thread) {
3283 s->quit = 1;
3284 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3285 if (errcode)
3286 return got_error_set_errno(errcode,
3287 "pthread_cond_signal");
3288 errcode = pthread_mutex_unlock(&tog_mutex);
3289 if (errcode)
3290 return got_error_set_errno(errcode,
3291 "pthread_mutex_unlock");
3292 errcode = pthread_join(s->thread, (void **)&thread_err);
3293 if (errcode)
3294 return got_error_set_errno(errcode, "pthread_join");
3295 errcode = pthread_mutex_lock(&tog_mutex);
3296 if (errcode)
3297 return got_error_set_errno(errcode,
3298 "pthread_mutex_lock");
3299 s->thread = NULL;
3302 if (s->thread_args.repo) {
3303 err = got_repo_close(s->thread_args.repo);
3304 s->thread_args.repo = NULL;
3307 if (s->thread_args.pack_fds) {
3308 const struct got_error *pack_err =
3309 got_repo_pack_fds_close(s->thread_args.pack_fds);
3310 if (err == NULL)
3311 err = pack_err;
3312 s->thread_args.pack_fds = NULL;
3315 if (s->thread_args.graph) {
3316 got_commit_graph_close(s->thread_args.graph);
3317 s->thread_args.graph = NULL;
3320 return err ? err : thread_err;
3323 static const struct got_error *
3324 close_log_view(struct tog_view *view)
3326 const struct got_error *err = NULL;
3327 struct tog_log_view_state *s = &view->state.log;
3328 int errcode;
3330 err = stop_log_thread(s);
3332 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3333 if (errcode && err == NULL)
3334 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3336 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3337 if (errcode && err == NULL)
3338 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3340 free_commits(&s->limit_commits);
3341 free_commits(&s->real_commits);
3342 free(s->in_repo_path);
3343 s->in_repo_path = NULL;
3344 free(s->start_id);
3345 s->start_id = NULL;
3346 free(s->head_ref_name);
3347 s->head_ref_name = NULL;
3348 return err;
3352 * We use two queues to implement the limit feature: first consists of
3353 * commits matching the current limit_regex; second is the real queue
3354 * of all known commits (real_commits). When the user starts limiting,
3355 * we swap queues such that all movement and displaying functionality
3356 * works with very slight change.
3358 static const struct got_error *
3359 limit_log_view(struct tog_view *view)
3361 struct tog_log_view_state *s = &view->state.log;
3362 struct commit_queue_entry *entry;
3363 struct tog_view *v = view;
3364 const struct got_error *err = NULL;
3365 char pattern[1024];
3366 int ret;
3368 if (view_is_hsplit_top(view))
3369 v = view->child;
3370 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3371 v = view->parent;
3373 /* Get the pattern */
3374 wmove(v->window, v->nlines - 1, 0);
3375 wclrtoeol(v->window);
3376 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3377 nodelay(v->window, FALSE);
3378 nocbreak();
3379 echo();
3380 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3381 cbreak();
3382 noecho();
3383 nodelay(v->window, TRUE);
3384 if (ret == ERR)
3385 return NULL;
3387 if (*pattern == '\0') {
3389 * Safety measure for the situation where the user
3390 * resets limit without previously limiting anything.
3392 if (!s->limit_view)
3393 return NULL;
3396 * User could have pressed Ctrl+L, which refreshed the
3397 * commit queues, it means we can't save previously
3398 * (before limit took place) displayed entries,
3399 * because they would point to already free'ed memory,
3400 * so we are forced to always select first entry of
3401 * the queue.
3403 s->commits = &s->real_commits;
3404 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3405 s->selected_entry = s->first_displayed_entry;
3406 s->selected = 0;
3407 s->limit_view = 0;
3409 return NULL;
3412 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3413 return NULL;
3415 s->limit_view = 1;
3417 /* Clear the screen while loading limit view */
3418 s->first_displayed_entry = NULL;
3419 s->last_displayed_entry = NULL;
3420 s->selected_entry = NULL;
3421 s->commits = &s->limit_commits;
3423 /* Prepare limit queue for new search */
3424 free_commits(&s->limit_commits);
3425 s->limit_commits.ncommits = 0;
3427 /* First process commits, which are in queue already */
3428 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3429 int have_match = 0;
3431 err = match_commit(&have_match, entry->id,
3432 entry->commit, &s->limit_regex);
3433 if (err)
3434 return err;
3436 if (have_match) {
3437 struct commit_queue_entry *matched;
3439 matched = alloc_commit_queue_entry(entry->commit,
3440 entry->id);
3441 if (matched == NULL) {
3442 err = got_error_from_errno(
3443 "alloc_commit_queue_entry");
3444 break;
3446 matched->commit = entry->commit;
3447 got_object_commit_retain(entry->commit);
3449 matched->idx = s->limit_commits.ncommits;
3450 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3451 matched, entry);
3452 s->limit_commits.ncommits++;
3456 /* Second process all the commits, until we fill the screen */
3457 if (s->limit_commits.ncommits < view->nlines - 1 &&
3458 !s->thread_args.log_complete) {
3459 s->thread_args.commits_needed +=
3460 view->nlines - s->limit_commits.ncommits - 1;
3461 err = trigger_log_thread(view, 1);
3462 if (err)
3463 return err;
3466 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3467 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3468 s->selected = 0;
3470 return NULL;
3473 static const struct got_error *
3474 search_start_log_view(struct tog_view *view)
3476 struct tog_log_view_state *s = &view->state.log;
3478 s->matched_entry = NULL;
3479 s->search_entry = NULL;
3480 return NULL;
3483 static const struct got_error *
3484 search_next_log_view(struct tog_view *view)
3486 const struct got_error *err = NULL;
3487 struct tog_log_view_state *s = &view->state.log;
3488 struct commit_queue_entry *entry;
3490 /* Display progress update in log view. */
3491 show_log_view(view);
3492 update_panels();
3493 doupdate();
3495 if (s->search_entry) {
3496 int errcode, ch;
3497 errcode = pthread_mutex_unlock(&tog_mutex);
3498 if (errcode)
3499 return got_error_set_errno(errcode,
3500 "pthread_mutex_unlock");
3501 ch = wgetch(view->window);
3502 errcode = pthread_mutex_lock(&tog_mutex);
3503 if (errcode)
3504 return got_error_set_errno(errcode,
3505 "pthread_mutex_lock");
3506 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3507 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3508 return NULL;
3510 if (view->searching == TOG_SEARCH_FORWARD)
3511 entry = TAILQ_NEXT(s->search_entry, entry);
3512 else
3513 entry = TAILQ_PREV(s->search_entry,
3514 commit_queue_head, entry);
3515 } else if (s->matched_entry) {
3517 * If the user has moved the cursor after we hit a match,
3518 * the position from where we should continue searching
3519 * might have changed.
3521 if (view->searching == TOG_SEARCH_FORWARD)
3522 entry = TAILQ_NEXT(s->selected_entry, entry);
3523 else
3524 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3525 entry);
3526 } else {
3527 entry = s->selected_entry;
3530 while (1) {
3531 int have_match = 0;
3533 if (entry == NULL) {
3534 if (s->thread_args.log_complete ||
3535 view->searching == TOG_SEARCH_BACKWARD) {
3536 view->search_next_done =
3537 (s->matched_entry == NULL ?
3538 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3539 s->search_entry = NULL;
3540 return NULL;
3543 * Poke the log thread for more commits and return,
3544 * allowing the main loop to make progress. Search
3545 * will resume at s->search_entry once we come back.
3547 s->thread_args.commits_needed++;
3548 return trigger_log_thread(view, 0);
3551 err = match_commit(&have_match, entry->id, entry->commit,
3552 &view->regex);
3553 if (err)
3554 break;
3555 if (have_match) {
3556 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3557 s->matched_entry = entry;
3558 break;
3561 s->search_entry = entry;
3562 if (view->searching == TOG_SEARCH_FORWARD)
3563 entry = TAILQ_NEXT(entry, entry);
3564 else
3565 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3568 if (s->matched_entry) {
3569 int cur = s->selected_entry->idx;
3570 while (cur < s->matched_entry->idx) {
3571 err = input_log_view(NULL, view, KEY_DOWN);
3572 if (err)
3573 return err;
3574 cur++;
3576 while (cur > s->matched_entry->idx) {
3577 err = input_log_view(NULL, view, KEY_UP);
3578 if (err)
3579 return err;
3580 cur--;
3584 s->search_entry = NULL;
3586 return NULL;
3589 static const struct got_error *
3590 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3591 struct got_repository *repo, const char *head_ref_name,
3592 const char *in_repo_path, int log_branches)
3594 const struct got_error *err = NULL;
3595 struct tog_log_view_state *s = &view->state.log;
3596 struct got_repository *thread_repo = NULL;
3597 struct got_commit_graph *thread_graph = NULL;
3598 int errcode;
3600 if (in_repo_path != s->in_repo_path) {
3601 free(s->in_repo_path);
3602 s->in_repo_path = strdup(in_repo_path);
3603 if (s->in_repo_path == NULL) {
3604 err = got_error_from_errno("strdup");
3605 goto done;
3609 /* The commit queue only contains commits being displayed. */
3610 TAILQ_INIT(&s->real_commits.head);
3611 s->real_commits.ncommits = 0;
3612 s->commits = &s->real_commits;
3614 TAILQ_INIT(&s->limit_commits.head);
3615 s->limit_view = 0;
3616 s->limit_commits.ncommits = 0;
3618 s->repo = repo;
3619 if (head_ref_name) {
3620 s->head_ref_name = strdup(head_ref_name);
3621 if (s->head_ref_name == NULL) {
3622 err = got_error_from_errno("strdup");
3623 goto done;
3626 s->start_id = got_object_id_dup(start_id);
3627 if (s->start_id == NULL) {
3628 err = got_error_from_errno("got_object_id_dup");
3629 goto done;
3631 s->log_branches = log_branches;
3632 s->use_committer = 1;
3634 STAILQ_INIT(&s->colors);
3635 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3636 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3637 get_color_value("TOG_COLOR_COMMIT"));
3638 if (err)
3639 goto done;
3640 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3641 get_color_value("TOG_COLOR_AUTHOR"));
3642 if (err) {
3643 free_colors(&s->colors);
3644 goto done;
3646 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3647 get_color_value("TOG_COLOR_DATE"));
3648 if (err) {
3649 free_colors(&s->colors);
3650 goto done;
3654 view->show = show_log_view;
3655 view->input = input_log_view;
3656 view->resize = resize_log_view;
3657 view->close = close_log_view;
3658 view->search_start = search_start_log_view;
3659 view->search_next = search_next_log_view;
3661 if (s->thread_args.pack_fds == NULL) {
3662 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3663 if (err)
3664 goto done;
3666 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3667 s->thread_args.pack_fds);
3668 if (err)
3669 goto done;
3670 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3671 !s->log_branches);
3672 if (err)
3673 goto done;
3674 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3675 s->repo, NULL, NULL);
3676 if (err)
3677 goto done;
3679 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3680 if (errcode) {
3681 err = got_error_set_errno(errcode, "pthread_cond_init");
3682 goto done;
3684 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3685 if (errcode) {
3686 err = got_error_set_errno(errcode, "pthread_cond_init");
3687 goto done;
3690 s->thread_args.commits_needed = view->nlines;
3691 s->thread_args.graph = thread_graph;
3692 s->thread_args.real_commits = &s->real_commits;
3693 s->thread_args.limit_commits = &s->limit_commits;
3694 s->thread_args.in_repo_path = s->in_repo_path;
3695 s->thread_args.start_id = s->start_id;
3696 s->thread_args.repo = thread_repo;
3697 s->thread_args.log_complete = 0;
3698 s->thread_args.quit = &s->quit;
3699 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3700 s->thread_args.selected_entry = &s->selected_entry;
3701 s->thread_args.searching = &view->searching;
3702 s->thread_args.search_next_done = &view->search_next_done;
3703 s->thread_args.regex = &view->regex;
3704 s->thread_args.limiting = &s->limit_view;
3705 s->thread_args.limit_regex = &s->limit_regex;
3706 s->thread_args.limit_commits = &s->limit_commits;
3707 done:
3708 if (err) {
3709 if (view->close == NULL)
3710 close_log_view(view);
3711 view_close(view);
3713 return err;
3716 static const struct got_error *
3717 show_log_view(struct tog_view *view)
3719 const struct got_error *err;
3720 struct tog_log_view_state *s = &view->state.log;
3722 if (s->thread == NULL) {
3723 int errcode = pthread_create(&s->thread, NULL, log_thread,
3724 &s->thread_args);
3725 if (errcode)
3726 return got_error_set_errno(errcode, "pthread_create");
3727 if (s->thread_args.commits_needed > 0) {
3728 err = trigger_log_thread(view, 1);
3729 if (err)
3730 return err;
3734 return draw_commits(view);
3737 static void
3738 log_move_cursor_up(struct tog_view *view, int page, int home)
3740 struct tog_log_view_state *s = &view->state.log;
3742 if (s->first_displayed_entry == NULL)
3743 return;
3744 if (s->selected_entry->idx == 0)
3745 view->count = 0;
3747 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3748 || home)
3749 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3751 if (!page && !home && s->selected > 0)
3752 --s->selected;
3753 else
3754 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3756 select_commit(s);
3757 return;
3760 static const struct got_error *
3761 log_move_cursor_down(struct tog_view *view, int page)
3763 struct tog_log_view_state *s = &view->state.log;
3764 const struct got_error *err = NULL;
3765 int eos = view->nlines - 2;
3767 if (s->first_displayed_entry == NULL)
3768 return NULL;
3770 if (s->thread_args.log_complete &&
3771 s->selected_entry->idx >= s->commits->ncommits - 1)
3772 return NULL;
3774 if (view_is_hsplit_top(view))
3775 --eos; /* border consumes the last line */
3777 if (!page) {
3778 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3779 ++s->selected;
3780 else
3781 err = log_scroll_down(view, 1);
3782 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3783 struct commit_queue_entry *entry;
3784 int n;
3786 s->selected = 0;
3787 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3788 s->last_displayed_entry = entry;
3789 for (n = 0; n <= eos; n++) {
3790 if (entry == NULL)
3791 break;
3792 s->first_displayed_entry = entry;
3793 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3795 if (n > 0)
3796 s->selected = n - 1;
3797 } else {
3798 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3799 s->thread_args.log_complete)
3800 s->selected += MIN(page,
3801 s->commits->ncommits - s->selected_entry->idx - 1);
3802 else
3803 err = log_scroll_down(view, page);
3805 if (err)
3806 return err;
3809 * We might necessarily overshoot in horizontal
3810 * splits; if so, select the last displayed commit.
3812 if (s->first_displayed_entry && s->last_displayed_entry) {
3813 s->selected = MIN(s->selected,
3814 s->last_displayed_entry->idx -
3815 s->first_displayed_entry->idx);
3818 select_commit(s);
3820 if (s->thread_args.log_complete &&
3821 s->selected_entry->idx == s->commits->ncommits - 1)
3822 view->count = 0;
3824 return NULL;
3827 static void
3828 view_get_split(struct tog_view *view, int *y, int *x)
3830 *x = 0;
3831 *y = 0;
3833 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3834 if (view->child && view->child->resized_y)
3835 *y = view->child->resized_y;
3836 else if (view->resized_y)
3837 *y = view->resized_y;
3838 else
3839 *y = view_split_begin_y(view->lines);
3840 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3841 if (view->child && view->child->resized_x)
3842 *x = view->child->resized_x;
3843 else if (view->resized_x)
3844 *x = view->resized_x;
3845 else
3846 *x = view_split_begin_x(view->begin_x);
3850 /* Split view horizontally at y and offset view->state->selected line. */
3851 static const struct got_error *
3852 view_init_hsplit(struct tog_view *view, int y)
3854 const struct got_error *err = NULL;
3856 view->nlines = y;
3857 view->ncols = COLS;
3858 err = view_resize(view);
3859 if (err)
3860 return err;
3862 err = offset_selection_down(view);
3864 return err;
3867 static const struct got_error *
3868 log_goto_line(struct tog_view *view, int nlines)
3870 const struct got_error *err = NULL;
3871 struct tog_log_view_state *s = &view->state.log;
3872 int g, idx = s->selected_entry->idx;
3874 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3875 return NULL;
3877 g = view->gline;
3878 view->gline = 0;
3880 if (g >= s->first_displayed_entry->idx + 1 &&
3881 g <= s->last_displayed_entry->idx + 1 &&
3882 g - s->first_displayed_entry->idx - 1 < nlines) {
3883 s->selected = g - s->first_displayed_entry->idx - 1;
3884 select_commit(s);
3885 return NULL;
3888 if (idx + 1 < g) {
3889 err = log_move_cursor_down(view, g - idx - 1);
3890 if (!err && g > s->selected_entry->idx + 1)
3891 err = log_move_cursor_down(view,
3892 g - s->first_displayed_entry->idx - 1);
3893 if (err)
3894 return err;
3895 } else if (idx + 1 > g)
3896 log_move_cursor_up(view, idx - g + 1, 0);
3898 if (g < nlines && s->first_displayed_entry->idx == 0)
3899 s->selected = g - 1;
3901 select_commit(s);
3902 return NULL;
3906 static void
3907 horizontal_scroll_input(struct tog_view *view, int ch)
3910 switch (ch) {
3911 case KEY_LEFT:
3912 case 'h':
3913 view->x -= MIN(view->x, 2);
3914 if (view->x <= 0)
3915 view->count = 0;
3916 break;
3917 case KEY_RIGHT:
3918 case 'l':
3919 if (view->x + view->ncols / 2 < view->maxx)
3920 view->x += 2;
3921 else
3922 view->count = 0;
3923 break;
3924 case '0':
3925 view->x = 0;
3926 break;
3927 case '$':
3928 view->x = MAX(view->maxx - view->ncols / 2, 0);
3929 view->count = 0;
3930 break;
3931 default:
3932 break;
3936 static const struct got_error *
3937 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3939 const struct got_error *err = NULL;
3940 struct tog_log_view_state *s = &view->state.log;
3941 int eos, nscroll;
3943 if (s->thread_args.load_all) {
3944 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3945 s->thread_args.load_all = 0;
3946 else if (s->thread_args.log_complete) {
3947 err = log_move_cursor_down(view, s->commits->ncommits);
3948 s->thread_args.load_all = 0;
3950 if (err)
3951 return err;
3954 eos = nscroll = view->nlines - 1;
3955 if (view_is_hsplit_top(view))
3956 --eos; /* border */
3958 if (view->gline)
3959 return log_goto_line(view, eos);
3961 switch (ch) {
3962 case '&':
3963 err = limit_log_view(view);
3964 break;
3965 case 'q':
3966 s->quit = 1;
3967 break;
3968 case '0':
3969 case '$':
3970 case KEY_RIGHT:
3971 case 'l':
3972 case KEY_LEFT:
3973 case 'h':
3974 horizontal_scroll_input(view, ch);
3975 break;
3976 case 'k':
3977 case KEY_UP:
3978 case '<':
3979 case ',':
3980 case CTRL('p'):
3981 log_move_cursor_up(view, 0, 0);
3982 break;
3983 case 'g':
3984 case '=':
3985 case KEY_HOME:
3986 log_move_cursor_up(view, 0, 1);
3987 view->count = 0;
3988 break;
3989 case CTRL('u'):
3990 case 'u':
3991 nscroll /= 2;
3992 /* FALL THROUGH */
3993 case KEY_PPAGE:
3994 case CTRL('b'):
3995 case 'b':
3996 log_move_cursor_up(view, nscroll, 0);
3997 break;
3998 case 'j':
3999 case KEY_DOWN:
4000 case '>':
4001 case '.':
4002 case CTRL('n'):
4003 err = log_move_cursor_down(view, 0);
4004 break;
4005 case '@':
4006 s->use_committer = !s->use_committer;
4007 view->action = s->use_committer ?
4008 "show committer" : "show commit author";
4009 break;
4010 case 'G':
4011 case '*':
4012 case KEY_END: {
4013 /* We don't know yet how many commits, so we're forced to
4014 * traverse them all. */
4015 view->count = 0;
4016 s->thread_args.load_all = 1;
4017 if (!s->thread_args.log_complete)
4018 return trigger_log_thread(view, 0);
4019 err = log_move_cursor_down(view, s->commits->ncommits);
4020 s->thread_args.load_all = 0;
4021 break;
4023 case CTRL('d'):
4024 case 'd':
4025 nscroll /= 2;
4026 /* FALL THROUGH */
4027 case KEY_NPAGE:
4028 case CTRL('f'):
4029 case 'f':
4030 case ' ':
4031 err = log_move_cursor_down(view, nscroll);
4032 break;
4033 case KEY_RESIZE:
4034 if (s->selected > view->nlines - 2)
4035 s->selected = view->nlines - 2;
4036 if (s->selected > s->commits->ncommits - 1)
4037 s->selected = s->commits->ncommits - 1;
4038 select_commit(s);
4039 if (s->commits->ncommits < view->nlines - 1 &&
4040 !s->thread_args.log_complete) {
4041 s->thread_args.commits_needed += (view->nlines - 1) -
4042 s->commits->ncommits;
4043 err = trigger_log_thread(view, 1);
4045 break;
4046 case KEY_ENTER:
4047 case '\r':
4048 view->count = 0;
4049 if (s->selected_entry == NULL)
4050 break;
4051 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4052 break;
4053 case 'T':
4054 view->count = 0;
4055 if (s->selected_entry == NULL)
4056 break;
4057 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4058 break;
4059 case KEY_BACKSPACE:
4060 case CTRL('l'):
4061 case 'B':
4062 view->count = 0;
4063 if (ch == KEY_BACKSPACE &&
4064 got_path_is_root_dir(s->in_repo_path))
4065 break;
4066 err = stop_log_thread(s);
4067 if (err)
4068 return err;
4069 if (ch == KEY_BACKSPACE) {
4070 char *parent_path;
4071 err = got_path_dirname(&parent_path, s->in_repo_path);
4072 if (err)
4073 return err;
4074 free(s->in_repo_path);
4075 s->in_repo_path = parent_path;
4076 s->thread_args.in_repo_path = s->in_repo_path;
4077 } else if (ch == CTRL('l')) {
4078 struct got_object_id *start_id;
4079 err = got_repo_match_object_id(&start_id, NULL,
4080 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4081 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4082 if (err) {
4083 if (s->head_ref_name == NULL ||
4084 err->code != GOT_ERR_NOT_REF)
4085 return err;
4086 /* Try to cope with deleted references. */
4087 free(s->head_ref_name);
4088 s->head_ref_name = NULL;
4089 err = got_repo_match_object_id(&start_id,
4090 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4091 &tog_refs, s->repo);
4092 if (err)
4093 return err;
4095 free(s->start_id);
4096 s->start_id = start_id;
4097 s->thread_args.start_id = s->start_id;
4098 } else /* 'B' */
4099 s->log_branches = !s->log_branches;
4101 if (s->thread_args.pack_fds == NULL) {
4102 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4103 if (err)
4104 return err;
4106 err = got_repo_open(&s->thread_args.repo,
4107 got_repo_get_path(s->repo), NULL,
4108 s->thread_args.pack_fds);
4109 if (err)
4110 return err;
4111 tog_free_refs();
4112 err = tog_load_refs(s->repo, 0);
4113 if (err)
4114 return err;
4115 err = got_commit_graph_open(&s->thread_args.graph,
4116 s->in_repo_path, !s->log_branches);
4117 if (err)
4118 return err;
4119 err = got_commit_graph_iter_start(s->thread_args.graph,
4120 s->start_id, s->repo, NULL, NULL);
4121 if (err)
4122 return err;
4123 free_commits(&s->real_commits);
4124 free_commits(&s->limit_commits);
4125 s->first_displayed_entry = NULL;
4126 s->last_displayed_entry = NULL;
4127 s->selected_entry = NULL;
4128 s->selected = 0;
4129 s->thread_args.log_complete = 0;
4130 s->quit = 0;
4131 s->thread_args.commits_needed = view->lines;
4132 s->matched_entry = NULL;
4133 s->search_entry = NULL;
4134 view->offset = 0;
4135 break;
4136 case 'R':
4137 view->count = 0;
4138 err = view_request_new(new_view, view, TOG_VIEW_REF);
4139 break;
4140 default:
4141 view->count = 0;
4142 break;
4145 return err;
4148 static const struct got_error *
4149 apply_unveil(const char *repo_path, const char *worktree_path)
4151 const struct got_error *error;
4153 #ifdef PROFILE
4154 if (unveil("gmon.out", "rwc") != 0)
4155 return got_error_from_errno2("unveil", "gmon.out");
4156 #endif
4157 if (repo_path && unveil(repo_path, "r") != 0)
4158 return got_error_from_errno2("unveil", repo_path);
4160 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4161 return got_error_from_errno2("unveil", worktree_path);
4163 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4164 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4166 error = got_privsep_unveil_exec_helpers();
4167 if (error != NULL)
4168 return error;
4170 if (unveil(NULL, NULL) != 0)
4171 return got_error_from_errno("unveil");
4173 return NULL;
4176 static const struct got_error *
4177 init_mock_term(const char *test_script_path)
4179 const struct got_error *err = NULL;
4181 if (test_script_path == NULL || *test_script_path == '\0')
4182 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4184 tog_io.f = fopen(test_script_path, "re");
4185 if (tog_io.f == NULL) {
4186 err = got_error_from_errno_fmt("fopen: %s",
4187 test_script_path);
4188 goto done;
4191 /* test mode, we don't want any output */
4192 tog_io.cout = fopen("/dev/null", "w+");
4193 if (tog_io.cout == NULL) {
4194 err = got_error_from_errno("fopen: /dev/null");
4195 goto done;
4198 tog_io.cin = fopen("/dev/tty", "r+");
4199 if (tog_io.cin == NULL) {
4200 err = got_error_from_errno("fopen: /dev/tty");
4201 goto done;
4204 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4205 err = got_error_from_errno("fseeko");
4206 goto done;
4209 /* use local TERM so we test in different environments */
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;
4215 done:
4216 if (err)
4217 tog_io_close();
4218 return err;
4221 static void
4222 init_curses(void)
4225 * Override default signal handlers before starting ncurses.
4226 * This should prevent ncurses from installing its own
4227 * broken cleanup() signal handler.
4229 signal(SIGWINCH, tog_sigwinch);
4230 signal(SIGPIPE, tog_sigpipe);
4231 signal(SIGCONT, tog_sigcont);
4232 signal(SIGINT, tog_sigint);
4233 signal(SIGTERM, tog_sigterm);
4235 if (using_mock_io) /* In test mode we use a fake terminal */
4236 return;
4238 initscr();
4240 cbreak();
4241 halfdelay(1); /* Fast refresh while initial view is loading. */
4242 noecho();
4243 nonl();
4244 intrflush(stdscr, FALSE);
4245 keypad(stdscr, TRUE);
4246 curs_set(0);
4247 if (getenv("TOG_COLORS") != NULL) {
4248 start_color();
4249 use_default_colors();
4252 return;
4255 static const struct got_error *
4256 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4257 struct got_repository *repo, struct got_worktree *worktree)
4259 const struct got_error *err = NULL;
4261 if (argc == 0) {
4262 *in_repo_path = strdup("/");
4263 if (*in_repo_path == NULL)
4264 return got_error_from_errno("strdup");
4265 return NULL;
4268 if (worktree) {
4269 const char *prefix = got_worktree_get_path_prefix(worktree);
4270 char *p;
4272 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4273 if (err)
4274 return err;
4275 if (asprintf(in_repo_path, "%s%s%s", prefix,
4276 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4277 p) == -1) {
4278 err = got_error_from_errno("asprintf");
4279 *in_repo_path = NULL;
4281 free(p);
4282 } else
4283 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4285 return err;
4288 static const struct got_error *
4289 cmd_log(int argc, char *argv[])
4291 const struct got_error *error;
4292 struct got_repository *repo = NULL;
4293 struct got_worktree *worktree = NULL;
4294 struct got_object_id *start_id = NULL;
4295 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4296 char *start_commit = NULL, *label = NULL;
4297 struct got_reference *ref = NULL;
4298 const char *head_ref_name = NULL;
4299 int ch, log_branches = 0;
4300 struct tog_view *view;
4301 int *pack_fds = NULL;
4303 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4304 switch (ch) {
4305 case 'b':
4306 log_branches = 1;
4307 break;
4308 case 'c':
4309 start_commit = optarg;
4310 break;
4311 case 'r':
4312 repo_path = realpath(optarg, NULL);
4313 if (repo_path == NULL)
4314 return got_error_from_errno2("realpath",
4315 optarg);
4316 break;
4317 default:
4318 usage_log();
4319 /* NOTREACHED */
4323 argc -= optind;
4324 argv += optind;
4326 if (argc > 1)
4327 usage_log();
4329 error = got_repo_pack_fds_open(&pack_fds);
4330 if (error != NULL)
4331 goto done;
4333 if (repo_path == NULL) {
4334 cwd = getcwd(NULL, 0);
4335 if (cwd == NULL)
4336 return got_error_from_errno("getcwd");
4337 error = got_worktree_open(&worktree, cwd);
4338 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4339 goto done;
4340 if (worktree)
4341 repo_path =
4342 strdup(got_worktree_get_repo_path(worktree));
4343 else
4344 repo_path = strdup(cwd);
4345 if (repo_path == NULL) {
4346 error = got_error_from_errno("strdup");
4347 goto done;
4351 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4352 if (error != NULL)
4353 goto done;
4355 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4356 repo, worktree);
4357 if (error)
4358 goto done;
4360 init_curses();
4362 error = apply_unveil(got_repo_get_path(repo),
4363 worktree ? got_worktree_get_root_path(worktree) : NULL);
4364 if (error)
4365 goto done;
4367 /* already loaded by tog_log_with_path()? */
4368 if (TAILQ_EMPTY(&tog_refs)) {
4369 error = tog_load_refs(repo, 0);
4370 if (error)
4371 goto done;
4374 if (start_commit == NULL) {
4375 error = got_repo_match_object_id(&start_id, &label,
4376 worktree ? got_worktree_get_head_ref_name(worktree) :
4377 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4378 if (error)
4379 goto done;
4380 head_ref_name = label;
4381 } else {
4382 error = got_ref_open(&ref, repo, start_commit, 0);
4383 if (error == NULL)
4384 head_ref_name = got_ref_get_name(ref);
4385 else if (error->code != GOT_ERR_NOT_REF)
4386 goto done;
4387 error = got_repo_match_object_id(&start_id, NULL,
4388 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4389 if (error)
4390 goto done;
4393 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4394 if (view == NULL) {
4395 error = got_error_from_errno("view_open");
4396 goto done;
4398 error = open_log_view(view, start_id, repo, head_ref_name,
4399 in_repo_path, log_branches);
4400 if (error)
4401 goto done;
4402 if (worktree) {
4403 /* Release work tree lock. */
4404 got_worktree_close(worktree);
4405 worktree = NULL;
4407 error = view_loop(view);
4408 done:
4409 free(in_repo_path);
4410 free(repo_path);
4411 free(cwd);
4412 free(start_id);
4413 free(label);
4414 if (ref)
4415 got_ref_close(ref);
4416 if (repo) {
4417 const struct got_error *close_err = got_repo_close(repo);
4418 if (error == NULL)
4419 error = close_err;
4421 if (worktree)
4422 got_worktree_close(worktree);
4423 if (pack_fds) {
4424 const struct got_error *pack_err =
4425 got_repo_pack_fds_close(pack_fds);
4426 if (error == NULL)
4427 error = pack_err;
4429 tog_free_refs();
4430 return error;
4433 __dead static void
4434 usage_diff(void)
4436 endwin();
4437 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4438 "object1 object2\n", getprogname());
4439 exit(1);
4442 static int
4443 match_line(const char *line, regex_t *regex, size_t nmatch,
4444 regmatch_t *regmatch)
4446 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4449 static struct tog_color *
4450 match_color(struct tog_colors *colors, const char *line)
4452 struct tog_color *tc = NULL;
4454 STAILQ_FOREACH(tc, colors, entry) {
4455 if (match_line(line, &tc->regex, 0, NULL))
4456 return tc;
4459 return NULL;
4462 static const struct got_error *
4463 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4464 WINDOW *window, int skipcol, regmatch_t *regmatch)
4466 const struct got_error *err = NULL;
4467 char *exstr = NULL;
4468 wchar_t *wline = NULL;
4469 int rme, rms, n, width, scrollx;
4470 int width0 = 0, width1 = 0, width2 = 0;
4471 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4473 *wtotal = 0;
4475 rms = regmatch->rm_so;
4476 rme = regmatch->rm_eo;
4478 err = expand_tab(&exstr, line);
4479 if (err)
4480 return err;
4482 /* Split the line into 3 segments, according to match offsets. */
4483 seg0 = strndup(exstr, rms);
4484 if (seg0 == NULL) {
4485 err = got_error_from_errno("strndup");
4486 goto done;
4488 seg1 = strndup(exstr + rms, rme - rms);
4489 if (seg1 == NULL) {
4490 err = got_error_from_errno("strndup");
4491 goto done;
4493 seg2 = strdup(exstr + rme);
4494 if (seg2 == NULL) {
4495 err = got_error_from_errno("strndup");
4496 goto done;
4499 /* draw up to matched token if we haven't scrolled past it */
4500 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4501 col_tab_align, 1);
4502 if (err)
4503 goto done;
4504 n = MAX(width0 - skipcol, 0);
4505 if (n) {
4506 free(wline);
4507 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4508 wlimit, col_tab_align, 1);
4509 if (err)
4510 goto done;
4511 waddwstr(window, &wline[scrollx]);
4512 wlimit -= width;
4513 *wtotal += width;
4516 if (wlimit > 0) {
4517 int i = 0, w = 0;
4518 size_t wlen;
4520 free(wline);
4521 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4522 col_tab_align, 1);
4523 if (err)
4524 goto done;
4525 wlen = wcslen(wline);
4526 while (i < wlen) {
4527 width = wcwidth(wline[i]);
4528 if (width == -1) {
4529 /* should not happen, tabs are expanded */
4530 err = got_error(GOT_ERR_RANGE);
4531 goto done;
4533 if (width0 + w + width > skipcol)
4534 break;
4535 w += width;
4536 i++;
4538 /* draw (visible part of) matched token (if scrolled into it) */
4539 if (width1 - w > 0) {
4540 wattron(window, A_STANDOUT);
4541 waddwstr(window, &wline[i]);
4542 wattroff(window, A_STANDOUT);
4543 wlimit -= (width1 - w);
4544 *wtotal += (width1 - w);
4548 if (wlimit > 0) { /* draw rest of line */
4549 free(wline);
4550 if (skipcol > width0 + width1) {
4551 err = format_line(&wline, &width2, &scrollx, seg2,
4552 skipcol - (width0 + width1), wlimit,
4553 col_tab_align, 1);
4554 if (err)
4555 goto done;
4556 waddwstr(window, &wline[scrollx]);
4557 } else {
4558 err = format_line(&wline, &width2, NULL, seg2, 0,
4559 wlimit, col_tab_align, 1);
4560 if (err)
4561 goto done;
4562 waddwstr(window, wline);
4564 *wtotal += width2;
4566 done:
4567 free(wline);
4568 free(exstr);
4569 free(seg0);
4570 free(seg1);
4571 free(seg2);
4572 return err;
4575 static int
4576 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4578 FILE *f = NULL;
4579 int *eof, *first, *selected;
4581 if (view->type == TOG_VIEW_DIFF) {
4582 struct tog_diff_view_state *s = &view->state.diff;
4584 first = &s->first_displayed_line;
4585 selected = first;
4586 eof = &s->eof;
4587 f = s->f;
4588 } else if (view->type == TOG_VIEW_HELP) {
4589 struct tog_help_view_state *s = &view->state.help;
4591 first = &s->first_displayed_line;
4592 selected = first;
4593 eof = &s->eof;
4594 f = s->f;
4595 } else if (view->type == TOG_VIEW_BLAME) {
4596 struct tog_blame_view_state *s = &view->state.blame;
4598 first = &s->first_displayed_line;
4599 selected = &s->selected_line;
4600 eof = &s->eof;
4601 f = s->blame.f;
4602 } else
4603 return 0;
4605 /* Center gline in the middle of the page like vi(1). */
4606 if (*lineno < view->gline - (view->nlines - 3) / 2)
4607 return 0;
4608 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4609 rewind(f);
4610 *eof = 0;
4611 *first = 1;
4612 *lineno = 0;
4613 *nprinted = 0;
4614 return 0;
4617 *selected = view->gline <= (view->nlines - 3) / 2 ?
4618 view->gline : (view->nlines - 3) / 2 + 1;
4619 view->gline = 0;
4621 return 1;
4624 static const struct got_error *
4625 draw_file(struct tog_view *view, const char *header)
4627 struct tog_diff_view_state *s = &view->state.diff;
4628 regmatch_t *regmatch = &view->regmatch;
4629 const struct got_error *err;
4630 int nprinted = 0;
4631 char *line;
4632 size_t linesize = 0;
4633 ssize_t linelen;
4634 wchar_t *wline;
4635 int width;
4636 int max_lines = view->nlines;
4637 int nlines = s->nlines;
4638 off_t line_offset;
4640 s->lineno = s->first_displayed_line - 1;
4641 line_offset = s->lines[s->first_displayed_line - 1].offset;
4642 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4643 return got_error_from_errno("fseek");
4645 werase(view->window);
4647 if (view->gline > s->nlines - 1)
4648 view->gline = s->nlines - 1;
4650 if (header) {
4651 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4652 1 : view->gline - (view->nlines - 3) / 2 :
4653 s->lineno + s->selected_line;
4655 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4656 return got_error_from_errno("asprintf");
4657 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4658 0, 0);
4659 free(line);
4660 if (err)
4661 return err;
4663 if (view_needs_focus_indication(view))
4664 wstandout(view->window);
4665 waddwstr(view->window, wline);
4666 free(wline);
4667 wline = NULL;
4668 while (width++ < view->ncols)
4669 waddch(view->window, ' ');
4670 if (view_needs_focus_indication(view))
4671 wstandend(view->window);
4673 if (max_lines <= 1)
4674 return NULL;
4675 max_lines--;
4678 s->eof = 0;
4679 view->maxx = 0;
4680 line = NULL;
4681 while (max_lines > 0 && nprinted < max_lines) {
4682 enum got_diff_line_type linetype;
4683 attr_t attr = 0;
4685 linelen = getline(&line, &linesize, s->f);
4686 if (linelen == -1) {
4687 if (feof(s->f)) {
4688 s->eof = 1;
4689 break;
4691 free(line);
4692 return got_ferror(s->f, GOT_ERR_IO);
4695 if (++s->lineno < s->first_displayed_line)
4696 continue;
4697 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4698 continue;
4699 if (s->lineno == view->hiline)
4700 attr = A_STANDOUT;
4702 /* Set view->maxx based on full line length. */
4703 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4704 view->x ? 1 : 0);
4705 if (err) {
4706 free(line);
4707 return err;
4709 view->maxx = MAX(view->maxx, width);
4710 free(wline);
4711 wline = NULL;
4713 linetype = s->lines[s->lineno].type;
4714 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4715 linetype < GOT_DIFF_LINE_CONTEXT)
4716 attr |= COLOR_PAIR(linetype);
4717 if (attr)
4718 wattron(view->window, attr);
4719 if (s->first_displayed_line + nprinted == s->matched_line &&
4720 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4721 err = add_matched_line(&width, line, view->ncols, 0,
4722 view->window, view->x, regmatch);
4723 if (err) {
4724 free(line);
4725 return err;
4727 } else {
4728 int skip;
4729 err = format_line(&wline, &width, &skip, line,
4730 view->x, view->ncols, 0, view->x ? 1 : 0);
4731 if (err) {
4732 free(line);
4733 return err;
4735 waddwstr(view->window, &wline[skip]);
4736 free(wline);
4737 wline = NULL;
4739 if (s->lineno == view->hiline) {
4740 /* highlight full gline length */
4741 while (width++ < view->ncols)
4742 waddch(view->window, ' ');
4743 } else {
4744 if (width <= view->ncols - 1)
4745 waddch(view->window, '\n');
4747 if (attr)
4748 wattroff(view->window, attr);
4749 if (++nprinted == 1)
4750 s->first_displayed_line = s->lineno;
4752 free(line);
4753 if (nprinted >= 1)
4754 s->last_displayed_line = s->first_displayed_line +
4755 (nprinted - 1);
4756 else
4757 s->last_displayed_line = s->first_displayed_line;
4759 view_border(view);
4761 if (s->eof) {
4762 while (nprinted < view->nlines) {
4763 waddch(view->window, '\n');
4764 nprinted++;
4767 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4768 view->ncols, 0, 0);
4769 if (err) {
4770 return err;
4773 wstandout(view->window);
4774 waddwstr(view->window, wline);
4775 free(wline);
4776 wline = NULL;
4777 wstandend(view->window);
4780 return NULL;
4783 static char *
4784 get_datestr(time_t *time, char *datebuf)
4786 struct tm mytm, *tm;
4787 char *p, *s;
4789 tm = gmtime_r(time, &mytm);
4790 if (tm == NULL)
4791 return NULL;
4792 s = asctime_r(tm, datebuf);
4793 if (s == NULL)
4794 return NULL;
4795 p = strchr(s, '\n');
4796 if (p)
4797 *p = '\0';
4798 return s;
4801 static const struct got_error *
4802 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4803 off_t off, uint8_t type)
4805 struct got_diff_line *p;
4807 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4808 if (p == NULL)
4809 return got_error_from_errno("reallocarray");
4810 *lines = p;
4811 (*lines)[*nlines].offset = off;
4812 (*lines)[*nlines].type = type;
4813 (*nlines)++;
4815 return NULL;
4818 static const struct got_error *
4819 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4820 struct got_diff_line *s_lines, size_t s_nlines)
4822 struct got_diff_line *p;
4823 char buf[BUFSIZ];
4824 size_t i, r;
4826 if (fseeko(src, 0L, SEEK_SET) == -1)
4827 return got_error_from_errno("fseeko");
4829 for (;;) {
4830 r = fread(buf, 1, sizeof(buf), src);
4831 if (r == 0) {
4832 if (ferror(src))
4833 return got_error_from_errno("fread");
4834 if (feof(src))
4835 break;
4837 if (fwrite(buf, 1, r, dst) != r)
4838 return got_ferror(dst, GOT_ERR_IO);
4841 if (s_nlines == 0 && *d_nlines == 0)
4842 return NULL;
4845 * If commit info was in dst, increment line offsets
4846 * of the appended diff content, but skip s_lines[0]
4847 * because offset zero is already in *d_lines.
4849 if (*d_nlines > 0) {
4850 for (i = 1; i < s_nlines; ++i)
4851 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4853 if (s_nlines > 0) {
4854 --s_nlines;
4855 ++s_lines;
4859 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4860 if (p == NULL) {
4861 /* d_lines is freed in close_diff_view() */
4862 return got_error_from_errno("reallocarray");
4865 *d_lines = p;
4867 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4868 *d_nlines += s_nlines;
4870 return NULL;
4873 static const struct got_error *
4874 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4875 struct got_object_id *commit_id, struct got_reflist_head *refs,
4876 struct got_repository *repo, int ignore_ws, int force_text_diff,
4877 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4879 const struct got_error *err = NULL;
4880 char datebuf[26], *datestr;
4881 struct got_commit_object *commit;
4882 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4883 time_t committer_time;
4884 const char *author, *committer;
4885 char *refs_str = NULL;
4886 struct got_pathlist_entry *pe;
4887 off_t outoff = 0;
4888 int n;
4890 if (refs) {
4891 err = build_refs_str(&refs_str, refs, commit_id, repo);
4892 if (err)
4893 return err;
4896 err = got_object_open_as_commit(&commit, repo, commit_id);
4897 if (err)
4898 return err;
4900 err = got_object_id_str(&id_str, commit_id);
4901 if (err) {
4902 err = got_error_from_errno("got_object_id_str");
4903 goto done;
4906 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4907 if (err)
4908 goto done;
4910 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4911 refs_str ? refs_str : "", refs_str ? ")" : "");
4912 if (n < 0) {
4913 err = got_error_from_errno("fprintf");
4914 goto done;
4916 outoff += n;
4917 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4918 if (err)
4919 goto done;
4921 n = fprintf(outfile, "from: %s\n",
4922 got_object_commit_get_author(commit));
4923 if (n < 0) {
4924 err = got_error_from_errno("fprintf");
4925 goto done;
4927 outoff += n;
4928 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4929 if (err)
4930 goto done;
4932 author = got_object_commit_get_author(commit);
4933 committer = got_object_commit_get_committer(commit);
4934 if (strcmp(author, committer) != 0) {
4935 n = fprintf(outfile, "via: %s\n", committer);
4936 if (n < 0) {
4937 err = got_error_from_errno("fprintf");
4938 goto done;
4940 outoff += n;
4941 err = add_line_metadata(lines, nlines, outoff,
4942 GOT_DIFF_LINE_AUTHOR);
4943 if (err)
4944 goto done;
4946 committer_time = got_object_commit_get_committer_time(commit);
4947 datestr = get_datestr(&committer_time, datebuf);
4948 if (datestr) {
4949 n = fprintf(outfile, "date: %s UTC\n", datestr);
4950 if (n < 0) {
4951 err = got_error_from_errno("fprintf");
4952 goto done;
4954 outoff += n;
4955 err = add_line_metadata(lines, nlines, outoff,
4956 GOT_DIFF_LINE_DATE);
4957 if (err)
4958 goto done;
4960 if (got_object_commit_get_nparents(commit) > 1) {
4961 const struct got_object_id_queue *parent_ids;
4962 struct got_object_qid *qid;
4963 int pn = 1;
4964 parent_ids = got_object_commit_get_parent_ids(commit);
4965 STAILQ_FOREACH(qid, parent_ids, entry) {
4966 err = got_object_id_str(&id_str, &qid->id);
4967 if (err)
4968 goto done;
4969 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4970 if (n < 0) {
4971 err = got_error_from_errno("fprintf");
4972 goto done;
4974 outoff += n;
4975 err = add_line_metadata(lines, nlines, outoff,
4976 GOT_DIFF_LINE_META);
4977 if (err)
4978 goto done;
4979 free(id_str);
4980 id_str = NULL;
4984 err = got_object_commit_get_logmsg(&logmsg, commit);
4985 if (err)
4986 goto done;
4987 s = logmsg;
4988 while ((line = strsep(&s, "\n")) != NULL) {
4989 n = fprintf(outfile, "%s\n", line);
4990 if (n < 0) {
4991 err = got_error_from_errno("fprintf");
4992 goto done;
4994 outoff += n;
4995 err = add_line_metadata(lines, nlines, outoff,
4996 GOT_DIFF_LINE_LOGMSG);
4997 if (err)
4998 goto done;
5001 TAILQ_FOREACH(pe, dsa->paths, entry) {
5002 struct got_diff_changed_path *cp = pe->data;
5003 int pad = dsa->max_path_len - pe->path_len + 1;
5005 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5006 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5007 dsa->rm_cols + 1, cp->rm);
5008 if (n < 0) {
5009 err = got_error_from_errno("fprintf");
5010 goto done;
5012 outoff += n;
5013 err = add_line_metadata(lines, nlines, outoff,
5014 GOT_DIFF_LINE_CHANGES);
5015 if (err)
5016 goto done;
5019 fputc('\n', outfile);
5020 outoff++;
5021 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5022 if (err)
5023 goto done;
5025 n = fprintf(outfile,
5026 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5027 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5028 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5029 if (n < 0) {
5030 err = got_error_from_errno("fprintf");
5031 goto done;
5033 outoff += n;
5034 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5035 if (err)
5036 goto done;
5038 fputc('\n', outfile);
5039 outoff++;
5040 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5041 done:
5042 free(id_str);
5043 free(logmsg);
5044 free(refs_str);
5045 got_object_commit_close(commit);
5046 if (err) {
5047 free(*lines);
5048 *lines = NULL;
5049 *nlines = 0;
5051 return err;
5054 static const struct got_error *
5055 create_diff(struct tog_diff_view_state *s)
5057 const struct got_error *err = NULL;
5058 FILE *f = NULL, *tmp_diff_file = NULL;
5059 int obj_type;
5060 struct got_diff_line *lines = NULL;
5061 struct got_pathlist_head changed_paths;
5063 TAILQ_INIT(&changed_paths);
5065 free(s->lines);
5066 s->lines = malloc(sizeof(*s->lines));
5067 if (s->lines == NULL)
5068 return got_error_from_errno("malloc");
5069 s->nlines = 0;
5071 f = got_opentemp();
5072 if (f == NULL) {
5073 err = got_error_from_errno("got_opentemp");
5074 goto done;
5076 tmp_diff_file = got_opentemp();
5077 if (tmp_diff_file == NULL) {
5078 err = got_error_from_errno("got_opentemp");
5079 goto done;
5081 if (s->f && fclose(s->f) == EOF) {
5082 err = got_error_from_errno("fclose");
5083 goto done;
5085 s->f = f;
5087 if (s->id1)
5088 err = got_object_get_type(&obj_type, s->repo, s->id1);
5089 else
5090 err = got_object_get_type(&obj_type, s->repo, s->id2);
5091 if (err)
5092 goto done;
5094 switch (obj_type) {
5095 case GOT_OBJ_TYPE_BLOB:
5096 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5097 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5098 s->label1, s->label2, tog_diff_algo, s->diff_context,
5099 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5100 s->f);
5101 break;
5102 case GOT_OBJ_TYPE_TREE:
5103 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5104 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5105 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5106 s->force_text_diff, NULL, s->repo, s->f);
5107 break;
5108 case GOT_OBJ_TYPE_COMMIT: {
5109 const struct got_object_id_queue *parent_ids;
5110 struct got_object_qid *pid;
5111 struct got_commit_object *commit2;
5112 struct got_reflist_head *refs;
5113 size_t nlines = 0;
5114 struct got_diffstat_cb_arg dsa = {
5115 0, 0, 0, 0, 0, 0,
5116 &changed_paths,
5117 s->ignore_whitespace,
5118 s->force_text_diff,
5119 tog_diff_algo
5122 lines = malloc(sizeof(*lines));
5123 if (lines == NULL) {
5124 err = got_error_from_errno("malloc");
5125 goto done;
5128 /* build diff first in tmp file then append to commit info */
5129 err = got_diff_objects_as_commits(&lines, &nlines,
5130 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5131 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5132 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5133 if (err)
5134 break;
5136 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5137 if (err)
5138 goto done;
5139 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5140 /* Show commit info if we're diffing to a parent/root commit. */
5141 if (s->id1 == NULL) {
5142 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5143 refs, s->repo, s->ignore_whitespace,
5144 s->force_text_diff, &dsa, s->f);
5145 if (err)
5146 goto done;
5147 } else {
5148 parent_ids = got_object_commit_get_parent_ids(commit2);
5149 STAILQ_FOREACH(pid, parent_ids, entry) {
5150 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5151 err = write_commit_info(&s->lines,
5152 &s->nlines, s->id2, refs, s->repo,
5153 s->ignore_whitespace,
5154 s->force_text_diff, &dsa, s->f);
5155 if (err)
5156 goto done;
5157 break;
5161 got_object_commit_close(commit2);
5163 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5164 lines, nlines);
5165 break;
5167 default:
5168 err = got_error(GOT_ERR_OBJ_TYPE);
5169 break;
5171 done:
5172 free(lines);
5173 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5174 if (s->f && fflush(s->f) != 0 && err == NULL)
5175 err = got_error_from_errno("fflush");
5176 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5177 err = got_error_from_errno("fclose");
5178 return err;
5181 static void
5182 diff_view_indicate_progress(struct tog_view *view)
5184 mvwaddstr(view->window, 0, 0, "diffing...");
5185 update_panels();
5186 doupdate();
5189 static const struct got_error *
5190 search_start_diff_view(struct tog_view *view)
5192 struct tog_diff_view_state *s = &view->state.diff;
5194 s->matched_line = 0;
5195 return NULL;
5198 static void
5199 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5200 size_t *nlines, int **first, int **last, int **match, int **selected)
5202 struct tog_diff_view_state *s = &view->state.diff;
5204 *f = s->f;
5205 *nlines = s->nlines;
5206 *line_offsets = NULL;
5207 *match = &s->matched_line;
5208 *first = &s->first_displayed_line;
5209 *last = &s->last_displayed_line;
5210 *selected = &s->selected_line;
5213 static const struct got_error *
5214 search_next_view_match(struct tog_view *view)
5216 const struct got_error *err = NULL;
5217 FILE *f;
5218 int lineno;
5219 char *line = NULL;
5220 size_t linesize = 0;
5221 ssize_t linelen;
5222 off_t *line_offsets;
5223 size_t nlines = 0;
5224 int *first, *last, *match, *selected;
5226 if (!view->search_setup)
5227 return got_error_msg(GOT_ERR_NOT_IMPL,
5228 "view search not supported");
5229 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5230 &match, &selected);
5232 if (!view->searching) {
5233 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5234 return NULL;
5237 if (*match) {
5238 if (view->searching == TOG_SEARCH_FORWARD)
5239 lineno = *first + 1;
5240 else
5241 lineno = *first - 1;
5242 } else
5243 lineno = *first - 1 + *selected;
5245 while (1) {
5246 off_t offset;
5248 if (lineno <= 0 || lineno > nlines) {
5249 if (*match == 0) {
5250 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5251 break;
5254 if (view->searching == TOG_SEARCH_FORWARD)
5255 lineno = 1;
5256 else
5257 lineno = nlines;
5260 offset = view->type == TOG_VIEW_DIFF ?
5261 view->state.diff.lines[lineno - 1].offset :
5262 line_offsets[lineno - 1];
5263 if (fseeko(f, offset, SEEK_SET) != 0) {
5264 free(line);
5265 return got_error_from_errno("fseeko");
5267 linelen = getline(&line, &linesize, f);
5268 if (linelen != -1) {
5269 char *exstr;
5270 err = expand_tab(&exstr, line);
5271 if (err)
5272 break;
5273 if (match_line(exstr, &view->regex, 1,
5274 &view->regmatch)) {
5275 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5276 *match = lineno;
5277 free(exstr);
5278 break;
5280 free(exstr);
5282 if (view->searching == TOG_SEARCH_FORWARD)
5283 lineno++;
5284 else
5285 lineno--;
5287 free(line);
5289 if (*match) {
5290 *first = *match;
5291 *selected = 1;
5294 return err;
5297 static const struct got_error *
5298 close_diff_view(struct tog_view *view)
5300 const struct got_error *err = NULL;
5301 struct tog_diff_view_state *s = &view->state.diff;
5303 free(s->id1);
5304 s->id1 = NULL;
5305 free(s->id2);
5306 s->id2 = NULL;
5307 if (s->f && fclose(s->f) == EOF)
5308 err = got_error_from_errno("fclose");
5309 s->f = NULL;
5310 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5311 err = got_error_from_errno("fclose");
5312 s->f1 = NULL;
5313 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5314 err = got_error_from_errno("fclose");
5315 s->f2 = NULL;
5316 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5317 err = got_error_from_errno("close");
5318 s->fd1 = -1;
5319 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5320 err = got_error_from_errno("close");
5321 s->fd2 = -1;
5322 free(s->lines);
5323 s->lines = NULL;
5324 s->nlines = 0;
5325 return err;
5328 static const struct got_error *
5329 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5330 struct got_object_id *id2, const char *label1, const char *label2,
5331 int diff_context, int ignore_whitespace, int force_text_diff,
5332 struct tog_view *parent_view, struct got_repository *repo)
5334 const struct got_error *err;
5335 struct tog_diff_view_state *s = &view->state.diff;
5337 memset(s, 0, sizeof(*s));
5338 s->fd1 = -1;
5339 s->fd2 = -1;
5341 if (id1 != NULL && id2 != NULL) {
5342 int type1, type2;
5344 err = got_object_get_type(&type1, repo, id1);
5345 if (err)
5346 goto done;
5347 err = got_object_get_type(&type2, repo, id2);
5348 if (err)
5349 goto done;
5351 if (type1 != type2) {
5352 err = got_error(GOT_ERR_OBJ_TYPE);
5353 goto done;
5356 s->first_displayed_line = 1;
5357 s->last_displayed_line = view->nlines;
5358 s->selected_line = 1;
5359 s->repo = repo;
5360 s->id1 = id1;
5361 s->id2 = id2;
5362 s->label1 = label1;
5363 s->label2 = label2;
5365 if (id1) {
5366 s->id1 = got_object_id_dup(id1);
5367 if (s->id1 == NULL) {
5368 err = got_error_from_errno("got_object_id_dup");
5369 goto done;
5371 } else
5372 s->id1 = NULL;
5374 s->id2 = got_object_id_dup(id2);
5375 if (s->id2 == NULL) {
5376 err = got_error_from_errno("got_object_id_dup");
5377 goto done;
5380 s->f1 = got_opentemp();
5381 if (s->f1 == NULL) {
5382 err = got_error_from_errno("got_opentemp");
5383 goto done;
5386 s->f2 = got_opentemp();
5387 if (s->f2 == NULL) {
5388 err = got_error_from_errno("got_opentemp");
5389 goto done;
5392 s->fd1 = got_opentempfd();
5393 if (s->fd1 == -1) {
5394 err = got_error_from_errno("got_opentempfd");
5395 goto done;
5398 s->fd2 = got_opentempfd();
5399 if (s->fd2 == -1) {
5400 err = got_error_from_errno("got_opentempfd");
5401 goto done;
5404 s->diff_context = diff_context;
5405 s->ignore_whitespace = ignore_whitespace;
5406 s->force_text_diff = force_text_diff;
5407 s->parent_view = parent_view;
5408 s->repo = repo;
5410 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5411 int rc;
5413 rc = init_pair(GOT_DIFF_LINE_MINUS,
5414 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5415 if (rc != ERR)
5416 rc = init_pair(GOT_DIFF_LINE_PLUS,
5417 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5418 if (rc != ERR)
5419 rc = init_pair(GOT_DIFF_LINE_HUNK,
5420 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5421 if (rc != ERR)
5422 rc = init_pair(GOT_DIFF_LINE_META,
5423 get_color_value("TOG_COLOR_DIFF_META"), -1);
5424 if (rc != ERR)
5425 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5426 get_color_value("TOG_COLOR_DIFF_META"), -1);
5427 if (rc != ERR)
5428 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5429 get_color_value("TOG_COLOR_DIFF_META"), -1);
5430 if (rc != ERR)
5431 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5432 get_color_value("TOG_COLOR_DIFF_META"), -1);
5433 if (rc != ERR)
5434 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5435 get_color_value("TOG_COLOR_AUTHOR"), -1);
5436 if (rc != ERR)
5437 rc = init_pair(GOT_DIFF_LINE_DATE,
5438 get_color_value("TOG_COLOR_DATE"), -1);
5439 if (rc == ERR) {
5440 err = got_error(GOT_ERR_RANGE);
5441 goto done;
5445 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5446 view_is_splitscreen(view))
5447 show_log_view(parent_view); /* draw border */
5448 diff_view_indicate_progress(view);
5450 err = create_diff(s);
5452 view->show = show_diff_view;
5453 view->input = input_diff_view;
5454 view->reset = reset_diff_view;
5455 view->close = close_diff_view;
5456 view->search_start = search_start_diff_view;
5457 view->search_setup = search_setup_diff_view;
5458 view->search_next = search_next_view_match;
5459 done:
5460 if (err) {
5461 if (view->close == NULL)
5462 close_diff_view(view);
5463 view_close(view);
5465 return err;
5468 static const struct got_error *
5469 show_diff_view(struct tog_view *view)
5471 const struct got_error *err;
5472 struct tog_diff_view_state *s = &view->state.diff;
5473 char *id_str1 = NULL, *id_str2, *header;
5474 const char *label1, *label2;
5476 if (s->id1) {
5477 err = got_object_id_str(&id_str1, s->id1);
5478 if (err)
5479 return err;
5480 label1 = s->label1 ? s->label1 : id_str1;
5481 } else
5482 label1 = "/dev/null";
5484 err = got_object_id_str(&id_str2, s->id2);
5485 if (err)
5486 return err;
5487 label2 = s->label2 ? s->label2 : id_str2;
5489 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5490 err = got_error_from_errno("asprintf");
5491 free(id_str1);
5492 free(id_str2);
5493 return err;
5495 free(id_str1);
5496 free(id_str2);
5498 err = draw_file(view, header);
5499 free(header);
5500 return err;
5503 static const struct got_error *
5504 set_selected_commit(struct tog_diff_view_state *s,
5505 struct commit_queue_entry *entry)
5507 const struct got_error *err;
5508 const struct got_object_id_queue *parent_ids;
5509 struct got_commit_object *selected_commit;
5510 struct got_object_qid *pid;
5512 free(s->id2);
5513 s->id2 = got_object_id_dup(entry->id);
5514 if (s->id2 == NULL)
5515 return got_error_from_errno("got_object_id_dup");
5517 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5518 if (err)
5519 return err;
5520 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5521 free(s->id1);
5522 pid = STAILQ_FIRST(parent_ids);
5523 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5524 got_object_commit_close(selected_commit);
5525 return NULL;
5528 static const struct got_error *
5529 reset_diff_view(struct tog_view *view)
5531 struct tog_diff_view_state *s = &view->state.diff;
5533 view->count = 0;
5534 wclear(view->window);
5535 s->first_displayed_line = 1;
5536 s->last_displayed_line = view->nlines;
5537 s->matched_line = 0;
5538 diff_view_indicate_progress(view);
5539 return create_diff(s);
5542 static void
5543 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5545 int start, i;
5547 i = start = s->first_displayed_line - 1;
5549 while (s->lines[i].type != type) {
5550 if (i == 0)
5551 i = s->nlines - 1;
5552 if (--i == start)
5553 return; /* do nothing, requested type not in file */
5556 s->selected_line = 1;
5557 s->first_displayed_line = i;
5560 static void
5561 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5563 int start, i;
5565 i = start = s->first_displayed_line + 1;
5567 while (s->lines[i].type != type) {
5568 if (i == s->nlines - 1)
5569 i = 0;
5570 if (++i == start)
5571 return; /* do nothing, requested type not in file */
5574 s->selected_line = 1;
5575 s->first_displayed_line = i;
5578 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5579 int, int, int);
5580 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5581 int, int);
5583 static const struct got_error *
5584 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5586 const struct got_error *err = NULL;
5587 struct tog_diff_view_state *s = &view->state.diff;
5588 struct tog_log_view_state *ls;
5589 struct commit_queue_entry *old_selected_entry;
5590 char *line = NULL;
5591 size_t linesize = 0;
5592 ssize_t linelen;
5593 int i, nscroll = view->nlines - 1, up = 0;
5595 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5597 switch (ch) {
5598 case '0':
5599 case '$':
5600 case KEY_RIGHT:
5601 case 'l':
5602 case KEY_LEFT:
5603 case 'h':
5604 horizontal_scroll_input(view, ch);
5605 break;
5606 case 'a':
5607 case 'w':
5608 if (ch == 'a') {
5609 s->force_text_diff = !s->force_text_diff;
5610 view->action = s->force_text_diff ?
5611 "force ASCII text enabled" :
5612 "force ASCII text disabled";
5614 else if (ch == 'w') {
5615 s->ignore_whitespace = !s->ignore_whitespace;
5616 view->action = s->ignore_whitespace ?
5617 "ignore whitespace enabled" :
5618 "ignore whitespace disabled";
5620 err = reset_diff_view(view);
5621 break;
5622 case 'g':
5623 case KEY_HOME:
5624 s->first_displayed_line = 1;
5625 view->count = 0;
5626 break;
5627 case 'G':
5628 case KEY_END:
5629 view->count = 0;
5630 if (s->eof)
5631 break;
5633 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5634 s->eof = 1;
5635 break;
5636 case 'k':
5637 case KEY_UP:
5638 case CTRL('p'):
5639 if (s->first_displayed_line > 1)
5640 s->first_displayed_line--;
5641 else
5642 view->count = 0;
5643 break;
5644 case CTRL('u'):
5645 case 'u':
5646 nscroll /= 2;
5647 /* FALL THROUGH */
5648 case KEY_PPAGE:
5649 case CTRL('b'):
5650 case 'b':
5651 if (s->first_displayed_line == 1) {
5652 view->count = 0;
5653 break;
5655 i = 0;
5656 while (i++ < nscroll && s->first_displayed_line > 1)
5657 s->first_displayed_line--;
5658 break;
5659 case 'j':
5660 case KEY_DOWN:
5661 case CTRL('n'):
5662 if (!s->eof)
5663 s->first_displayed_line++;
5664 else
5665 view->count = 0;
5666 break;
5667 case CTRL('d'):
5668 case 'd':
5669 nscroll /= 2;
5670 /* FALL THROUGH */
5671 case KEY_NPAGE:
5672 case CTRL('f'):
5673 case 'f':
5674 case ' ':
5675 if (s->eof) {
5676 view->count = 0;
5677 break;
5679 i = 0;
5680 while (!s->eof && i++ < nscroll) {
5681 linelen = getline(&line, &linesize, s->f);
5682 s->first_displayed_line++;
5683 if (linelen == -1) {
5684 if (feof(s->f)) {
5685 s->eof = 1;
5686 } else
5687 err = got_ferror(s->f, GOT_ERR_IO);
5688 break;
5691 free(line);
5692 break;
5693 case '(':
5694 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5695 break;
5696 case ')':
5697 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5698 break;
5699 case '{':
5700 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5701 break;
5702 case '}':
5703 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5704 break;
5705 case '[':
5706 if (s->diff_context > 0) {
5707 s->diff_context--;
5708 s->matched_line = 0;
5709 diff_view_indicate_progress(view);
5710 err = create_diff(s);
5711 if (s->first_displayed_line + view->nlines - 1 >
5712 s->nlines) {
5713 s->first_displayed_line = 1;
5714 s->last_displayed_line = view->nlines;
5716 } else
5717 view->count = 0;
5718 break;
5719 case ']':
5720 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5721 s->diff_context++;
5722 s->matched_line = 0;
5723 diff_view_indicate_progress(view);
5724 err = create_diff(s);
5725 } else
5726 view->count = 0;
5727 break;
5728 case '<':
5729 case ',':
5730 case 'K':
5731 up = 1;
5732 /* FALL THROUGH */
5733 case '>':
5734 case '.':
5735 case 'J':
5736 if (s->parent_view == NULL) {
5737 view->count = 0;
5738 break;
5740 s->parent_view->count = view->count;
5742 if (s->parent_view->type == TOG_VIEW_LOG) {
5743 ls = &s->parent_view->state.log;
5744 old_selected_entry = ls->selected_entry;
5746 err = input_log_view(NULL, s->parent_view,
5747 up ? KEY_UP : KEY_DOWN);
5748 if (err)
5749 break;
5750 view->count = s->parent_view->count;
5752 if (old_selected_entry == ls->selected_entry)
5753 break;
5755 err = set_selected_commit(s, ls->selected_entry);
5756 if (err)
5757 break;
5758 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5759 struct tog_blame_view_state *bs;
5760 struct got_object_id *id, *prev_id;
5762 bs = &s->parent_view->state.blame;
5763 prev_id = get_annotation_for_line(bs->blame.lines,
5764 bs->blame.nlines, bs->last_diffed_line);
5766 err = input_blame_view(&view, s->parent_view,
5767 up ? KEY_UP : KEY_DOWN);
5768 if (err)
5769 break;
5770 view->count = s->parent_view->count;
5772 if (prev_id == NULL)
5773 break;
5774 id = get_selected_commit_id(bs->blame.lines,
5775 bs->blame.nlines, bs->first_displayed_line,
5776 bs->selected_line);
5777 if (id == NULL)
5778 break;
5780 if (!got_object_id_cmp(prev_id, id))
5781 break;
5783 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5784 if (err)
5785 break;
5787 s->first_displayed_line = 1;
5788 s->last_displayed_line = view->nlines;
5789 s->matched_line = 0;
5790 view->x = 0;
5792 diff_view_indicate_progress(view);
5793 err = create_diff(s);
5794 break;
5795 default:
5796 view->count = 0;
5797 break;
5800 return err;
5803 static const struct got_error *
5804 cmd_diff(int argc, char *argv[])
5806 const struct got_error *error;
5807 struct got_repository *repo = NULL;
5808 struct got_worktree *worktree = NULL;
5809 struct got_object_id *id1 = NULL, *id2 = NULL;
5810 char *repo_path = NULL, *cwd = NULL;
5811 char *id_str1 = NULL, *id_str2 = NULL;
5812 char *label1 = NULL, *label2 = NULL;
5813 int diff_context = 3, ignore_whitespace = 0;
5814 int ch, force_text_diff = 0;
5815 const char *errstr;
5816 struct tog_view *view;
5817 int *pack_fds = NULL;
5819 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5820 switch (ch) {
5821 case 'a':
5822 force_text_diff = 1;
5823 break;
5824 case 'C':
5825 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5826 &errstr);
5827 if (errstr != NULL)
5828 errx(1, "number of context lines is %s: %s",
5829 errstr, errstr);
5830 break;
5831 case 'r':
5832 repo_path = realpath(optarg, NULL);
5833 if (repo_path == NULL)
5834 return got_error_from_errno2("realpath",
5835 optarg);
5836 got_path_strip_trailing_slashes(repo_path);
5837 break;
5838 case 'w':
5839 ignore_whitespace = 1;
5840 break;
5841 default:
5842 usage_diff();
5843 /* NOTREACHED */
5847 argc -= optind;
5848 argv += optind;
5850 if (argc == 0) {
5851 usage_diff(); /* TODO show local worktree changes */
5852 } else if (argc == 2) {
5853 id_str1 = argv[0];
5854 id_str2 = argv[1];
5855 } else
5856 usage_diff();
5858 error = got_repo_pack_fds_open(&pack_fds);
5859 if (error)
5860 goto done;
5862 if (repo_path == NULL) {
5863 cwd = getcwd(NULL, 0);
5864 if (cwd == NULL)
5865 return got_error_from_errno("getcwd");
5866 error = got_worktree_open(&worktree, cwd);
5867 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5868 goto done;
5869 if (worktree)
5870 repo_path =
5871 strdup(got_worktree_get_repo_path(worktree));
5872 else
5873 repo_path = strdup(cwd);
5874 if (repo_path == NULL) {
5875 error = got_error_from_errno("strdup");
5876 goto done;
5880 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5881 if (error)
5882 goto done;
5884 init_curses();
5886 error = apply_unveil(got_repo_get_path(repo), NULL);
5887 if (error)
5888 goto done;
5890 error = tog_load_refs(repo, 0);
5891 if (error)
5892 goto done;
5894 error = got_repo_match_object_id(&id1, &label1, id_str1,
5895 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5896 if (error)
5897 goto done;
5899 error = got_repo_match_object_id(&id2, &label2, id_str2,
5900 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5901 if (error)
5902 goto done;
5904 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5905 if (view == NULL) {
5906 error = got_error_from_errno("view_open");
5907 goto done;
5909 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5910 ignore_whitespace, force_text_diff, NULL, repo);
5911 if (error)
5912 goto done;
5913 error = view_loop(view);
5914 done:
5915 free(label1);
5916 free(label2);
5917 free(repo_path);
5918 free(cwd);
5919 if (repo) {
5920 const struct got_error *close_err = got_repo_close(repo);
5921 if (error == NULL)
5922 error = close_err;
5924 if (worktree)
5925 got_worktree_close(worktree);
5926 if (pack_fds) {
5927 const struct got_error *pack_err =
5928 got_repo_pack_fds_close(pack_fds);
5929 if (error == NULL)
5930 error = pack_err;
5932 tog_free_refs();
5933 return error;
5936 __dead static void
5937 usage_blame(void)
5939 endwin();
5940 fprintf(stderr,
5941 "usage: %s blame [-c commit] [-r repository-path] path\n",
5942 getprogname());
5943 exit(1);
5946 struct tog_blame_line {
5947 int annotated;
5948 struct got_object_id *id;
5951 static const struct got_error *
5952 draw_blame(struct tog_view *view)
5954 struct tog_blame_view_state *s = &view->state.blame;
5955 struct tog_blame *blame = &s->blame;
5956 regmatch_t *regmatch = &view->regmatch;
5957 const struct got_error *err;
5958 int lineno = 0, nprinted = 0;
5959 char *line = NULL;
5960 size_t linesize = 0;
5961 ssize_t linelen;
5962 wchar_t *wline;
5963 int width;
5964 struct tog_blame_line *blame_line;
5965 struct got_object_id *prev_id = NULL;
5966 char *id_str;
5967 struct tog_color *tc;
5969 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5970 if (err)
5971 return err;
5973 rewind(blame->f);
5974 werase(view->window);
5976 if (asprintf(&line, "commit %s", id_str) == -1) {
5977 err = got_error_from_errno("asprintf");
5978 free(id_str);
5979 return err;
5982 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5983 free(line);
5984 line = NULL;
5985 if (err)
5986 return err;
5987 if (view_needs_focus_indication(view))
5988 wstandout(view->window);
5989 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5990 if (tc)
5991 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5992 waddwstr(view->window, wline);
5993 while (width++ < view->ncols)
5994 waddch(view->window, ' ');
5995 if (tc)
5996 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5997 if (view_needs_focus_indication(view))
5998 wstandend(view->window);
5999 free(wline);
6000 wline = NULL;
6002 if (view->gline > blame->nlines)
6003 view->gline = blame->nlines;
6005 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6006 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6007 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6008 free(id_str);
6009 return got_error_from_errno("asprintf");
6011 free(id_str);
6012 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6013 free(line);
6014 line = NULL;
6015 if (err)
6016 return err;
6017 waddwstr(view->window, wline);
6018 free(wline);
6019 wline = NULL;
6020 if (width < view->ncols - 1)
6021 waddch(view->window, '\n');
6023 s->eof = 0;
6024 view->maxx = 0;
6025 while (nprinted < view->nlines - 2) {
6026 linelen = getline(&line, &linesize, blame->f);
6027 if (linelen == -1) {
6028 if (feof(blame->f)) {
6029 s->eof = 1;
6030 break;
6032 free(line);
6033 return got_ferror(blame->f, GOT_ERR_IO);
6035 if (++lineno < s->first_displayed_line)
6036 continue;
6037 if (view->gline && !gotoline(view, &lineno, &nprinted))
6038 continue;
6040 /* Set view->maxx based on full line length. */
6041 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6042 if (err) {
6043 free(line);
6044 return err;
6046 free(wline);
6047 wline = NULL;
6048 view->maxx = MAX(view->maxx, width);
6050 if (nprinted == s->selected_line - 1)
6051 wstandout(view->window);
6053 if (blame->nlines > 0) {
6054 blame_line = &blame->lines[lineno - 1];
6055 if (blame_line->annotated && prev_id &&
6056 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6057 !(nprinted == s->selected_line - 1)) {
6058 waddstr(view->window, " ");
6059 } else if (blame_line->annotated) {
6060 char *id_str;
6061 err = got_object_id_str(&id_str,
6062 blame_line->id);
6063 if (err) {
6064 free(line);
6065 return err;
6067 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6068 if (tc)
6069 wattr_on(view->window,
6070 COLOR_PAIR(tc->colorpair), NULL);
6071 wprintw(view->window, "%.8s", id_str);
6072 if (tc)
6073 wattr_off(view->window,
6074 COLOR_PAIR(tc->colorpair), NULL);
6075 free(id_str);
6076 prev_id = blame_line->id;
6077 } else {
6078 waddstr(view->window, "........");
6079 prev_id = NULL;
6081 } else {
6082 waddstr(view->window, "........");
6083 prev_id = NULL;
6086 if (nprinted == s->selected_line - 1)
6087 wstandend(view->window);
6088 waddstr(view->window, " ");
6090 if (view->ncols <= 9) {
6091 width = 9;
6092 } else if (s->first_displayed_line + nprinted ==
6093 s->matched_line &&
6094 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6095 err = add_matched_line(&width, line, view->ncols - 9, 9,
6096 view->window, view->x, regmatch);
6097 if (err) {
6098 free(line);
6099 return err;
6101 width += 9;
6102 } else {
6103 int skip;
6104 err = format_line(&wline, &width, &skip, line,
6105 view->x, view->ncols - 9, 9, 1);
6106 if (err) {
6107 free(line);
6108 return err;
6110 waddwstr(view->window, &wline[skip]);
6111 width += 9;
6112 free(wline);
6113 wline = NULL;
6116 if (width <= view->ncols - 1)
6117 waddch(view->window, '\n');
6118 if (++nprinted == 1)
6119 s->first_displayed_line = lineno;
6121 free(line);
6122 s->last_displayed_line = lineno;
6124 view_border(view);
6126 if (tog_io.wait_for_ui) {
6127 if (s->blame_complete)
6128 tog_io.wait_for_ui = 0;
6131 return NULL;
6134 static const struct got_error *
6135 blame_cb(void *arg, int nlines, int lineno,
6136 struct got_commit_object *commit, struct got_object_id *id)
6138 const struct got_error *err = NULL;
6139 struct tog_blame_cb_args *a = arg;
6140 struct tog_blame_line *line;
6141 int errcode;
6143 if (nlines != a->nlines ||
6144 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6145 return got_error(GOT_ERR_RANGE);
6147 errcode = pthread_mutex_lock(&tog_mutex);
6148 if (errcode)
6149 return got_error_set_errno(errcode, "pthread_mutex_lock");
6151 if (*a->quit) { /* user has quit the blame view */
6152 err = got_error(GOT_ERR_ITER_COMPLETED);
6153 goto done;
6156 if (lineno == -1)
6157 goto done; /* no change in this commit */
6159 line = &a->lines[lineno - 1];
6160 if (line->annotated)
6161 goto done;
6163 line->id = got_object_id_dup(id);
6164 if (line->id == NULL) {
6165 err = got_error_from_errno("got_object_id_dup");
6166 goto done;
6168 line->annotated = 1;
6169 done:
6170 errcode = pthread_mutex_unlock(&tog_mutex);
6171 if (errcode)
6172 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6173 return err;
6176 static void *
6177 blame_thread(void *arg)
6179 const struct got_error *err, *close_err;
6180 struct tog_blame_thread_args *ta = arg;
6181 struct tog_blame_cb_args *a = ta->cb_args;
6182 int errcode, fd1 = -1, fd2 = -1;
6183 FILE *f1 = NULL, *f2 = NULL;
6185 fd1 = got_opentempfd();
6186 if (fd1 == -1)
6187 return (void *)got_error_from_errno("got_opentempfd");
6189 fd2 = got_opentempfd();
6190 if (fd2 == -1) {
6191 err = got_error_from_errno("got_opentempfd");
6192 goto done;
6195 f1 = got_opentemp();
6196 if (f1 == NULL) {
6197 err = (void *)got_error_from_errno("got_opentemp");
6198 goto done;
6200 f2 = got_opentemp();
6201 if (f2 == NULL) {
6202 err = (void *)got_error_from_errno("got_opentemp");
6203 goto done;
6206 err = block_signals_used_by_main_thread();
6207 if (err)
6208 goto done;
6210 err = got_blame(ta->path, a->commit_id, ta->repo,
6211 tog_diff_algo, blame_cb, ta->cb_args,
6212 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6213 if (err && err->code == GOT_ERR_CANCELLED)
6214 err = NULL;
6216 errcode = pthread_mutex_lock(&tog_mutex);
6217 if (errcode) {
6218 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6219 goto done;
6222 close_err = got_repo_close(ta->repo);
6223 if (err == NULL)
6224 err = close_err;
6225 ta->repo = NULL;
6226 *ta->complete = 1;
6228 errcode = pthread_mutex_unlock(&tog_mutex);
6229 if (errcode && err == NULL)
6230 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6232 done:
6233 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6234 err = got_error_from_errno("close");
6235 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6236 err = got_error_from_errno("close");
6237 if (f1 && fclose(f1) == EOF && err == NULL)
6238 err = got_error_from_errno("fclose");
6239 if (f2 && fclose(f2) == EOF && err == NULL)
6240 err = got_error_from_errno("fclose");
6242 return (void *)err;
6245 static struct got_object_id *
6246 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6247 int first_displayed_line, int selected_line)
6249 struct tog_blame_line *line;
6251 if (nlines <= 0)
6252 return NULL;
6254 line = &lines[first_displayed_line - 1 + selected_line - 1];
6255 if (!line->annotated)
6256 return NULL;
6258 return line->id;
6261 static struct got_object_id *
6262 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6263 int lineno)
6265 struct tog_blame_line *line;
6267 if (nlines <= 0 || lineno >= nlines)
6268 return NULL;
6270 line = &lines[lineno - 1];
6271 if (!line->annotated)
6272 return NULL;
6274 return line->id;
6277 static const struct got_error *
6278 stop_blame(struct tog_blame *blame)
6280 const struct got_error *err = NULL;
6281 int i;
6283 if (blame->thread) {
6284 int errcode;
6285 errcode = pthread_mutex_unlock(&tog_mutex);
6286 if (errcode)
6287 return got_error_set_errno(errcode,
6288 "pthread_mutex_unlock");
6289 errcode = pthread_join(blame->thread, (void **)&err);
6290 if (errcode)
6291 return got_error_set_errno(errcode, "pthread_join");
6292 errcode = pthread_mutex_lock(&tog_mutex);
6293 if (errcode)
6294 return got_error_set_errno(errcode,
6295 "pthread_mutex_lock");
6296 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6297 err = NULL;
6298 blame->thread = NULL;
6300 if (blame->thread_args.repo) {
6301 const struct got_error *close_err;
6302 close_err = got_repo_close(blame->thread_args.repo);
6303 if (err == NULL)
6304 err = close_err;
6305 blame->thread_args.repo = NULL;
6307 if (blame->f) {
6308 if (fclose(blame->f) == EOF && err == NULL)
6309 err = got_error_from_errno("fclose");
6310 blame->f = NULL;
6312 if (blame->lines) {
6313 for (i = 0; i < blame->nlines; i++)
6314 free(blame->lines[i].id);
6315 free(blame->lines);
6316 blame->lines = NULL;
6318 free(blame->cb_args.commit_id);
6319 blame->cb_args.commit_id = NULL;
6320 if (blame->pack_fds) {
6321 const struct got_error *pack_err =
6322 got_repo_pack_fds_close(blame->pack_fds);
6323 if (err == NULL)
6324 err = pack_err;
6325 blame->pack_fds = NULL;
6327 return err;
6330 static const struct got_error *
6331 cancel_blame_view(void *arg)
6333 const struct got_error *err = NULL;
6334 int *done = arg;
6335 int errcode;
6337 errcode = pthread_mutex_lock(&tog_mutex);
6338 if (errcode)
6339 return got_error_set_errno(errcode,
6340 "pthread_mutex_unlock");
6342 if (*done)
6343 err = got_error(GOT_ERR_CANCELLED);
6345 errcode = pthread_mutex_unlock(&tog_mutex);
6346 if (errcode)
6347 return got_error_set_errno(errcode,
6348 "pthread_mutex_lock");
6350 return err;
6353 static const struct got_error *
6354 run_blame(struct tog_view *view)
6356 struct tog_blame_view_state *s = &view->state.blame;
6357 struct tog_blame *blame = &s->blame;
6358 const struct got_error *err = NULL;
6359 struct got_commit_object *commit = NULL;
6360 struct got_blob_object *blob = NULL;
6361 struct got_repository *thread_repo = NULL;
6362 struct got_object_id *obj_id = NULL;
6363 int obj_type, fd = -1;
6364 int *pack_fds = NULL;
6366 err = got_object_open_as_commit(&commit, s->repo,
6367 &s->blamed_commit->id);
6368 if (err)
6369 return err;
6371 fd = got_opentempfd();
6372 if (fd == -1) {
6373 err = got_error_from_errno("got_opentempfd");
6374 goto done;
6377 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6378 if (err)
6379 goto done;
6381 err = got_object_get_type(&obj_type, s->repo, obj_id);
6382 if (err)
6383 goto done;
6385 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6386 err = got_error(GOT_ERR_OBJ_TYPE);
6387 goto done;
6390 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6391 if (err)
6392 goto done;
6393 blame->f = got_opentemp();
6394 if (blame->f == NULL) {
6395 err = got_error_from_errno("got_opentemp");
6396 goto done;
6398 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6399 &blame->line_offsets, blame->f, blob);
6400 if (err)
6401 goto done;
6402 if (blame->nlines == 0) {
6403 s->blame_complete = 1;
6404 goto done;
6407 /* Don't include \n at EOF in the blame line count. */
6408 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6409 blame->nlines--;
6411 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6412 if (blame->lines == NULL) {
6413 err = got_error_from_errno("calloc");
6414 goto done;
6417 err = got_repo_pack_fds_open(&pack_fds);
6418 if (err)
6419 goto done;
6420 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6421 pack_fds);
6422 if (err)
6423 goto done;
6425 blame->pack_fds = pack_fds;
6426 blame->cb_args.view = view;
6427 blame->cb_args.lines = blame->lines;
6428 blame->cb_args.nlines = blame->nlines;
6429 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6430 if (blame->cb_args.commit_id == NULL) {
6431 err = got_error_from_errno("got_object_id_dup");
6432 goto done;
6434 blame->cb_args.quit = &s->done;
6436 blame->thread_args.path = s->path;
6437 blame->thread_args.repo = thread_repo;
6438 blame->thread_args.cb_args = &blame->cb_args;
6439 blame->thread_args.complete = &s->blame_complete;
6440 blame->thread_args.cancel_cb = cancel_blame_view;
6441 blame->thread_args.cancel_arg = &s->done;
6442 s->blame_complete = 0;
6444 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6445 s->first_displayed_line = 1;
6446 s->last_displayed_line = view->nlines;
6447 s->selected_line = 1;
6449 s->matched_line = 0;
6451 done:
6452 if (commit)
6453 got_object_commit_close(commit);
6454 if (fd != -1 && close(fd) == -1 && err == NULL)
6455 err = got_error_from_errno("close");
6456 if (blob)
6457 got_object_blob_close(blob);
6458 free(obj_id);
6459 if (err)
6460 stop_blame(blame);
6461 return err;
6464 static const struct got_error *
6465 open_blame_view(struct tog_view *view, char *path,
6466 struct got_object_id *commit_id, struct got_repository *repo)
6468 const struct got_error *err = NULL;
6469 struct tog_blame_view_state *s = &view->state.blame;
6471 STAILQ_INIT(&s->blamed_commits);
6473 s->path = strdup(path);
6474 if (s->path == NULL)
6475 return got_error_from_errno("strdup");
6477 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6478 if (err) {
6479 free(s->path);
6480 return err;
6483 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6484 s->first_displayed_line = 1;
6485 s->last_displayed_line = view->nlines;
6486 s->selected_line = 1;
6487 s->blame_complete = 0;
6488 s->repo = repo;
6489 s->commit_id = commit_id;
6490 memset(&s->blame, 0, sizeof(s->blame));
6492 STAILQ_INIT(&s->colors);
6493 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6494 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6495 get_color_value("TOG_COLOR_COMMIT"));
6496 if (err)
6497 return err;
6500 view->show = show_blame_view;
6501 view->input = input_blame_view;
6502 view->reset = reset_blame_view;
6503 view->close = close_blame_view;
6504 view->search_start = search_start_blame_view;
6505 view->search_setup = search_setup_blame_view;
6506 view->search_next = search_next_view_match;
6508 return run_blame(view);
6511 static const struct got_error *
6512 close_blame_view(struct tog_view *view)
6514 const struct got_error *err = NULL;
6515 struct tog_blame_view_state *s = &view->state.blame;
6517 if (s->blame.thread)
6518 err = stop_blame(&s->blame);
6520 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6521 struct got_object_qid *blamed_commit;
6522 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6523 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6524 got_object_qid_free(blamed_commit);
6527 free(s->path);
6528 free_colors(&s->colors);
6529 return err;
6532 static const struct got_error *
6533 search_start_blame_view(struct tog_view *view)
6535 struct tog_blame_view_state *s = &view->state.blame;
6537 s->matched_line = 0;
6538 return NULL;
6541 static void
6542 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6543 size_t *nlines, int **first, int **last, int **match, int **selected)
6545 struct tog_blame_view_state *s = &view->state.blame;
6547 *f = s->blame.f;
6548 *nlines = s->blame.nlines;
6549 *line_offsets = s->blame.line_offsets;
6550 *match = &s->matched_line;
6551 *first = &s->first_displayed_line;
6552 *last = &s->last_displayed_line;
6553 *selected = &s->selected_line;
6556 static const struct got_error *
6557 show_blame_view(struct tog_view *view)
6559 const struct got_error *err = NULL;
6560 struct tog_blame_view_state *s = &view->state.blame;
6561 int errcode;
6563 if (s->blame.thread == NULL && !s->blame_complete) {
6564 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6565 &s->blame.thread_args);
6566 if (errcode)
6567 return got_error_set_errno(errcode, "pthread_create");
6569 if (!using_mock_io)
6570 halfdelay(1); /* fast refresh while annotating */
6573 if (s->blame_complete && !using_mock_io)
6574 halfdelay(10); /* disable fast refresh */
6576 err = draw_blame(view);
6578 view_border(view);
6579 return err;
6582 static const struct got_error *
6583 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6584 struct got_repository *repo, struct got_object_id *id)
6586 struct tog_view *log_view;
6587 const struct got_error *err = NULL;
6589 *new_view = NULL;
6591 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6592 if (log_view == NULL)
6593 return got_error_from_errno("view_open");
6595 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6596 if (err)
6597 view_close(log_view);
6598 else
6599 *new_view = log_view;
6601 return err;
6604 static const struct got_error *
6605 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6607 const struct got_error *err = NULL, *thread_err = NULL;
6608 struct tog_view *diff_view;
6609 struct tog_blame_view_state *s = &view->state.blame;
6610 int eos, nscroll, begin_y = 0, begin_x = 0;
6612 eos = nscroll = view->nlines - 2;
6613 if (view_is_hsplit_top(view))
6614 --eos; /* border */
6616 switch (ch) {
6617 case '0':
6618 case '$':
6619 case KEY_RIGHT:
6620 case 'l':
6621 case KEY_LEFT:
6622 case 'h':
6623 horizontal_scroll_input(view, ch);
6624 break;
6625 case 'q':
6626 s->done = 1;
6627 break;
6628 case 'g':
6629 case KEY_HOME:
6630 s->selected_line = 1;
6631 s->first_displayed_line = 1;
6632 view->count = 0;
6633 break;
6634 case 'G':
6635 case KEY_END:
6636 if (s->blame.nlines < eos) {
6637 s->selected_line = s->blame.nlines;
6638 s->first_displayed_line = 1;
6639 } else {
6640 s->selected_line = eos;
6641 s->first_displayed_line = s->blame.nlines - (eos - 1);
6643 view->count = 0;
6644 break;
6645 case 'k':
6646 case KEY_UP:
6647 case CTRL('p'):
6648 if (s->selected_line > 1)
6649 s->selected_line--;
6650 else if (s->selected_line == 1 &&
6651 s->first_displayed_line > 1)
6652 s->first_displayed_line--;
6653 else
6654 view->count = 0;
6655 break;
6656 case CTRL('u'):
6657 case 'u':
6658 nscroll /= 2;
6659 /* FALL THROUGH */
6660 case KEY_PPAGE:
6661 case CTRL('b'):
6662 case 'b':
6663 if (s->first_displayed_line == 1) {
6664 if (view->count > 1)
6665 nscroll += nscroll;
6666 s->selected_line = MAX(1, s->selected_line - nscroll);
6667 view->count = 0;
6668 break;
6670 if (s->first_displayed_line > nscroll)
6671 s->first_displayed_line -= nscroll;
6672 else
6673 s->first_displayed_line = 1;
6674 break;
6675 case 'j':
6676 case KEY_DOWN:
6677 case CTRL('n'):
6678 if (s->selected_line < eos && s->first_displayed_line +
6679 s->selected_line <= s->blame.nlines)
6680 s->selected_line++;
6681 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6682 s->first_displayed_line++;
6683 else
6684 view->count = 0;
6685 break;
6686 case 'c':
6687 case 'p': {
6688 struct got_object_id *id = NULL;
6690 view->count = 0;
6691 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6692 s->first_displayed_line, s->selected_line);
6693 if (id == NULL)
6694 break;
6695 if (ch == 'p') {
6696 struct got_commit_object *commit, *pcommit;
6697 struct got_object_qid *pid;
6698 struct got_object_id *blob_id = NULL;
6699 int obj_type;
6700 err = got_object_open_as_commit(&commit,
6701 s->repo, id);
6702 if (err)
6703 break;
6704 pid = STAILQ_FIRST(
6705 got_object_commit_get_parent_ids(commit));
6706 if (pid == NULL) {
6707 got_object_commit_close(commit);
6708 break;
6710 /* Check if path history ends here. */
6711 err = got_object_open_as_commit(&pcommit,
6712 s->repo, &pid->id);
6713 if (err)
6714 break;
6715 err = got_object_id_by_path(&blob_id, s->repo,
6716 pcommit, s->path);
6717 got_object_commit_close(pcommit);
6718 if (err) {
6719 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6720 err = NULL;
6721 got_object_commit_close(commit);
6722 break;
6724 err = got_object_get_type(&obj_type, s->repo,
6725 blob_id);
6726 free(blob_id);
6727 /* Can't blame non-blob type objects. */
6728 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6729 got_object_commit_close(commit);
6730 break;
6732 err = got_object_qid_alloc(&s->blamed_commit,
6733 &pid->id);
6734 got_object_commit_close(commit);
6735 } else {
6736 if (got_object_id_cmp(id,
6737 &s->blamed_commit->id) == 0)
6738 break;
6739 err = got_object_qid_alloc(&s->blamed_commit,
6740 id);
6742 if (err)
6743 break;
6744 s->done = 1;
6745 thread_err = stop_blame(&s->blame);
6746 s->done = 0;
6747 if (thread_err)
6748 break;
6749 STAILQ_INSERT_HEAD(&s->blamed_commits,
6750 s->blamed_commit, entry);
6751 err = run_blame(view);
6752 if (err)
6753 break;
6754 break;
6756 case 'C': {
6757 struct got_object_qid *first;
6759 view->count = 0;
6760 first = STAILQ_FIRST(&s->blamed_commits);
6761 if (!got_object_id_cmp(&first->id, s->commit_id))
6762 break;
6763 s->done = 1;
6764 thread_err = stop_blame(&s->blame);
6765 s->done = 0;
6766 if (thread_err)
6767 break;
6768 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6769 got_object_qid_free(s->blamed_commit);
6770 s->blamed_commit =
6771 STAILQ_FIRST(&s->blamed_commits);
6772 err = run_blame(view);
6773 if (err)
6774 break;
6775 break;
6777 case 'L':
6778 view->count = 0;
6779 s->id_to_log = get_selected_commit_id(s->blame.lines,
6780 s->blame.nlines, s->first_displayed_line, s->selected_line);
6781 if (s->id_to_log)
6782 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6783 break;
6784 case KEY_ENTER:
6785 case '\r': {
6786 struct got_object_id *id = NULL;
6787 struct got_object_qid *pid;
6788 struct got_commit_object *commit = NULL;
6790 view->count = 0;
6791 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6792 s->first_displayed_line, s->selected_line);
6793 if (id == NULL)
6794 break;
6795 err = got_object_open_as_commit(&commit, s->repo, id);
6796 if (err)
6797 break;
6798 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6799 if (*new_view) {
6800 /* traversed from diff view, release diff resources */
6801 err = close_diff_view(*new_view);
6802 if (err)
6803 break;
6804 diff_view = *new_view;
6805 } else {
6806 if (view_is_parent_view(view))
6807 view_get_split(view, &begin_y, &begin_x);
6809 diff_view = view_open(0, 0, begin_y, begin_x,
6810 TOG_VIEW_DIFF);
6811 if (diff_view == NULL) {
6812 got_object_commit_close(commit);
6813 err = got_error_from_errno("view_open");
6814 break;
6817 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6818 id, NULL, NULL, 3, 0, 0, view, s->repo);
6819 got_object_commit_close(commit);
6820 if (err) {
6821 view_close(diff_view);
6822 break;
6824 s->last_diffed_line = s->first_displayed_line - 1 +
6825 s->selected_line;
6826 if (*new_view)
6827 break; /* still open from active diff view */
6828 if (view_is_parent_view(view) &&
6829 view->mode == TOG_VIEW_SPLIT_HRZN) {
6830 err = view_init_hsplit(view, begin_y);
6831 if (err)
6832 break;
6835 view->focussed = 0;
6836 diff_view->focussed = 1;
6837 diff_view->mode = view->mode;
6838 diff_view->nlines = view->lines - begin_y;
6839 if (view_is_parent_view(view)) {
6840 view_transfer_size(diff_view, view);
6841 err = view_close_child(view);
6842 if (err)
6843 break;
6844 err = view_set_child(view, diff_view);
6845 if (err)
6846 break;
6847 view->focus_child = 1;
6848 } else
6849 *new_view = diff_view;
6850 if (err)
6851 break;
6852 break;
6854 case CTRL('d'):
6855 case 'd':
6856 nscroll /= 2;
6857 /* FALL THROUGH */
6858 case KEY_NPAGE:
6859 case CTRL('f'):
6860 case 'f':
6861 case ' ':
6862 if (s->last_displayed_line >= s->blame.nlines &&
6863 s->selected_line >= MIN(s->blame.nlines,
6864 view->nlines - 2)) {
6865 view->count = 0;
6866 break;
6868 if (s->last_displayed_line >= s->blame.nlines &&
6869 s->selected_line < view->nlines - 2) {
6870 s->selected_line +=
6871 MIN(nscroll, s->last_displayed_line -
6872 s->first_displayed_line - s->selected_line + 1);
6874 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6875 s->first_displayed_line += nscroll;
6876 else
6877 s->first_displayed_line =
6878 s->blame.nlines - (view->nlines - 3);
6879 break;
6880 case KEY_RESIZE:
6881 if (s->selected_line > view->nlines - 2) {
6882 s->selected_line = MIN(s->blame.nlines,
6883 view->nlines - 2);
6885 break;
6886 default:
6887 view->count = 0;
6888 break;
6890 return thread_err ? thread_err : err;
6893 static const struct got_error *
6894 reset_blame_view(struct tog_view *view)
6896 const struct got_error *err;
6897 struct tog_blame_view_state *s = &view->state.blame;
6899 view->count = 0;
6900 s->done = 1;
6901 err = stop_blame(&s->blame);
6902 s->done = 0;
6903 if (err)
6904 return err;
6905 return run_blame(view);
6908 static const struct got_error *
6909 cmd_blame(int argc, char *argv[])
6911 const struct got_error *error;
6912 struct got_repository *repo = NULL;
6913 struct got_worktree *worktree = NULL;
6914 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6915 char *link_target = NULL;
6916 struct got_object_id *commit_id = NULL;
6917 struct got_commit_object *commit = NULL;
6918 char *commit_id_str = NULL;
6919 int ch;
6920 struct tog_view *view = NULL;
6921 int *pack_fds = NULL;
6923 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6924 switch (ch) {
6925 case 'c':
6926 commit_id_str = optarg;
6927 break;
6928 case 'r':
6929 repo_path = realpath(optarg, NULL);
6930 if (repo_path == NULL)
6931 return got_error_from_errno2("realpath",
6932 optarg);
6933 break;
6934 default:
6935 usage_blame();
6936 /* NOTREACHED */
6940 argc -= optind;
6941 argv += optind;
6943 if (argc != 1)
6944 usage_blame();
6946 error = got_repo_pack_fds_open(&pack_fds);
6947 if (error != NULL)
6948 goto done;
6950 if (repo_path == NULL) {
6951 cwd = getcwd(NULL, 0);
6952 if (cwd == NULL)
6953 return got_error_from_errno("getcwd");
6954 error = got_worktree_open(&worktree, cwd);
6955 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6956 goto done;
6957 if (worktree)
6958 repo_path =
6959 strdup(got_worktree_get_repo_path(worktree));
6960 else
6961 repo_path = strdup(cwd);
6962 if (repo_path == NULL) {
6963 error = got_error_from_errno("strdup");
6964 goto done;
6968 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6969 if (error != NULL)
6970 goto done;
6972 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6973 worktree);
6974 if (error)
6975 goto done;
6977 init_curses();
6979 error = apply_unveil(got_repo_get_path(repo), NULL);
6980 if (error)
6981 goto done;
6983 error = tog_load_refs(repo, 0);
6984 if (error)
6985 goto done;
6987 if (commit_id_str == NULL) {
6988 struct got_reference *head_ref;
6989 error = got_ref_open(&head_ref, repo, worktree ?
6990 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6991 if (error != NULL)
6992 goto done;
6993 error = got_ref_resolve(&commit_id, repo, head_ref);
6994 got_ref_close(head_ref);
6995 } else {
6996 error = got_repo_match_object_id(&commit_id, NULL,
6997 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6999 if (error != NULL)
7000 goto done;
7002 error = got_object_open_as_commit(&commit, repo, commit_id);
7003 if (error)
7004 goto done;
7006 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7007 commit, repo);
7008 if (error)
7009 goto done;
7011 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7012 if (view == NULL) {
7013 error = got_error_from_errno("view_open");
7014 goto done;
7016 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7017 commit_id, repo);
7018 if (error != NULL) {
7019 if (view->close == NULL)
7020 close_blame_view(view);
7021 view_close(view);
7022 goto done;
7024 if (worktree) {
7025 /* Release work tree lock. */
7026 got_worktree_close(worktree);
7027 worktree = NULL;
7029 error = view_loop(view);
7030 done:
7031 free(repo_path);
7032 free(in_repo_path);
7033 free(link_target);
7034 free(cwd);
7035 free(commit_id);
7036 if (commit)
7037 got_object_commit_close(commit);
7038 if (worktree)
7039 got_worktree_close(worktree);
7040 if (repo) {
7041 const struct got_error *close_err = got_repo_close(repo);
7042 if (error == NULL)
7043 error = close_err;
7045 if (pack_fds) {
7046 const struct got_error *pack_err =
7047 got_repo_pack_fds_close(pack_fds);
7048 if (error == NULL)
7049 error = pack_err;
7051 tog_free_refs();
7052 return error;
7055 static const struct got_error *
7056 draw_tree_entries(struct tog_view *view, const char *parent_path)
7058 struct tog_tree_view_state *s = &view->state.tree;
7059 const struct got_error *err = NULL;
7060 struct got_tree_entry *te;
7061 wchar_t *wline;
7062 char *index = NULL;
7063 struct tog_color *tc;
7064 int width, n, nentries, scrollx, i = 1;
7065 int limit = view->nlines;
7067 s->ndisplayed = 0;
7068 if (view_is_hsplit_top(view))
7069 --limit; /* border */
7071 werase(view->window);
7073 if (limit == 0)
7074 return NULL;
7076 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7077 0, 0);
7078 if (err)
7079 return err;
7080 if (view_needs_focus_indication(view))
7081 wstandout(view->window);
7082 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7083 if (tc)
7084 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7085 waddwstr(view->window, wline);
7086 free(wline);
7087 wline = NULL;
7088 while (width++ < view->ncols)
7089 waddch(view->window, ' ');
7090 if (tc)
7091 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7092 if (view_needs_focus_indication(view))
7093 wstandend(view->window);
7094 if (--limit <= 0)
7095 return NULL;
7097 i += s->selected;
7098 if (s->first_displayed_entry) {
7099 i += got_tree_entry_get_index(s->first_displayed_entry);
7100 if (s->tree != s->root)
7101 ++i; /* account for ".." entry */
7103 nentries = got_object_tree_get_nentries(s->tree);
7104 if (asprintf(&index, "[%d/%d] %s",
7105 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7106 return got_error_from_errno("asprintf");
7107 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7108 free(index);
7109 if (err)
7110 return err;
7111 waddwstr(view->window, wline);
7112 free(wline);
7113 wline = NULL;
7114 if (width < view->ncols - 1)
7115 waddch(view->window, '\n');
7116 if (--limit <= 0)
7117 return NULL;
7118 waddch(view->window, '\n');
7119 if (--limit <= 0)
7120 return NULL;
7122 if (s->first_displayed_entry == NULL) {
7123 te = got_object_tree_get_first_entry(s->tree);
7124 if (s->selected == 0) {
7125 if (view->focussed)
7126 wstandout(view->window);
7127 s->selected_entry = NULL;
7129 waddstr(view->window, " ..\n"); /* parent directory */
7130 if (s->selected == 0 && view->focussed)
7131 wstandend(view->window);
7132 s->ndisplayed++;
7133 if (--limit <= 0)
7134 return NULL;
7135 n = 1;
7136 } else {
7137 n = 0;
7138 te = s->first_displayed_entry;
7141 view->maxx = 0;
7142 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7143 char *line = NULL, *id_str = NULL, *link_target = NULL;
7144 const char *modestr = "";
7145 mode_t mode;
7147 te = got_object_tree_get_entry(s->tree, i);
7148 mode = got_tree_entry_get_mode(te);
7150 if (s->show_ids) {
7151 err = got_object_id_str(&id_str,
7152 got_tree_entry_get_id(te));
7153 if (err)
7154 return got_error_from_errno(
7155 "got_object_id_str");
7157 if (got_object_tree_entry_is_submodule(te))
7158 modestr = "$";
7159 else if (S_ISLNK(mode)) {
7160 int i;
7162 err = got_tree_entry_get_symlink_target(&link_target,
7163 te, s->repo);
7164 if (err) {
7165 free(id_str);
7166 return err;
7168 for (i = 0; i < strlen(link_target); i++) {
7169 if (!isprint((unsigned char)link_target[i]))
7170 link_target[i] = '?';
7172 modestr = "@";
7174 else if (S_ISDIR(mode))
7175 modestr = "/";
7176 else if (mode & S_IXUSR)
7177 modestr = "*";
7178 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7179 got_tree_entry_get_name(te), modestr,
7180 link_target ? " -> ": "",
7181 link_target ? link_target : "") == -1) {
7182 free(id_str);
7183 free(link_target);
7184 return got_error_from_errno("asprintf");
7186 free(id_str);
7187 free(link_target);
7189 /* use full line width to determine view->maxx */
7190 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7191 if (err) {
7192 free(line);
7193 break;
7195 view->maxx = MAX(view->maxx, width);
7196 free(wline);
7197 wline = NULL;
7199 err = format_line(&wline, &width, &scrollx, line, view->x,
7200 view->ncols, 0, 0);
7201 if (err) {
7202 free(line);
7203 break;
7205 if (n == s->selected) {
7206 if (view->focussed)
7207 wstandout(view->window);
7208 s->selected_entry = te;
7210 tc = match_color(&s->colors, line);
7211 if (tc)
7212 wattr_on(view->window,
7213 COLOR_PAIR(tc->colorpair), NULL);
7214 waddwstr(view->window, &wline[scrollx]);
7215 if (tc)
7216 wattr_off(view->window,
7217 COLOR_PAIR(tc->colorpair), NULL);
7218 if (width < view->ncols)
7219 waddch(view->window, '\n');
7220 if (n == s->selected && view->focussed)
7221 wstandend(view->window);
7222 free(line);
7223 free(wline);
7224 wline = NULL;
7225 n++;
7226 s->ndisplayed++;
7227 s->last_displayed_entry = te;
7228 if (--limit <= 0)
7229 break;
7232 return err;
7235 static void
7236 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7238 struct got_tree_entry *te;
7239 int isroot = s->tree == s->root;
7240 int i = 0;
7242 if (s->first_displayed_entry == NULL)
7243 return;
7245 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7246 while (i++ < maxscroll) {
7247 if (te == NULL) {
7248 if (!isroot)
7249 s->first_displayed_entry = NULL;
7250 break;
7252 s->first_displayed_entry = te;
7253 te = got_tree_entry_get_prev(s->tree, te);
7257 static const struct got_error *
7258 tree_scroll_down(struct tog_view *view, int maxscroll)
7260 struct tog_tree_view_state *s = &view->state.tree;
7261 struct got_tree_entry *next, *last;
7262 int n = 0;
7264 if (s->first_displayed_entry)
7265 next = got_tree_entry_get_next(s->tree,
7266 s->first_displayed_entry);
7267 else
7268 next = got_object_tree_get_first_entry(s->tree);
7270 last = s->last_displayed_entry;
7271 while (next && n++ < maxscroll) {
7272 if (last) {
7273 s->last_displayed_entry = last;
7274 last = got_tree_entry_get_next(s->tree, last);
7276 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7277 s->first_displayed_entry = next;
7278 next = got_tree_entry_get_next(s->tree, next);
7282 return NULL;
7285 static const struct got_error *
7286 tree_entry_path(char **path, struct tog_parent_trees *parents,
7287 struct got_tree_entry *te)
7289 const struct got_error *err = NULL;
7290 struct tog_parent_tree *pt;
7291 size_t len = 2; /* for leading slash and NUL */
7293 TAILQ_FOREACH(pt, parents, entry)
7294 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7295 + 1 /* slash */;
7296 if (te)
7297 len += strlen(got_tree_entry_get_name(te));
7299 *path = calloc(1, len);
7300 if (path == NULL)
7301 return got_error_from_errno("calloc");
7303 (*path)[0] = '/';
7304 pt = TAILQ_LAST(parents, tog_parent_trees);
7305 while (pt) {
7306 const char *name = got_tree_entry_get_name(pt->selected_entry);
7307 if (strlcat(*path, name, len) >= len) {
7308 err = got_error(GOT_ERR_NO_SPACE);
7309 goto done;
7311 if (strlcat(*path, "/", len) >= len) {
7312 err = got_error(GOT_ERR_NO_SPACE);
7313 goto done;
7315 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7317 if (te) {
7318 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7319 err = got_error(GOT_ERR_NO_SPACE);
7320 goto done;
7323 done:
7324 if (err) {
7325 free(*path);
7326 *path = NULL;
7328 return err;
7331 static const struct got_error *
7332 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7333 struct got_tree_entry *te, struct tog_parent_trees *parents,
7334 struct got_object_id *commit_id, struct got_repository *repo)
7336 const struct got_error *err = NULL;
7337 char *path;
7338 struct tog_view *blame_view;
7340 *new_view = NULL;
7342 err = tree_entry_path(&path, parents, te);
7343 if (err)
7344 return err;
7346 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7347 if (blame_view == NULL) {
7348 err = got_error_from_errno("view_open");
7349 goto done;
7352 err = open_blame_view(blame_view, path, commit_id, repo);
7353 if (err) {
7354 if (err->code == GOT_ERR_CANCELLED)
7355 err = NULL;
7356 view_close(blame_view);
7357 } else
7358 *new_view = blame_view;
7359 done:
7360 free(path);
7361 return err;
7364 static const struct got_error *
7365 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7366 struct tog_tree_view_state *s)
7368 struct tog_view *log_view;
7369 const struct got_error *err = NULL;
7370 char *path;
7372 *new_view = NULL;
7374 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7375 if (log_view == NULL)
7376 return got_error_from_errno("view_open");
7378 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7379 if (err)
7380 return err;
7382 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7383 path, 0);
7384 if (err)
7385 view_close(log_view);
7386 else
7387 *new_view = log_view;
7388 free(path);
7389 return err;
7392 static const struct got_error *
7393 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7394 const char *head_ref_name, struct got_repository *repo)
7396 const struct got_error *err = NULL;
7397 char *commit_id_str = NULL;
7398 struct tog_tree_view_state *s = &view->state.tree;
7399 struct got_commit_object *commit = NULL;
7401 TAILQ_INIT(&s->parents);
7402 STAILQ_INIT(&s->colors);
7404 s->commit_id = got_object_id_dup(commit_id);
7405 if (s->commit_id == NULL) {
7406 err = got_error_from_errno("got_object_id_dup");
7407 goto done;
7410 err = got_object_open_as_commit(&commit, repo, commit_id);
7411 if (err)
7412 goto done;
7415 * The root is opened here and will be closed when the view is closed.
7416 * Any visited subtrees and their path-wise parents are opened and
7417 * closed on demand.
7419 err = got_object_open_as_tree(&s->root, repo,
7420 got_object_commit_get_tree_id(commit));
7421 if (err)
7422 goto done;
7423 s->tree = s->root;
7425 err = got_object_id_str(&commit_id_str, commit_id);
7426 if (err != NULL)
7427 goto done;
7429 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7430 err = got_error_from_errno("asprintf");
7431 goto done;
7434 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7435 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7436 if (head_ref_name) {
7437 s->head_ref_name = strdup(head_ref_name);
7438 if (s->head_ref_name == NULL) {
7439 err = got_error_from_errno("strdup");
7440 goto done;
7443 s->repo = repo;
7445 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7446 err = add_color(&s->colors, "\\$$",
7447 TOG_COLOR_TREE_SUBMODULE,
7448 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7449 if (err)
7450 goto done;
7451 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7452 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7453 if (err)
7454 goto done;
7455 err = add_color(&s->colors, "/$",
7456 TOG_COLOR_TREE_DIRECTORY,
7457 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7458 if (err)
7459 goto done;
7461 err = add_color(&s->colors, "\\*$",
7462 TOG_COLOR_TREE_EXECUTABLE,
7463 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7464 if (err)
7465 goto done;
7467 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7468 get_color_value("TOG_COLOR_COMMIT"));
7469 if (err)
7470 goto done;
7473 view->show = show_tree_view;
7474 view->input = input_tree_view;
7475 view->close = close_tree_view;
7476 view->search_start = search_start_tree_view;
7477 view->search_next = search_next_tree_view;
7478 done:
7479 free(commit_id_str);
7480 if (commit)
7481 got_object_commit_close(commit);
7482 if (err) {
7483 if (view->close == NULL)
7484 close_tree_view(view);
7485 view_close(view);
7487 return err;
7490 static const struct got_error *
7491 close_tree_view(struct tog_view *view)
7493 struct tog_tree_view_state *s = &view->state.tree;
7495 free_colors(&s->colors);
7496 free(s->tree_label);
7497 s->tree_label = NULL;
7498 free(s->commit_id);
7499 s->commit_id = NULL;
7500 free(s->head_ref_name);
7501 s->head_ref_name = NULL;
7502 while (!TAILQ_EMPTY(&s->parents)) {
7503 struct tog_parent_tree *parent;
7504 parent = TAILQ_FIRST(&s->parents);
7505 TAILQ_REMOVE(&s->parents, parent, entry);
7506 if (parent->tree != s->root)
7507 got_object_tree_close(parent->tree);
7508 free(parent);
7511 if (s->tree != NULL && s->tree != s->root)
7512 got_object_tree_close(s->tree);
7513 if (s->root)
7514 got_object_tree_close(s->root);
7515 return NULL;
7518 static const struct got_error *
7519 search_start_tree_view(struct tog_view *view)
7521 struct tog_tree_view_state *s = &view->state.tree;
7523 s->matched_entry = NULL;
7524 return NULL;
7527 static int
7528 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7530 regmatch_t regmatch;
7532 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7533 0) == 0;
7536 static const struct got_error *
7537 search_next_tree_view(struct tog_view *view)
7539 struct tog_tree_view_state *s = &view->state.tree;
7540 struct got_tree_entry *te = NULL;
7542 if (!view->searching) {
7543 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7544 return NULL;
7547 if (s->matched_entry) {
7548 if (view->searching == TOG_SEARCH_FORWARD) {
7549 if (s->selected_entry)
7550 te = got_tree_entry_get_next(s->tree,
7551 s->selected_entry);
7552 else
7553 te = got_object_tree_get_first_entry(s->tree);
7554 } else {
7555 if (s->selected_entry == NULL)
7556 te = got_object_tree_get_last_entry(s->tree);
7557 else
7558 te = got_tree_entry_get_prev(s->tree,
7559 s->selected_entry);
7561 } else {
7562 if (s->selected_entry)
7563 te = s->selected_entry;
7564 else if (view->searching == TOG_SEARCH_FORWARD)
7565 te = got_object_tree_get_first_entry(s->tree);
7566 else
7567 te = got_object_tree_get_last_entry(s->tree);
7570 while (1) {
7571 if (te == NULL) {
7572 if (s->matched_entry == NULL) {
7573 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7574 return NULL;
7576 if (view->searching == TOG_SEARCH_FORWARD)
7577 te = got_object_tree_get_first_entry(s->tree);
7578 else
7579 te = got_object_tree_get_last_entry(s->tree);
7582 if (match_tree_entry(te, &view->regex)) {
7583 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7584 s->matched_entry = te;
7585 break;
7588 if (view->searching == TOG_SEARCH_FORWARD)
7589 te = got_tree_entry_get_next(s->tree, te);
7590 else
7591 te = got_tree_entry_get_prev(s->tree, te);
7594 if (s->matched_entry) {
7595 s->first_displayed_entry = s->matched_entry;
7596 s->selected = 0;
7599 return NULL;
7602 static const struct got_error *
7603 show_tree_view(struct tog_view *view)
7605 const struct got_error *err = NULL;
7606 struct tog_tree_view_state *s = &view->state.tree;
7607 char *parent_path;
7609 err = tree_entry_path(&parent_path, &s->parents, NULL);
7610 if (err)
7611 return err;
7613 err = draw_tree_entries(view, parent_path);
7614 free(parent_path);
7616 view_border(view);
7617 return err;
7620 static const struct got_error *
7621 tree_goto_line(struct tog_view *view, int nlines)
7623 const struct got_error *err = NULL;
7624 struct tog_tree_view_state *s = &view->state.tree;
7625 struct got_tree_entry **fte, **lte, **ste;
7626 int g, last, first = 1, i = 1;
7627 int root = s->tree == s->root;
7628 int off = root ? 1 : 2;
7630 g = view->gline;
7631 view->gline = 0;
7633 if (g == 0)
7634 g = 1;
7635 else if (g > got_object_tree_get_nentries(s->tree))
7636 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7638 fte = &s->first_displayed_entry;
7639 lte = &s->last_displayed_entry;
7640 ste = &s->selected_entry;
7642 if (*fte != NULL) {
7643 first = got_tree_entry_get_index(*fte);
7644 first += off; /* account for ".." */
7646 last = got_tree_entry_get_index(*lte);
7647 last += off;
7649 if (g >= first && g <= last && g - first < nlines) {
7650 s->selected = g - first;
7651 return NULL; /* gline is on the current page */
7654 if (*ste != NULL) {
7655 i = got_tree_entry_get_index(*ste);
7656 i += off;
7659 if (i < g) {
7660 err = tree_scroll_down(view, g - i);
7661 if (err)
7662 return err;
7663 if (got_tree_entry_get_index(*lte) >=
7664 got_object_tree_get_nentries(s->tree) - 1 &&
7665 first + s->selected < g &&
7666 s->selected < s->ndisplayed - 1) {
7667 first = got_tree_entry_get_index(*fte);
7668 first += off;
7669 s->selected = g - first;
7671 } else if (i > g)
7672 tree_scroll_up(s, i - g);
7674 if (g < nlines &&
7675 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7676 s->selected = g - 1;
7678 return NULL;
7681 static const struct got_error *
7682 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7684 const struct got_error *err = NULL;
7685 struct tog_tree_view_state *s = &view->state.tree;
7686 struct got_tree_entry *te;
7687 int n, nscroll = view->nlines - 3;
7689 if (view->gline)
7690 return tree_goto_line(view, nscroll);
7692 switch (ch) {
7693 case '0':
7694 case '$':
7695 case KEY_RIGHT:
7696 case 'l':
7697 case KEY_LEFT:
7698 case 'h':
7699 horizontal_scroll_input(view, ch);
7700 break;
7701 case 'i':
7702 s->show_ids = !s->show_ids;
7703 view->count = 0;
7704 break;
7705 case 'L':
7706 view->count = 0;
7707 if (!s->selected_entry)
7708 break;
7709 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7710 break;
7711 case 'R':
7712 view->count = 0;
7713 err = view_request_new(new_view, view, TOG_VIEW_REF);
7714 break;
7715 case 'g':
7716 case '=':
7717 case KEY_HOME:
7718 s->selected = 0;
7719 view->count = 0;
7720 if (s->tree == s->root)
7721 s->first_displayed_entry =
7722 got_object_tree_get_first_entry(s->tree);
7723 else
7724 s->first_displayed_entry = NULL;
7725 break;
7726 case 'G':
7727 case '*':
7728 case KEY_END: {
7729 int eos = view->nlines - 3;
7731 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7732 --eos; /* border */
7733 s->selected = 0;
7734 view->count = 0;
7735 te = got_object_tree_get_last_entry(s->tree);
7736 for (n = 0; n < eos; n++) {
7737 if (te == NULL) {
7738 if (s->tree != s->root) {
7739 s->first_displayed_entry = NULL;
7740 n++;
7742 break;
7744 s->first_displayed_entry = te;
7745 te = got_tree_entry_get_prev(s->tree, te);
7747 if (n > 0)
7748 s->selected = n - 1;
7749 break;
7751 case 'k':
7752 case KEY_UP:
7753 case CTRL('p'):
7754 if (s->selected > 0) {
7755 s->selected--;
7756 break;
7758 tree_scroll_up(s, 1);
7759 if (s->selected_entry == NULL ||
7760 (s->tree == s->root && s->selected_entry ==
7761 got_object_tree_get_first_entry(s->tree)))
7762 view->count = 0;
7763 break;
7764 case CTRL('u'):
7765 case 'u':
7766 nscroll /= 2;
7767 /* FALL THROUGH */
7768 case KEY_PPAGE:
7769 case CTRL('b'):
7770 case 'b':
7771 if (s->tree == s->root) {
7772 if (got_object_tree_get_first_entry(s->tree) ==
7773 s->first_displayed_entry)
7774 s->selected -= MIN(s->selected, nscroll);
7775 } else {
7776 if (s->first_displayed_entry == NULL)
7777 s->selected -= MIN(s->selected, nscroll);
7779 tree_scroll_up(s, MAX(0, nscroll));
7780 if (s->selected_entry == NULL ||
7781 (s->tree == s->root && s->selected_entry ==
7782 got_object_tree_get_first_entry(s->tree)))
7783 view->count = 0;
7784 break;
7785 case 'j':
7786 case KEY_DOWN:
7787 case CTRL('n'):
7788 if (s->selected < s->ndisplayed - 1) {
7789 s->selected++;
7790 break;
7792 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7793 == NULL) {
7794 /* can't scroll any further */
7795 view->count = 0;
7796 break;
7798 tree_scroll_down(view, 1);
7799 break;
7800 case CTRL('d'):
7801 case 'd':
7802 nscroll /= 2;
7803 /* FALL THROUGH */
7804 case KEY_NPAGE:
7805 case CTRL('f'):
7806 case 'f':
7807 case ' ':
7808 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7809 == NULL) {
7810 /* can't scroll any further; move cursor down */
7811 if (s->selected < s->ndisplayed - 1)
7812 s->selected += MIN(nscroll,
7813 s->ndisplayed - s->selected - 1);
7814 else
7815 view->count = 0;
7816 break;
7818 tree_scroll_down(view, nscroll);
7819 break;
7820 case KEY_ENTER:
7821 case '\r':
7822 case KEY_BACKSPACE:
7823 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7824 struct tog_parent_tree *parent;
7825 /* user selected '..' */
7826 if (s->tree == s->root) {
7827 view->count = 0;
7828 break;
7830 parent = TAILQ_FIRST(&s->parents);
7831 TAILQ_REMOVE(&s->parents, parent,
7832 entry);
7833 got_object_tree_close(s->tree);
7834 s->tree = parent->tree;
7835 s->first_displayed_entry =
7836 parent->first_displayed_entry;
7837 s->selected_entry =
7838 parent->selected_entry;
7839 s->selected = parent->selected;
7840 if (s->selected > view->nlines - 3) {
7841 err = offset_selection_down(view);
7842 if (err)
7843 break;
7845 free(parent);
7846 } else if (S_ISDIR(got_tree_entry_get_mode(
7847 s->selected_entry))) {
7848 struct got_tree_object *subtree;
7849 view->count = 0;
7850 err = got_object_open_as_tree(&subtree, s->repo,
7851 got_tree_entry_get_id(s->selected_entry));
7852 if (err)
7853 break;
7854 err = tree_view_visit_subtree(s, subtree);
7855 if (err) {
7856 got_object_tree_close(subtree);
7857 break;
7859 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7860 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7861 break;
7862 case KEY_RESIZE:
7863 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7864 s->selected = view->nlines - 4;
7865 view->count = 0;
7866 break;
7867 default:
7868 view->count = 0;
7869 break;
7872 return err;
7875 __dead static void
7876 usage_tree(void)
7878 endwin();
7879 fprintf(stderr,
7880 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7881 getprogname());
7882 exit(1);
7885 static const struct got_error *
7886 cmd_tree(int argc, char *argv[])
7888 const struct got_error *error;
7889 struct got_repository *repo = NULL;
7890 struct got_worktree *worktree = NULL;
7891 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7892 struct got_object_id *commit_id = NULL;
7893 struct got_commit_object *commit = NULL;
7894 const char *commit_id_arg = NULL;
7895 char *label = NULL;
7896 struct got_reference *ref = NULL;
7897 const char *head_ref_name = NULL;
7898 int ch;
7899 struct tog_view *view;
7900 int *pack_fds = NULL;
7902 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7903 switch (ch) {
7904 case 'c':
7905 commit_id_arg = optarg;
7906 break;
7907 case 'r':
7908 repo_path = realpath(optarg, NULL);
7909 if (repo_path == NULL)
7910 return got_error_from_errno2("realpath",
7911 optarg);
7912 break;
7913 default:
7914 usage_tree();
7915 /* NOTREACHED */
7919 argc -= optind;
7920 argv += optind;
7922 if (argc > 1)
7923 usage_tree();
7925 error = got_repo_pack_fds_open(&pack_fds);
7926 if (error != NULL)
7927 goto done;
7929 if (repo_path == NULL) {
7930 cwd = getcwd(NULL, 0);
7931 if (cwd == NULL)
7932 return got_error_from_errno("getcwd");
7933 error = got_worktree_open(&worktree, cwd);
7934 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7935 goto done;
7936 if (worktree)
7937 repo_path =
7938 strdup(got_worktree_get_repo_path(worktree));
7939 else
7940 repo_path = strdup(cwd);
7941 if (repo_path == NULL) {
7942 error = got_error_from_errno("strdup");
7943 goto done;
7947 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7948 if (error != NULL)
7949 goto done;
7951 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7952 repo, worktree);
7953 if (error)
7954 goto done;
7956 init_curses();
7958 error = apply_unveil(got_repo_get_path(repo), NULL);
7959 if (error)
7960 goto done;
7962 error = tog_load_refs(repo, 0);
7963 if (error)
7964 goto done;
7966 if (commit_id_arg == NULL) {
7967 error = got_repo_match_object_id(&commit_id, &label,
7968 worktree ? got_worktree_get_head_ref_name(worktree) :
7969 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7970 if (error)
7971 goto done;
7972 head_ref_name = label;
7973 } else {
7974 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7975 if (error == NULL)
7976 head_ref_name = got_ref_get_name(ref);
7977 else if (error->code != GOT_ERR_NOT_REF)
7978 goto done;
7979 error = got_repo_match_object_id(&commit_id, NULL,
7980 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7981 if (error)
7982 goto done;
7985 error = got_object_open_as_commit(&commit, repo, commit_id);
7986 if (error)
7987 goto done;
7989 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7990 if (view == NULL) {
7991 error = got_error_from_errno("view_open");
7992 goto done;
7994 error = open_tree_view(view, commit_id, head_ref_name, repo);
7995 if (error)
7996 goto done;
7997 if (!got_path_is_root_dir(in_repo_path)) {
7998 error = tree_view_walk_path(&view->state.tree, commit,
7999 in_repo_path);
8000 if (error)
8001 goto done;
8004 if (worktree) {
8005 /* Release work tree lock. */
8006 got_worktree_close(worktree);
8007 worktree = NULL;
8009 error = view_loop(view);
8010 done:
8011 free(repo_path);
8012 free(cwd);
8013 free(commit_id);
8014 free(label);
8015 if (ref)
8016 got_ref_close(ref);
8017 if (repo) {
8018 const struct got_error *close_err = got_repo_close(repo);
8019 if (error == NULL)
8020 error = close_err;
8022 if (pack_fds) {
8023 const struct got_error *pack_err =
8024 got_repo_pack_fds_close(pack_fds);
8025 if (error == NULL)
8026 error = pack_err;
8028 tog_free_refs();
8029 return error;
8032 static const struct got_error *
8033 ref_view_load_refs(struct tog_ref_view_state *s)
8035 struct got_reflist_entry *sre;
8036 struct tog_reflist_entry *re;
8038 s->nrefs = 0;
8039 TAILQ_FOREACH(sre, &tog_refs, entry) {
8040 if (strncmp(got_ref_get_name(sre->ref),
8041 "refs/got/", 9) == 0 &&
8042 strncmp(got_ref_get_name(sre->ref),
8043 "refs/got/backup/", 16) != 0)
8044 continue;
8046 re = malloc(sizeof(*re));
8047 if (re == NULL)
8048 return got_error_from_errno("malloc");
8050 re->ref = got_ref_dup(sre->ref);
8051 if (re->ref == NULL)
8052 return got_error_from_errno("got_ref_dup");
8053 re->idx = s->nrefs++;
8054 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8057 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8058 return NULL;
8061 static void
8062 ref_view_free_refs(struct tog_ref_view_state *s)
8064 struct tog_reflist_entry *re;
8066 while (!TAILQ_EMPTY(&s->refs)) {
8067 re = TAILQ_FIRST(&s->refs);
8068 TAILQ_REMOVE(&s->refs, re, entry);
8069 got_ref_close(re->ref);
8070 free(re);
8074 static const struct got_error *
8075 open_ref_view(struct tog_view *view, struct got_repository *repo)
8077 const struct got_error *err = NULL;
8078 struct tog_ref_view_state *s = &view->state.ref;
8080 s->selected_entry = 0;
8081 s->repo = repo;
8083 TAILQ_INIT(&s->refs);
8084 STAILQ_INIT(&s->colors);
8086 err = ref_view_load_refs(s);
8087 if (err)
8088 goto done;
8090 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8091 err = add_color(&s->colors, "^refs/heads/",
8092 TOG_COLOR_REFS_HEADS,
8093 get_color_value("TOG_COLOR_REFS_HEADS"));
8094 if (err)
8095 goto done;
8097 err = add_color(&s->colors, "^refs/tags/",
8098 TOG_COLOR_REFS_TAGS,
8099 get_color_value("TOG_COLOR_REFS_TAGS"));
8100 if (err)
8101 goto done;
8103 err = add_color(&s->colors, "^refs/remotes/",
8104 TOG_COLOR_REFS_REMOTES,
8105 get_color_value("TOG_COLOR_REFS_REMOTES"));
8106 if (err)
8107 goto done;
8109 err = add_color(&s->colors, "^refs/got/backup/",
8110 TOG_COLOR_REFS_BACKUP,
8111 get_color_value("TOG_COLOR_REFS_BACKUP"));
8112 if (err)
8113 goto done;
8116 view->show = show_ref_view;
8117 view->input = input_ref_view;
8118 view->close = close_ref_view;
8119 view->search_start = search_start_ref_view;
8120 view->search_next = search_next_ref_view;
8121 done:
8122 if (err) {
8123 if (view->close == NULL)
8124 close_ref_view(view);
8125 view_close(view);
8127 return err;
8130 static const struct got_error *
8131 close_ref_view(struct tog_view *view)
8133 struct tog_ref_view_state *s = &view->state.ref;
8135 ref_view_free_refs(s);
8136 free_colors(&s->colors);
8138 return NULL;
8141 static const struct got_error *
8142 resolve_reflist_entry(struct got_object_id **commit_id,
8143 struct tog_reflist_entry *re, struct got_repository *repo)
8145 const struct got_error *err = NULL;
8146 struct got_object_id *obj_id;
8147 struct got_tag_object *tag = NULL;
8148 int obj_type;
8150 *commit_id = NULL;
8152 err = got_ref_resolve(&obj_id, repo, re->ref);
8153 if (err)
8154 return err;
8156 err = got_object_get_type(&obj_type, repo, obj_id);
8157 if (err)
8158 goto done;
8160 switch (obj_type) {
8161 case GOT_OBJ_TYPE_COMMIT:
8162 *commit_id = obj_id;
8163 break;
8164 case GOT_OBJ_TYPE_TAG:
8165 err = got_object_open_as_tag(&tag, repo, obj_id);
8166 if (err)
8167 goto done;
8168 free(obj_id);
8169 err = got_object_get_type(&obj_type, repo,
8170 got_object_tag_get_object_id(tag));
8171 if (err)
8172 goto done;
8173 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8174 err = got_error(GOT_ERR_OBJ_TYPE);
8175 goto done;
8177 *commit_id = got_object_id_dup(
8178 got_object_tag_get_object_id(tag));
8179 if (*commit_id == NULL) {
8180 err = got_error_from_errno("got_object_id_dup");
8181 goto done;
8183 break;
8184 default:
8185 err = got_error(GOT_ERR_OBJ_TYPE);
8186 break;
8189 done:
8190 if (tag)
8191 got_object_tag_close(tag);
8192 if (err) {
8193 free(*commit_id);
8194 *commit_id = NULL;
8196 return err;
8199 static const struct got_error *
8200 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8201 struct tog_reflist_entry *re, struct got_repository *repo)
8203 struct tog_view *log_view;
8204 const struct got_error *err = NULL;
8205 struct got_object_id *commit_id = NULL;
8207 *new_view = NULL;
8209 err = resolve_reflist_entry(&commit_id, re, repo);
8210 if (err) {
8211 if (err->code != GOT_ERR_OBJ_TYPE)
8212 return err;
8213 else
8214 return NULL;
8217 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8218 if (log_view == NULL) {
8219 err = got_error_from_errno("view_open");
8220 goto done;
8223 err = open_log_view(log_view, commit_id, repo,
8224 got_ref_get_name(re->ref), "", 0);
8225 done:
8226 if (err)
8227 view_close(log_view);
8228 else
8229 *new_view = log_view;
8230 free(commit_id);
8231 return err;
8234 static void
8235 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8237 struct tog_reflist_entry *re;
8238 int i = 0;
8240 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8241 return;
8243 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8244 while (i++ < maxscroll) {
8245 if (re == NULL)
8246 break;
8247 s->first_displayed_entry = re;
8248 re = TAILQ_PREV(re, tog_reflist_head, entry);
8252 static const struct got_error *
8253 ref_scroll_down(struct tog_view *view, int maxscroll)
8255 struct tog_ref_view_state *s = &view->state.ref;
8256 struct tog_reflist_entry *next, *last;
8257 int n = 0;
8259 if (s->first_displayed_entry)
8260 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8261 else
8262 next = TAILQ_FIRST(&s->refs);
8264 last = s->last_displayed_entry;
8265 while (next && n++ < maxscroll) {
8266 if (last) {
8267 s->last_displayed_entry = last;
8268 last = TAILQ_NEXT(last, entry);
8270 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8271 s->first_displayed_entry = next;
8272 next = TAILQ_NEXT(next, entry);
8276 return NULL;
8279 static const struct got_error *
8280 search_start_ref_view(struct tog_view *view)
8282 struct tog_ref_view_state *s = &view->state.ref;
8284 s->matched_entry = NULL;
8285 return NULL;
8288 static int
8289 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8291 regmatch_t regmatch;
8293 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8294 0) == 0;
8297 static const struct got_error *
8298 search_next_ref_view(struct tog_view *view)
8300 struct tog_ref_view_state *s = &view->state.ref;
8301 struct tog_reflist_entry *re = NULL;
8303 if (!view->searching) {
8304 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8305 return NULL;
8308 if (s->matched_entry) {
8309 if (view->searching == TOG_SEARCH_FORWARD) {
8310 if (s->selected_entry)
8311 re = TAILQ_NEXT(s->selected_entry, entry);
8312 else
8313 re = TAILQ_PREV(s->selected_entry,
8314 tog_reflist_head, entry);
8315 } else {
8316 if (s->selected_entry == NULL)
8317 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8318 else
8319 re = TAILQ_PREV(s->selected_entry,
8320 tog_reflist_head, entry);
8322 } else {
8323 if (s->selected_entry)
8324 re = s->selected_entry;
8325 else if (view->searching == TOG_SEARCH_FORWARD)
8326 re = TAILQ_FIRST(&s->refs);
8327 else
8328 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8331 while (1) {
8332 if (re == NULL) {
8333 if (s->matched_entry == NULL) {
8334 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8335 return NULL;
8337 if (view->searching == TOG_SEARCH_FORWARD)
8338 re = TAILQ_FIRST(&s->refs);
8339 else
8340 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8343 if (match_reflist_entry(re, &view->regex)) {
8344 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8345 s->matched_entry = re;
8346 break;
8349 if (view->searching == TOG_SEARCH_FORWARD)
8350 re = TAILQ_NEXT(re, entry);
8351 else
8352 re = TAILQ_PREV(re, tog_reflist_head, entry);
8355 if (s->matched_entry) {
8356 s->first_displayed_entry = s->matched_entry;
8357 s->selected = 0;
8360 return NULL;
8363 static const struct got_error *
8364 show_ref_view(struct tog_view *view)
8366 const struct got_error *err = NULL;
8367 struct tog_ref_view_state *s = &view->state.ref;
8368 struct tog_reflist_entry *re;
8369 char *line = NULL;
8370 wchar_t *wline;
8371 struct tog_color *tc;
8372 int width, n, scrollx;
8373 int limit = view->nlines;
8375 werase(view->window);
8377 s->ndisplayed = 0;
8378 if (view_is_hsplit_top(view))
8379 --limit; /* border */
8381 if (limit == 0)
8382 return NULL;
8384 re = s->first_displayed_entry;
8386 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8387 s->nrefs) == -1)
8388 return got_error_from_errno("asprintf");
8390 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8391 if (err) {
8392 free(line);
8393 return err;
8395 if (view_needs_focus_indication(view))
8396 wstandout(view->window);
8397 waddwstr(view->window, wline);
8398 while (width++ < view->ncols)
8399 waddch(view->window, ' ');
8400 if (view_needs_focus_indication(view))
8401 wstandend(view->window);
8402 free(wline);
8403 wline = NULL;
8404 free(line);
8405 line = NULL;
8406 if (--limit <= 0)
8407 return NULL;
8409 n = 0;
8410 view->maxx = 0;
8411 while (re && limit > 0) {
8412 char *line = NULL;
8413 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8415 if (s->show_date) {
8416 struct got_commit_object *ci;
8417 struct got_tag_object *tag;
8418 struct got_object_id *id;
8419 struct tm tm;
8420 time_t t;
8422 err = got_ref_resolve(&id, s->repo, re->ref);
8423 if (err)
8424 return err;
8425 err = got_object_open_as_tag(&tag, s->repo, id);
8426 if (err) {
8427 if (err->code != GOT_ERR_OBJ_TYPE) {
8428 free(id);
8429 return err;
8431 err = got_object_open_as_commit(&ci, s->repo,
8432 id);
8433 if (err) {
8434 free(id);
8435 return err;
8437 t = got_object_commit_get_committer_time(ci);
8438 got_object_commit_close(ci);
8439 } else {
8440 t = got_object_tag_get_tagger_time(tag);
8441 got_object_tag_close(tag);
8443 free(id);
8444 if (gmtime_r(&t, &tm) == NULL)
8445 return got_error_from_errno("gmtime_r");
8446 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8447 return got_error(GOT_ERR_NO_SPACE);
8449 if (got_ref_is_symbolic(re->ref)) {
8450 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8451 ymd : "", got_ref_get_name(re->ref),
8452 got_ref_get_symref_target(re->ref)) == -1)
8453 return got_error_from_errno("asprintf");
8454 } else if (s->show_ids) {
8455 struct got_object_id *id;
8456 char *id_str;
8457 err = got_ref_resolve(&id, s->repo, re->ref);
8458 if (err)
8459 return err;
8460 err = got_object_id_str(&id_str, id);
8461 if (err) {
8462 free(id);
8463 return err;
8465 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8466 got_ref_get_name(re->ref), id_str) == -1) {
8467 err = got_error_from_errno("asprintf");
8468 free(id);
8469 free(id_str);
8470 return err;
8472 free(id);
8473 free(id_str);
8474 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8475 got_ref_get_name(re->ref)) == -1)
8476 return got_error_from_errno("asprintf");
8478 /* use full line width to determine view->maxx */
8479 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8480 if (err) {
8481 free(line);
8482 return err;
8484 view->maxx = MAX(view->maxx, width);
8485 free(wline);
8486 wline = NULL;
8488 err = format_line(&wline, &width, &scrollx, line, view->x,
8489 view->ncols, 0, 0);
8490 if (err) {
8491 free(line);
8492 return err;
8494 if (n == s->selected) {
8495 if (view->focussed)
8496 wstandout(view->window);
8497 s->selected_entry = re;
8499 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8500 if (tc)
8501 wattr_on(view->window,
8502 COLOR_PAIR(tc->colorpair), NULL);
8503 waddwstr(view->window, &wline[scrollx]);
8504 if (tc)
8505 wattr_off(view->window,
8506 COLOR_PAIR(tc->colorpair), NULL);
8507 if (width < view->ncols)
8508 waddch(view->window, '\n');
8509 if (n == s->selected && view->focussed)
8510 wstandend(view->window);
8511 free(line);
8512 free(wline);
8513 wline = NULL;
8514 n++;
8515 s->ndisplayed++;
8516 s->last_displayed_entry = re;
8518 limit--;
8519 re = TAILQ_NEXT(re, entry);
8522 view_border(view);
8523 return err;
8526 static const struct got_error *
8527 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8528 struct tog_reflist_entry *re, struct got_repository *repo)
8530 const struct got_error *err = NULL;
8531 struct got_object_id *commit_id = NULL;
8532 struct tog_view *tree_view;
8534 *new_view = NULL;
8536 err = resolve_reflist_entry(&commit_id, re, repo);
8537 if (err) {
8538 if (err->code != GOT_ERR_OBJ_TYPE)
8539 return err;
8540 else
8541 return NULL;
8545 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8546 if (tree_view == NULL) {
8547 err = got_error_from_errno("view_open");
8548 goto done;
8551 err = open_tree_view(tree_view, commit_id,
8552 got_ref_get_name(re->ref), repo);
8553 if (err)
8554 goto done;
8556 *new_view = tree_view;
8557 done:
8558 free(commit_id);
8559 return err;
8562 static const struct got_error *
8563 ref_goto_line(struct tog_view *view, int nlines)
8565 const struct got_error *err = NULL;
8566 struct tog_ref_view_state *s = &view->state.ref;
8567 int g, idx = s->selected_entry->idx;
8569 g = view->gline;
8570 view->gline = 0;
8572 if (g == 0)
8573 g = 1;
8574 else if (g > s->nrefs)
8575 g = s->nrefs;
8577 if (g >= s->first_displayed_entry->idx + 1 &&
8578 g <= s->last_displayed_entry->idx + 1 &&
8579 g - s->first_displayed_entry->idx - 1 < nlines) {
8580 s->selected = g - s->first_displayed_entry->idx - 1;
8581 return NULL;
8584 if (idx + 1 < g) {
8585 err = ref_scroll_down(view, g - idx - 1);
8586 if (err)
8587 return err;
8588 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8589 s->first_displayed_entry->idx + s->selected < g &&
8590 s->selected < s->ndisplayed - 1)
8591 s->selected = g - s->first_displayed_entry->idx - 1;
8592 } else if (idx + 1 > g)
8593 ref_scroll_up(s, idx - g + 1);
8595 if (g < nlines && s->first_displayed_entry->idx == 0)
8596 s->selected = g - 1;
8598 return NULL;
8602 static const struct got_error *
8603 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8605 const struct got_error *err = NULL;
8606 struct tog_ref_view_state *s = &view->state.ref;
8607 struct tog_reflist_entry *re;
8608 int n, nscroll = view->nlines - 1;
8610 if (view->gline)
8611 return ref_goto_line(view, nscroll);
8613 switch (ch) {
8614 case '0':
8615 case '$':
8616 case KEY_RIGHT:
8617 case 'l':
8618 case KEY_LEFT:
8619 case 'h':
8620 horizontal_scroll_input(view, ch);
8621 break;
8622 case 'i':
8623 s->show_ids = !s->show_ids;
8624 view->count = 0;
8625 break;
8626 case 'm':
8627 s->show_date = !s->show_date;
8628 view->count = 0;
8629 break;
8630 case 'o':
8631 s->sort_by_date = !s->sort_by_date;
8632 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8633 view->count = 0;
8634 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8635 got_ref_cmp_by_commit_timestamp_descending :
8636 tog_ref_cmp_by_name, s->repo);
8637 if (err)
8638 break;
8639 got_reflist_object_id_map_free(tog_refs_idmap);
8640 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8641 &tog_refs, s->repo);
8642 if (err)
8643 break;
8644 ref_view_free_refs(s);
8645 err = ref_view_load_refs(s);
8646 break;
8647 case KEY_ENTER:
8648 case '\r':
8649 view->count = 0;
8650 if (!s->selected_entry)
8651 break;
8652 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8653 break;
8654 case 'T':
8655 view->count = 0;
8656 if (!s->selected_entry)
8657 break;
8658 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8659 break;
8660 case 'g':
8661 case '=':
8662 case KEY_HOME:
8663 s->selected = 0;
8664 view->count = 0;
8665 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8666 break;
8667 case 'G':
8668 case '*':
8669 case KEY_END: {
8670 int eos = view->nlines - 1;
8672 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8673 --eos; /* border */
8674 s->selected = 0;
8675 view->count = 0;
8676 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8677 for (n = 0; n < eos; n++) {
8678 if (re == NULL)
8679 break;
8680 s->first_displayed_entry = re;
8681 re = TAILQ_PREV(re, tog_reflist_head, entry);
8683 if (n > 0)
8684 s->selected = n - 1;
8685 break;
8687 case 'k':
8688 case KEY_UP:
8689 case CTRL('p'):
8690 if (s->selected > 0) {
8691 s->selected--;
8692 break;
8694 ref_scroll_up(s, 1);
8695 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8696 view->count = 0;
8697 break;
8698 case CTRL('u'):
8699 case 'u':
8700 nscroll /= 2;
8701 /* FALL THROUGH */
8702 case KEY_PPAGE:
8703 case CTRL('b'):
8704 case 'b':
8705 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8706 s->selected -= MIN(nscroll, s->selected);
8707 ref_scroll_up(s, MAX(0, nscroll));
8708 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8709 view->count = 0;
8710 break;
8711 case 'j':
8712 case KEY_DOWN:
8713 case CTRL('n'):
8714 if (s->selected < s->ndisplayed - 1) {
8715 s->selected++;
8716 break;
8718 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8719 /* can't scroll any further */
8720 view->count = 0;
8721 break;
8723 ref_scroll_down(view, 1);
8724 break;
8725 case CTRL('d'):
8726 case 'd':
8727 nscroll /= 2;
8728 /* FALL THROUGH */
8729 case KEY_NPAGE:
8730 case CTRL('f'):
8731 case 'f':
8732 case ' ':
8733 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8734 /* can't scroll any further; move cursor down */
8735 if (s->selected < s->ndisplayed - 1)
8736 s->selected += MIN(nscroll,
8737 s->ndisplayed - s->selected - 1);
8738 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8739 s->selected += s->ndisplayed - s->selected - 1;
8740 view->count = 0;
8741 break;
8743 ref_scroll_down(view, nscroll);
8744 break;
8745 case CTRL('l'):
8746 view->count = 0;
8747 tog_free_refs();
8748 err = tog_load_refs(s->repo, s->sort_by_date);
8749 if (err)
8750 break;
8751 ref_view_free_refs(s);
8752 err = ref_view_load_refs(s);
8753 break;
8754 case KEY_RESIZE:
8755 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8756 s->selected = view->nlines - 2;
8757 break;
8758 default:
8759 view->count = 0;
8760 break;
8763 return err;
8766 __dead static void
8767 usage_ref(void)
8769 endwin();
8770 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8771 getprogname());
8772 exit(1);
8775 static const struct got_error *
8776 cmd_ref(int argc, char *argv[])
8778 const struct got_error *error;
8779 struct got_repository *repo = NULL;
8780 struct got_worktree *worktree = NULL;
8781 char *cwd = NULL, *repo_path = NULL;
8782 int ch;
8783 struct tog_view *view;
8784 int *pack_fds = NULL;
8786 while ((ch = getopt(argc, argv, "r:")) != -1) {
8787 switch (ch) {
8788 case 'r':
8789 repo_path = realpath(optarg, NULL);
8790 if (repo_path == NULL)
8791 return got_error_from_errno2("realpath",
8792 optarg);
8793 break;
8794 default:
8795 usage_ref();
8796 /* NOTREACHED */
8800 argc -= optind;
8801 argv += optind;
8803 if (argc > 1)
8804 usage_ref();
8806 error = got_repo_pack_fds_open(&pack_fds);
8807 if (error != NULL)
8808 goto done;
8810 if (repo_path == NULL) {
8811 cwd = getcwd(NULL, 0);
8812 if (cwd == NULL)
8813 return got_error_from_errno("getcwd");
8814 error = got_worktree_open(&worktree, cwd);
8815 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8816 goto done;
8817 if (worktree)
8818 repo_path =
8819 strdup(got_worktree_get_repo_path(worktree));
8820 else
8821 repo_path = strdup(cwd);
8822 if (repo_path == NULL) {
8823 error = got_error_from_errno("strdup");
8824 goto done;
8828 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8829 if (error != NULL)
8830 goto done;
8832 init_curses();
8834 error = apply_unveil(got_repo_get_path(repo), NULL);
8835 if (error)
8836 goto done;
8838 error = tog_load_refs(repo, 0);
8839 if (error)
8840 goto done;
8842 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8843 if (view == NULL) {
8844 error = got_error_from_errno("view_open");
8845 goto done;
8848 error = open_ref_view(view, repo);
8849 if (error)
8850 goto done;
8852 if (worktree) {
8853 /* Release work tree lock. */
8854 got_worktree_close(worktree);
8855 worktree = NULL;
8857 error = view_loop(view);
8858 done:
8859 free(repo_path);
8860 free(cwd);
8861 if (repo) {
8862 const struct got_error *close_err = got_repo_close(repo);
8863 if (close_err)
8864 error = close_err;
8866 if (pack_fds) {
8867 const struct got_error *pack_err =
8868 got_repo_pack_fds_close(pack_fds);
8869 if (error == NULL)
8870 error = pack_err;
8872 tog_free_refs();
8873 return error;
8876 static const struct got_error*
8877 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8878 const char *str)
8880 size_t len;
8882 if (win == NULL)
8883 win = stdscr;
8885 len = strlen(str);
8886 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8888 if (focus)
8889 wstandout(win);
8890 if (mvwprintw(win, y, x, "%s", str) == ERR)
8891 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8892 if (focus)
8893 wstandend(win);
8895 return NULL;
8898 static const struct got_error *
8899 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8901 off_t *p;
8903 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8904 if (p == NULL) {
8905 free(*line_offsets);
8906 *line_offsets = NULL;
8907 return got_error_from_errno("reallocarray");
8910 *line_offsets = p;
8911 (*line_offsets)[*nlines] = off;
8912 ++(*nlines);
8913 return NULL;
8916 static const struct got_error *
8917 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8919 *ret = 0;
8921 for (;n > 0; --n, ++km) {
8922 char *t0, *t, *k;
8923 size_t len = 1;
8925 if (km->keys == NULL)
8926 continue;
8928 t = t0 = strdup(km->keys);
8929 if (t0 == NULL)
8930 return got_error_from_errno("strdup");
8932 len += strlen(t);
8933 while ((k = strsep(&t, " ")) != NULL)
8934 len += strlen(k) > 1 ? 2 : 0;
8935 free(t0);
8936 *ret = MAX(*ret, len);
8939 return NULL;
8943 * Write keymap section headers, keys, and key info in km to f.
8944 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8945 * wrap control and symbolic keys in guillemets, else use <>.
8947 static const struct got_error *
8948 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8950 int n, len = width;
8952 if (km->keys) {
8953 static const char *u8_glyph[] = {
8954 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8955 "\xe2\x80\xba" /* U+203A (utf8 >) */
8957 char *t0, *t, *k;
8958 int cs, s, first = 1;
8960 cs = got_locale_is_utf8();
8962 t = t0 = strdup(km->keys);
8963 if (t0 == NULL)
8964 return got_error_from_errno("strdup");
8966 len = strlen(km->keys);
8967 while ((k = strsep(&t, " ")) != NULL) {
8968 s = strlen(k) > 1; /* control or symbolic key */
8969 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8970 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8971 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8972 if (n < 0) {
8973 free(t0);
8974 return got_error_from_errno("fprintf");
8976 first = 0;
8977 len += s ? 2 : 0;
8978 *off += n;
8980 free(t0);
8982 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8983 if (n < 0)
8984 return got_error_from_errno("fprintf");
8985 *off += n;
8987 return NULL;
8990 static const struct got_error *
8991 format_help(struct tog_help_view_state *s)
8993 const struct got_error *err = NULL;
8994 off_t off = 0;
8995 int i, max, n, show = s->all;
8996 static const struct tog_key_map km[] = {
8997 #define KEYMAP_(info, type) { NULL, (info), type }
8998 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8999 GENERATE_HELP
9000 #undef KEYMAP_
9001 #undef KEY_
9004 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9005 if (err)
9006 return err;
9008 n = nitems(km);
9009 err = max_key_str(&max, km, n);
9010 if (err)
9011 return err;
9013 for (i = 0; i < n; ++i) {
9014 if (km[i].keys == NULL) {
9015 show = s->all;
9016 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9017 km[i].type == s->type || s->all)
9018 show = 1;
9020 if (show) {
9021 err = format_help_line(&off, s->f, &km[i], max);
9022 if (err)
9023 return err;
9024 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9025 if (err)
9026 return err;
9029 fputc('\n', s->f);
9030 ++off;
9031 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9032 return err;
9035 static const struct got_error *
9036 create_help(struct tog_help_view_state *s)
9038 FILE *f;
9039 const struct got_error *err;
9041 free(s->line_offsets);
9042 s->line_offsets = NULL;
9043 s->nlines = 0;
9045 f = got_opentemp();
9046 if (f == NULL)
9047 return got_error_from_errno("got_opentemp");
9048 s->f = f;
9050 err = format_help(s);
9051 if (err)
9052 return err;
9054 if (s->f && fflush(s->f) != 0)
9055 return got_error_from_errno("fflush");
9057 return NULL;
9060 static const struct got_error *
9061 search_start_help_view(struct tog_view *view)
9063 view->state.help.matched_line = 0;
9064 return NULL;
9067 static void
9068 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9069 size_t *nlines, int **first, int **last, int **match, int **selected)
9071 struct tog_help_view_state *s = &view->state.help;
9073 *f = s->f;
9074 *nlines = s->nlines;
9075 *line_offsets = s->line_offsets;
9076 *match = &s->matched_line;
9077 *first = &s->first_displayed_line;
9078 *last = &s->last_displayed_line;
9079 *selected = &s->selected_line;
9082 static const struct got_error *
9083 show_help_view(struct tog_view *view)
9085 struct tog_help_view_state *s = &view->state.help;
9086 const struct got_error *err;
9087 regmatch_t *regmatch = &view->regmatch;
9088 wchar_t *wline;
9089 char *line;
9090 ssize_t linelen;
9091 size_t linesz = 0;
9092 int width, nprinted = 0, rc = 0;
9093 int eos = view->nlines;
9095 if (view_is_hsplit_top(view))
9096 --eos; /* account for border */
9098 s->lineno = 0;
9099 rewind(s->f);
9100 werase(view->window);
9102 if (view->gline > s->nlines - 1)
9103 view->gline = s->nlines - 1;
9105 err = win_draw_center(view->window, 0, 0, view->ncols,
9106 view_needs_focus_indication(view),
9107 "tog help (press q to return to tog)");
9108 if (err)
9109 return err;
9110 if (eos <= 1)
9111 return NULL;
9112 waddstr(view->window, "\n\n");
9113 eos -= 2;
9115 s->eof = 0;
9116 view->maxx = 0;
9117 line = NULL;
9118 while (eos > 0 && nprinted < eos) {
9119 attr_t attr = 0;
9121 linelen = getline(&line, &linesz, s->f);
9122 if (linelen == -1) {
9123 if (!feof(s->f)) {
9124 free(line);
9125 return got_ferror(s->f, GOT_ERR_IO);
9127 s->eof = 1;
9128 break;
9130 if (++s->lineno < s->first_displayed_line)
9131 continue;
9132 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9133 continue;
9134 if (s->lineno == view->hiline)
9135 attr = A_STANDOUT;
9137 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9138 view->x ? 1 : 0);
9139 if (err) {
9140 free(line);
9141 return err;
9143 view->maxx = MAX(view->maxx, width);
9144 free(wline);
9145 wline = NULL;
9147 if (attr)
9148 wattron(view->window, attr);
9149 if (s->first_displayed_line + nprinted == s->matched_line &&
9150 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9151 err = add_matched_line(&width, line, view->ncols - 1, 0,
9152 view->window, view->x, regmatch);
9153 if (err) {
9154 free(line);
9155 return err;
9157 } else {
9158 int skip;
9160 err = format_line(&wline, &width, &skip, line,
9161 view->x, view->ncols, 0, view->x ? 1 : 0);
9162 if (err) {
9163 free(line);
9164 return err;
9166 waddwstr(view->window, &wline[skip]);
9167 free(wline);
9168 wline = NULL;
9170 if (s->lineno == view->hiline) {
9171 while (width++ < view->ncols)
9172 waddch(view->window, ' ');
9173 } else {
9174 if (width < view->ncols)
9175 waddch(view->window, '\n');
9177 if (attr)
9178 wattroff(view->window, attr);
9179 if (++nprinted == 1)
9180 s->first_displayed_line = s->lineno;
9182 free(line);
9183 if (nprinted > 0)
9184 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9185 else
9186 s->last_displayed_line = s->first_displayed_line;
9188 view_border(view);
9190 if (s->eof) {
9191 rc = waddnstr(view->window,
9192 "See the tog(1) manual page for full documentation",
9193 view->ncols - 1);
9194 if (rc == ERR)
9195 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9196 } else {
9197 wmove(view->window, view->nlines - 1, 0);
9198 wclrtoeol(view->window);
9199 wstandout(view->window);
9200 rc = waddnstr(view->window, "scroll down for more...",
9201 view->ncols - 1);
9202 if (rc == ERR)
9203 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9204 if (getcurx(view->window) < view->ncols - 6) {
9205 rc = wprintw(view->window, "[%.0f%%]",
9206 100.00 * s->last_displayed_line / s->nlines);
9207 if (rc == ERR)
9208 return got_error_msg(GOT_ERR_IO, "wprintw");
9210 wstandend(view->window);
9213 return NULL;
9216 static const struct got_error *
9217 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9219 struct tog_help_view_state *s = &view->state.help;
9220 const struct got_error *err = NULL;
9221 char *line = NULL;
9222 ssize_t linelen;
9223 size_t linesz = 0;
9224 int eos, nscroll;
9226 eos = nscroll = view->nlines;
9227 if (view_is_hsplit_top(view))
9228 --eos; /* border */
9230 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9232 switch (ch) {
9233 case '0':
9234 case '$':
9235 case KEY_RIGHT:
9236 case 'l':
9237 case KEY_LEFT:
9238 case 'h':
9239 horizontal_scroll_input(view, ch);
9240 break;
9241 case 'g':
9242 case KEY_HOME:
9243 s->first_displayed_line = 1;
9244 view->count = 0;
9245 break;
9246 case 'G':
9247 case KEY_END:
9248 view->count = 0;
9249 if (s->eof)
9250 break;
9251 s->first_displayed_line = (s->nlines - eos) + 3;
9252 s->eof = 1;
9253 break;
9254 case 'k':
9255 case KEY_UP:
9256 if (s->first_displayed_line > 1)
9257 --s->first_displayed_line;
9258 else
9259 view->count = 0;
9260 break;
9261 case CTRL('u'):
9262 case 'u':
9263 nscroll /= 2;
9264 /* FALL THROUGH */
9265 case KEY_PPAGE:
9266 case CTRL('b'):
9267 case 'b':
9268 if (s->first_displayed_line == 1) {
9269 view->count = 0;
9270 break;
9272 while (--nscroll > 0 && s->first_displayed_line > 1)
9273 s->first_displayed_line--;
9274 break;
9275 case 'j':
9276 case KEY_DOWN:
9277 case CTRL('n'):
9278 if (!s->eof)
9279 ++s->first_displayed_line;
9280 else
9281 view->count = 0;
9282 break;
9283 case CTRL('d'):
9284 case 'd':
9285 nscroll /= 2;
9286 /* FALL THROUGH */
9287 case KEY_NPAGE:
9288 case CTRL('f'):
9289 case 'f':
9290 case ' ':
9291 if (s->eof) {
9292 view->count = 0;
9293 break;
9295 while (!s->eof && --nscroll > 0) {
9296 linelen = getline(&line, &linesz, s->f);
9297 s->first_displayed_line++;
9298 if (linelen == -1) {
9299 if (feof(s->f))
9300 s->eof = 1;
9301 else
9302 err = got_ferror(s->f, GOT_ERR_IO);
9303 break;
9306 free(line);
9307 break;
9308 default:
9309 view->count = 0;
9310 break;
9313 return err;
9316 static const struct got_error *
9317 close_help_view(struct tog_view *view)
9319 struct tog_help_view_state *s = &view->state.help;
9321 free(s->line_offsets);
9322 s->line_offsets = NULL;
9323 if (fclose(s->f) == EOF)
9324 return got_error_from_errno("fclose");
9326 return NULL;
9329 static const struct got_error *
9330 reset_help_view(struct tog_view *view)
9332 struct tog_help_view_state *s = &view->state.help;
9335 if (s->f && fclose(s->f) == EOF)
9336 return got_error_from_errno("fclose");
9338 wclear(view->window);
9339 view->count = 0;
9340 view->x = 0;
9341 s->all = !s->all;
9342 s->first_displayed_line = 1;
9343 s->last_displayed_line = view->nlines;
9344 s->matched_line = 0;
9346 return create_help(s);
9349 static const struct got_error *
9350 open_help_view(struct tog_view *view, struct tog_view *parent)
9352 const struct got_error *err = NULL;
9353 struct tog_help_view_state *s = &view->state.help;
9355 s->type = (enum tog_keymap_type)parent->type;
9356 s->first_displayed_line = 1;
9357 s->last_displayed_line = view->nlines;
9358 s->selected_line = 1;
9360 view->show = show_help_view;
9361 view->input = input_help_view;
9362 view->reset = reset_help_view;
9363 view->close = close_help_view;
9364 view->search_start = search_start_help_view;
9365 view->search_setup = search_setup_help_view;
9366 view->search_next = search_next_view_match;
9368 err = create_help(s);
9369 return err;
9372 static const struct got_error *
9373 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9374 enum tog_view_type request, int y, int x)
9376 const struct got_error *err = NULL;
9378 *new_view = NULL;
9380 switch (request) {
9381 case TOG_VIEW_DIFF:
9382 if (view->type == TOG_VIEW_LOG) {
9383 struct tog_log_view_state *s = &view->state.log;
9385 err = open_diff_view_for_commit(new_view, y, x,
9386 s->selected_entry->commit, s->selected_entry->id,
9387 view, s->repo);
9388 } else
9389 return got_error_msg(GOT_ERR_NOT_IMPL,
9390 "parent/child view pair not supported");
9391 break;
9392 case TOG_VIEW_BLAME:
9393 if (view->type == TOG_VIEW_TREE) {
9394 struct tog_tree_view_state *s = &view->state.tree;
9396 err = blame_tree_entry(new_view, y, x,
9397 s->selected_entry, &s->parents, s->commit_id,
9398 s->repo);
9399 } else
9400 return got_error_msg(GOT_ERR_NOT_IMPL,
9401 "parent/child view pair not supported");
9402 break;
9403 case TOG_VIEW_LOG:
9404 if (view->type == TOG_VIEW_BLAME)
9405 err = log_annotated_line(new_view, y, x,
9406 view->state.blame.repo, view->state.blame.id_to_log);
9407 else if (view->type == TOG_VIEW_TREE)
9408 err = log_selected_tree_entry(new_view, y, x,
9409 &view->state.tree);
9410 else if (view->type == TOG_VIEW_REF)
9411 err = log_ref_entry(new_view, y, x,
9412 view->state.ref.selected_entry,
9413 view->state.ref.repo);
9414 else
9415 return got_error_msg(GOT_ERR_NOT_IMPL,
9416 "parent/child view pair not supported");
9417 break;
9418 case TOG_VIEW_TREE:
9419 if (view->type == TOG_VIEW_LOG)
9420 err = browse_commit_tree(new_view, y, x,
9421 view->state.log.selected_entry,
9422 view->state.log.in_repo_path,
9423 view->state.log.head_ref_name,
9424 view->state.log.repo);
9425 else if (view->type == TOG_VIEW_REF)
9426 err = browse_ref_tree(new_view, y, x,
9427 view->state.ref.selected_entry,
9428 view->state.ref.repo);
9429 else
9430 return got_error_msg(GOT_ERR_NOT_IMPL,
9431 "parent/child view pair not supported");
9432 break;
9433 case TOG_VIEW_REF:
9434 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9435 if (*new_view == NULL)
9436 return got_error_from_errno("view_open");
9437 if (view->type == TOG_VIEW_LOG)
9438 err = open_ref_view(*new_view, view->state.log.repo);
9439 else if (view->type == TOG_VIEW_TREE)
9440 err = open_ref_view(*new_view, view->state.tree.repo);
9441 else
9442 err = got_error_msg(GOT_ERR_NOT_IMPL,
9443 "parent/child view pair not supported");
9444 if (err)
9445 view_close(*new_view);
9446 break;
9447 case TOG_VIEW_HELP:
9448 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9449 if (*new_view == NULL)
9450 return got_error_from_errno("view_open");
9451 err = open_help_view(*new_view, view);
9452 if (err)
9453 view_close(*new_view);
9454 break;
9455 default:
9456 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9459 return err;
9463 * If view was scrolled down to move the selected line into view when opening a
9464 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9466 static void
9467 offset_selection_up(struct tog_view *view)
9469 switch (view->type) {
9470 case TOG_VIEW_BLAME: {
9471 struct tog_blame_view_state *s = &view->state.blame;
9472 if (s->first_displayed_line == 1) {
9473 s->selected_line = MAX(s->selected_line - view->offset,
9474 1);
9475 break;
9477 if (s->first_displayed_line > view->offset)
9478 s->first_displayed_line -= view->offset;
9479 else
9480 s->first_displayed_line = 1;
9481 s->selected_line += view->offset;
9482 break;
9484 case TOG_VIEW_LOG:
9485 log_scroll_up(&view->state.log, view->offset);
9486 view->state.log.selected += view->offset;
9487 break;
9488 case TOG_VIEW_REF:
9489 ref_scroll_up(&view->state.ref, view->offset);
9490 view->state.ref.selected += view->offset;
9491 break;
9492 case TOG_VIEW_TREE:
9493 tree_scroll_up(&view->state.tree, view->offset);
9494 view->state.tree.selected += view->offset;
9495 break;
9496 default:
9497 break;
9500 view->offset = 0;
9504 * If the selected line is in the section of screen covered by the bottom split,
9505 * scroll down offset lines to move it into view and index its new position.
9507 static const struct got_error *
9508 offset_selection_down(struct tog_view *view)
9510 const struct got_error *err = NULL;
9511 const struct got_error *(*scrolld)(struct tog_view *, int);
9512 int *selected = NULL;
9513 int header, offset;
9515 switch (view->type) {
9516 case TOG_VIEW_BLAME: {
9517 struct tog_blame_view_state *s = &view->state.blame;
9518 header = 3;
9519 scrolld = NULL;
9520 if (s->selected_line > view->nlines - header) {
9521 offset = abs(view->nlines - s->selected_line - header);
9522 s->first_displayed_line += offset;
9523 s->selected_line -= offset;
9524 view->offset = offset;
9526 break;
9528 case TOG_VIEW_LOG: {
9529 struct tog_log_view_state *s = &view->state.log;
9530 scrolld = &log_scroll_down;
9531 header = view_is_parent_view(view) ? 3 : 2;
9532 selected = &s->selected;
9533 break;
9535 case TOG_VIEW_REF: {
9536 struct tog_ref_view_state *s = &view->state.ref;
9537 scrolld = &ref_scroll_down;
9538 header = 3;
9539 selected = &s->selected;
9540 break;
9542 case TOG_VIEW_TREE: {
9543 struct tog_tree_view_state *s = &view->state.tree;
9544 scrolld = &tree_scroll_down;
9545 header = 5;
9546 selected = &s->selected;
9547 break;
9549 default:
9550 selected = NULL;
9551 scrolld = NULL;
9552 header = 0;
9553 break;
9556 if (selected && *selected > view->nlines - header) {
9557 offset = abs(view->nlines - *selected - header);
9558 view->offset = offset;
9559 if (scrolld && offset) {
9560 err = scrolld(view, offset);
9561 *selected -= offset;
9565 return err;
9568 static void
9569 list_commands(FILE *fp)
9571 size_t i;
9573 fprintf(fp, "commands:");
9574 for (i = 0; i < nitems(tog_commands); i++) {
9575 const struct tog_cmd *cmd = &tog_commands[i];
9576 fprintf(fp, " %s", cmd->name);
9578 fputc('\n', fp);
9581 __dead static void
9582 usage(int hflag, int status)
9584 FILE *fp = (status == 0) ? stdout : stderr;
9586 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9587 getprogname());
9588 if (hflag) {
9589 fprintf(fp, "lazy usage: %s path\n", getprogname());
9590 list_commands(fp);
9592 exit(status);
9595 static char **
9596 make_argv(int argc, ...)
9598 va_list ap;
9599 char **argv;
9600 int i;
9602 va_start(ap, argc);
9604 argv = calloc(argc, sizeof(char *));
9605 if (argv == NULL)
9606 err(1, "calloc");
9607 for (i = 0; i < argc; i++) {
9608 argv[i] = strdup(va_arg(ap, char *));
9609 if (argv[i] == NULL)
9610 err(1, "strdup");
9613 va_end(ap);
9614 return argv;
9618 * Try to convert 'tog path' into a 'tog log path' command.
9619 * The user could simply have mistyped the command rather than knowingly
9620 * provided a path. So check whether argv[0] can in fact be resolved
9621 * to a path in the HEAD commit and print a special error if not.
9622 * This hack is for mpi@ <3
9624 static const struct got_error *
9625 tog_log_with_path(int argc, char *argv[])
9627 const struct got_error *error = NULL, *close_err;
9628 const struct tog_cmd *cmd = NULL;
9629 struct got_repository *repo = NULL;
9630 struct got_worktree *worktree = NULL;
9631 struct got_object_id *commit_id = NULL, *id = NULL;
9632 struct got_commit_object *commit = NULL;
9633 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9634 char *commit_id_str = NULL, **cmd_argv = NULL;
9635 int *pack_fds = NULL;
9637 cwd = getcwd(NULL, 0);
9638 if (cwd == NULL)
9639 return got_error_from_errno("getcwd");
9641 error = got_repo_pack_fds_open(&pack_fds);
9642 if (error != NULL)
9643 goto done;
9645 error = got_worktree_open(&worktree, cwd);
9646 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9647 goto done;
9649 if (worktree)
9650 repo_path = strdup(got_worktree_get_repo_path(worktree));
9651 else
9652 repo_path = strdup(cwd);
9653 if (repo_path == NULL) {
9654 error = got_error_from_errno("strdup");
9655 goto done;
9658 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9659 if (error != NULL)
9660 goto done;
9662 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9663 repo, worktree);
9664 if (error)
9665 goto done;
9667 error = tog_load_refs(repo, 0);
9668 if (error)
9669 goto done;
9670 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9671 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9672 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9673 if (error)
9674 goto done;
9676 if (worktree) {
9677 got_worktree_close(worktree);
9678 worktree = NULL;
9681 error = got_object_open_as_commit(&commit, repo, commit_id);
9682 if (error)
9683 goto done;
9685 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9686 if (error) {
9687 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9688 goto done;
9689 fprintf(stderr, "%s: '%s' is no known command or path\n",
9690 getprogname(), argv[0]);
9691 usage(1, 1);
9692 /* not reached */
9695 error = got_object_id_str(&commit_id_str, commit_id);
9696 if (error)
9697 goto done;
9699 cmd = &tog_commands[0]; /* log */
9700 argc = 4;
9701 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9702 error = cmd->cmd_main(argc, cmd_argv);
9703 done:
9704 if (repo) {
9705 close_err = got_repo_close(repo);
9706 if (error == NULL)
9707 error = close_err;
9709 if (commit)
9710 got_object_commit_close(commit);
9711 if (worktree)
9712 got_worktree_close(worktree);
9713 if (pack_fds) {
9714 const struct got_error *pack_err =
9715 got_repo_pack_fds_close(pack_fds);
9716 if (error == NULL)
9717 error = pack_err;
9719 free(id);
9720 free(commit_id_str);
9721 free(commit_id);
9722 free(cwd);
9723 free(repo_path);
9724 free(in_repo_path);
9725 if (cmd_argv) {
9726 int i;
9727 for (i = 0; i < argc; i++)
9728 free(cmd_argv[i]);
9729 free(cmd_argv);
9731 tog_free_refs();
9732 return error;
9735 int
9736 main(int argc, char *argv[])
9738 const struct got_error *io_err, *error = NULL;
9739 const struct tog_cmd *cmd = NULL;
9740 int ch, hflag = 0, Vflag = 0;
9741 char **cmd_argv = NULL;
9742 static const struct option longopts[] = {
9743 { "version", no_argument, NULL, 'V' },
9744 { NULL, 0, NULL, 0}
9746 char *diff_algo_str = NULL;
9747 const char *test_script_path;
9749 setlocale(LC_CTYPE, "");
9752 * Test mode init must happen before pledge() because "tty" will
9753 * not allow TTY-related ioctls to occur via regular files.
9755 test_script_path = getenv("TOG_TEST_SCRIPT");
9756 if (test_script_path != NULL) {
9757 error = init_mock_term(test_script_path);
9758 if (error) {
9759 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9760 return 1;
9764 #if !defined(PROFILE)
9765 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9766 NULL) == -1)
9767 err(1, "pledge");
9768 #endif
9770 if (!isatty(STDIN_FILENO))
9771 errx(1, "standard input is not a tty");
9773 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9774 switch (ch) {
9775 case 'h':
9776 hflag = 1;
9777 break;
9778 case 'V':
9779 Vflag = 1;
9780 break;
9781 default:
9782 usage(hflag, 1);
9783 /* NOTREACHED */
9787 argc -= optind;
9788 argv += optind;
9789 optind = 1;
9790 optreset = 1;
9792 if (Vflag) {
9793 got_version_print_str();
9794 return 0;
9797 if (argc == 0) {
9798 if (hflag)
9799 usage(hflag, 0);
9800 /* Build an argument vector which runs a default command. */
9801 cmd = &tog_commands[0];
9802 argc = 1;
9803 cmd_argv = make_argv(argc, cmd->name);
9804 } else {
9805 size_t i;
9807 /* Did the user specify a command? */
9808 for (i = 0; i < nitems(tog_commands); i++) {
9809 if (strncmp(tog_commands[i].name, argv[0],
9810 strlen(argv[0])) == 0) {
9811 cmd = &tog_commands[i];
9812 break;
9817 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9818 if (diff_algo_str) {
9819 if (strcasecmp(diff_algo_str, "patience") == 0)
9820 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9821 if (strcasecmp(diff_algo_str, "myers") == 0)
9822 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9825 if (cmd == NULL) {
9826 if (argc != 1)
9827 usage(0, 1);
9828 /* No command specified; try log with a path */
9829 error = tog_log_with_path(argc, argv);
9830 } else {
9831 if (hflag)
9832 cmd->cmd_usage();
9833 else
9834 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9837 if (using_mock_io) {
9838 io_err = tog_io_close();
9839 if (error == NULL)
9840 error = io_err;
9842 endwin();
9843 if (cmd_argv) {
9844 int i;
9845 for (i = 0; i < argc; i++)
9846 free(cmd_argv[i]);
9847 free(cmd_argv);
9850 if (error && error->code != GOT_ERR_CANCELLED &&
9851 error->code != GOT_ERR_EOF &&
9852 error->code != GOT_ERR_PRIVSEP_EXIT &&
9853 error->code != GOT_ERR_PRIVSEP_PIPE &&
9854 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9855 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9856 return 0;