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.3f /* 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 pthread_cond_t blame_complete;
436 };
438 struct tog_blame {
439 FILE *f;
440 off_t filesize;
441 struct tog_blame_line *lines;
442 int nlines;
443 off_t *line_offsets;
444 pthread_t thread;
445 struct tog_blame_thread_args thread_args;
446 struct tog_blame_cb_args cb_args;
447 const char *path;
448 int *pack_fds;
449 };
451 struct tog_blame_view_state {
452 int first_displayed_line;
453 int last_displayed_line;
454 int selected_line;
455 int last_diffed_line;
456 int blame_complete;
457 int eof;
458 int done;
459 struct got_object_id_queue blamed_commits;
460 struct got_object_qid *blamed_commit;
461 char *path;
462 struct got_repository *repo;
463 struct got_object_id *commit_id;
464 struct got_object_id *id_to_log;
465 struct tog_blame blame;
466 int matched_line;
467 struct tog_colors colors;
468 };
470 struct tog_parent_tree {
471 TAILQ_ENTRY(tog_parent_tree) entry;
472 struct got_tree_object *tree;
473 struct got_tree_entry *first_displayed_entry;
474 struct got_tree_entry *selected_entry;
475 int selected;
476 };
478 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
480 struct tog_tree_view_state {
481 char *tree_label;
482 struct got_object_id *commit_id;/* commit which this tree belongs to */
483 struct got_tree_object *root; /* the commit's root tree entry */
484 struct got_tree_object *tree; /* currently displayed (sub-)tree */
485 struct got_tree_entry *first_displayed_entry;
486 struct got_tree_entry *last_displayed_entry;
487 struct got_tree_entry *selected_entry;
488 int ndisplayed, selected, show_ids;
489 struct tog_parent_trees parents; /* parent trees of current sub-tree */
490 char *head_ref_name;
491 struct got_repository *repo;
492 struct got_tree_entry *matched_entry;
493 struct tog_colors colors;
494 };
496 struct tog_reflist_entry {
497 TAILQ_ENTRY(tog_reflist_entry) entry;
498 struct got_reference *ref;
499 int idx;
500 };
502 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
504 struct tog_ref_view_state {
505 struct tog_reflist_head refs;
506 struct tog_reflist_entry *first_displayed_entry;
507 struct tog_reflist_entry *last_displayed_entry;
508 struct tog_reflist_entry *selected_entry;
509 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
510 struct got_repository *repo;
511 struct tog_reflist_entry *matched_entry;
512 struct tog_colors colors;
513 };
515 struct tog_help_view_state {
516 FILE *f;
517 off_t *line_offsets;
518 size_t nlines;
519 int lineno;
520 int first_displayed_line;
521 int last_displayed_line;
522 int eof;
523 int matched_line;
524 int selected_line;
525 int all;
526 enum tog_keymap_type type;
527 };
529 #define GENERATE_HELP \
530 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
531 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
532 KEY_("k C-p Up", "Move cursor or page up one line"), \
533 KEY_("j C-n Down", "Move cursor or page down one line"), \
534 KEY_("C-b b PgUp", "Scroll the view up one page"), \
535 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
536 KEY_("C-u u", "Scroll the view up one half page"), \
537 KEY_("C-d d", "Scroll the view down one half page"), \
538 KEY_("g", "Go to line N (default: first line)"), \
539 KEY_("Home =", "Go to the first line"), \
540 KEY_("G", "Go to line N (default: last line)"), \
541 KEY_("End *", "Go to the last line"), \
542 KEY_("l Right", "Scroll the view right"), \
543 KEY_("h Left", "Scroll the view left"), \
544 KEY_("$", "Scroll view to the rightmost position"), \
545 KEY_("0", "Scroll view to the leftmost position"), \
546 KEY_("-", "Decrease size of the focussed split"), \
547 KEY_("+", "Increase size of the focussed split"), \
548 KEY_("Tab", "Switch focus between views"), \
549 KEY_("F", "Toggle fullscreen mode"), \
550 KEY_("S", "Switch split-screen layout"), \
551 KEY_("/", "Open prompt to enter search term"), \
552 KEY_("n", "Find next line/token matching the current search term"), \
553 KEY_("N", "Find previous line/token matching the current search term"),\
554 KEY_("q", "Quit the focussed view; Quit help screen"), \
555 KEY_("Q", "Quit tog"), \
557 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
558 KEY_("< ,", "Move cursor up one commit"), \
559 KEY_("> .", "Move cursor down one commit"), \
560 KEY_("Enter", "Open diff view of the selected commit"), \
561 KEY_("B", "Reload the log view and toggle display of merged commits"), \
562 KEY_("R", "Open ref view of all repository references"), \
563 KEY_("T", "Display tree view of the repository from the selected" \
564 " commit"), \
565 KEY_("@", "Toggle between displaying author and committer name"), \
566 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
567 KEY_("C-g Backspace", "Cancel current search or log operation"), \
568 KEY_("C-l", "Reload the log view with new commits in the repository"), \
570 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
571 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
572 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
573 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
574 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
575 " data"), \
576 KEY_("(", "Go to the previous file in the diff"), \
577 KEY_(")", "Go to the next file in the diff"), \
578 KEY_("{", "Go to the previous hunk in the diff"), \
579 KEY_("}", "Go to the next hunk in the diff"), \
580 KEY_("[", "Decrease the number of context lines"), \
581 KEY_("]", "Increase the number of context lines"), \
582 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
584 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
585 KEY_("Enter", "Display diff view of the selected line's commit"), \
586 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
587 KEY_("L", "Open log view for the currently selected annotated line"), \
588 KEY_("C", "Reload view with the previously blamed commit"), \
589 KEY_("c", "Reload view with the version of the file found in the" \
590 " selected line's commit"), \
591 KEY_("p", "Reload view with the version of the file found in the" \
592 " selected line's parent commit"), \
594 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
595 KEY_("Enter", "Enter selected directory or open blame view of the" \
596 " selected file"), \
597 KEY_("L", "Open log view for the selected entry"), \
598 KEY_("R", "Open ref view of all repository references"), \
599 KEY_("i", "Show object IDs for all tree entries"), \
600 KEY_("Backspace", "Return to the parent directory"), \
602 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
603 KEY_("Enter", "Display log view of the selected reference"), \
604 KEY_("T", "Display tree view of the selected reference"), \
605 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
606 KEY_("m", "Toggle display of last modified date for each reference"), \
607 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
608 KEY_("C-l", "Reload view with all repository references")
610 struct tog_key_map {
611 const char *keys;
612 const char *info;
613 enum tog_keymap_type type;
614 };
616 /* curses io for tog regress */
617 struct tog_io {
618 FILE *cin;
619 FILE *cout;
620 FILE *f;
621 FILE *sdump;
622 int wait_for_ui;
623 } tog_io;
624 static int using_mock_io;
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, ACS_HLINE, view->ncols);
986 else
987 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
988 ACS_VLINE, view->nlines);
991 static const struct got_error *view_init_hsplit(struct tog_view *, int);
992 static const struct got_error *request_log_commits(struct tog_view *);
993 static const struct got_error *offset_selection_down(struct tog_view *);
994 static void offset_selection_up(struct tog_view *);
995 static void view_get_split(struct tog_view *, int *, int *);
997 static const struct got_error *
998 view_resize(struct tog_view *view)
1000 const struct got_error *err = NULL;
1001 int dif, nlines, ncols;
1003 dif = LINES - view->lines; /* line difference */
1005 if (view->lines > LINES)
1006 nlines = view->nlines - (view->lines - LINES);
1007 else
1008 nlines = view->nlines + (LINES - view->lines);
1009 if (view->cols > COLS)
1010 ncols = view->ncols - (view->cols - COLS);
1011 else
1012 ncols = view->ncols + (COLS - view->cols);
1014 if (view->child) {
1015 int hs = view->child->begin_y;
1017 if (!view_is_fullscreen(view))
1018 view->child->begin_x = view_split_begin_x(view->begin_x);
1019 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1020 view->child->begin_x == 0) {
1021 ncols = COLS;
1023 view_fullscreen(view->child);
1024 if (view->child->focussed)
1025 show_panel(view->child->panel);
1026 else
1027 show_panel(view->panel);
1028 } else {
1029 ncols = view->child->begin_x;
1031 view_splitscreen(view->child);
1032 show_panel(view->child->panel);
1035 * XXX This is ugly and needs to be moved into the above
1036 * logic but "works" for now and my attempts at moving it
1037 * break either 'tab' or 'F' key maps in horizontal splits.
1039 if (hs) {
1040 err = view_splitscreen(view->child);
1041 if (err)
1042 return err;
1043 if (dif < 0) { /* top split decreased */
1044 err = offset_selection_down(view);
1045 if (err)
1046 return err;
1048 view_border(view);
1049 update_panels();
1050 doupdate();
1051 show_panel(view->child->panel);
1052 nlines = view->nlines;
1054 } else if (view->parent == NULL)
1055 ncols = COLS;
1057 if (view->resize && dif > 0) {
1058 err = view->resize(view, dif);
1059 if (err)
1060 return err;
1063 if (wresize(view->window, nlines, ncols) == ERR)
1064 return got_error_from_errno("wresize");
1065 if (replace_panel(view->panel, view->window) == ERR)
1066 return got_error_from_errno("replace_panel");
1067 wclear(view->window);
1069 view->nlines = nlines;
1070 view->ncols = ncols;
1071 view->lines = LINES;
1072 view->cols = COLS;
1074 return NULL;
1077 static const struct got_error *
1078 resize_log_view(struct tog_view *view, int increase)
1080 struct tog_log_view_state *s = &view->state.log;
1081 const struct got_error *err = NULL;
1082 int n = 0;
1084 if (s->selected_entry)
1085 n = s->selected_entry->idx + view->lines - s->selected;
1088 * Request commits to account for the increased
1089 * height so we have enough to populate the view.
1091 if (s->commits->ncommits < n) {
1092 view->nscrolled = n - s->commits->ncommits + increase + 1;
1093 err = request_log_commits(view);
1096 return err;
1099 static void
1100 view_adjust_offset(struct tog_view *view, int n)
1102 if (n == 0)
1103 return;
1105 if (view->parent && view->parent->offset) {
1106 if (view->parent->offset + n >= 0)
1107 view->parent->offset += n;
1108 else
1109 view->parent->offset = 0;
1110 } else if (view->offset) {
1111 if (view->offset - n >= 0)
1112 view->offset -= n;
1113 else
1114 view->offset = 0;
1118 static const struct got_error *
1119 view_resize_split(struct tog_view *view, int resize)
1121 const struct got_error *err = NULL;
1122 struct tog_view *v = NULL;
1124 if (view->parent)
1125 v = view->parent;
1126 else
1127 v = view;
1129 if (!v->child || !view_is_splitscreen(v->child))
1130 return NULL;
1132 v->resized = v->child->resized = resize; /* lock for resize event */
1134 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1135 if (v->child->resized_y)
1136 v->child->begin_y = v->child->resized_y;
1137 if (view->parent)
1138 v->child->begin_y -= resize;
1139 else
1140 v->child->begin_y += resize;
1141 if (v->child->begin_y < 3) {
1142 view->count = 0;
1143 v->child->begin_y = 3;
1144 } else if (v->child->begin_y > LINES - 1) {
1145 view->count = 0;
1146 v->child->begin_y = LINES - 1;
1148 v->ncols = COLS;
1149 v->child->ncols = COLS;
1150 view_adjust_offset(view, resize);
1151 err = view_init_hsplit(v, v->child->begin_y);
1152 if (err)
1153 return err;
1154 v->child->resized_y = v->child->begin_y;
1155 } else {
1156 if (v->child->resized_x)
1157 v->child->begin_x = v->child->resized_x;
1158 if (view->parent)
1159 v->child->begin_x -= resize;
1160 else
1161 v->child->begin_x += resize;
1162 if (v->child->begin_x < 11) {
1163 view->count = 0;
1164 v->child->begin_x = 11;
1165 } else if (v->child->begin_x > COLS - 1) {
1166 view->count = 0;
1167 v->child->begin_x = COLS - 1;
1169 v->child->resized_x = v->child->begin_x;
1172 v->child->mode = v->mode;
1173 v->child->nlines = v->lines - v->child->begin_y;
1174 v->child->ncols = v->cols - v->child->begin_x;
1175 v->focus_child = 1;
1177 err = view_fullscreen(v);
1178 if (err)
1179 return err;
1180 err = view_splitscreen(v->child);
1181 if (err)
1182 return err;
1184 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1185 err = offset_selection_down(v->child);
1186 if (err)
1187 return err;
1190 if (v->resize)
1191 err = v->resize(v, 0);
1192 else if (v->child->resize)
1193 err = v->child->resize(v->child, 0);
1195 v->resized = v->child->resized = 0;
1197 return err;
1200 static void
1201 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1203 struct tog_view *v = src->child ? src->child : src;
1205 dst->resized_x = v->resized_x;
1206 dst->resized_y = v->resized_y;
1209 static const struct got_error *
1210 view_close_child(struct tog_view *view)
1212 const struct got_error *err = NULL;
1214 if (view->child == NULL)
1215 return NULL;
1217 err = view_close(view->child);
1218 view->child = NULL;
1219 return err;
1222 static const struct got_error *
1223 view_set_child(struct tog_view *view, struct tog_view *child)
1225 const struct got_error *err = NULL;
1227 view->child = child;
1228 child->parent = view;
1230 err = view_resize(view);
1231 if (err)
1232 return err;
1234 if (view->child->resized_x || view->child->resized_y)
1235 err = view_resize_split(view, 0);
1237 return err;
1240 static const struct got_error *view_dispatch_request(struct tog_view **,
1241 struct tog_view *, enum tog_view_type, int, int);
1243 static const struct got_error *
1244 view_request_new(struct tog_view **requested, struct tog_view *view,
1245 enum tog_view_type request)
1247 struct tog_view *new_view = NULL;
1248 const struct got_error *err;
1249 int y = 0, x = 0;
1251 *requested = NULL;
1253 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1254 view_get_split(view, &y, &x);
1256 err = view_dispatch_request(&new_view, view, request, y, x);
1257 if (err)
1258 return err;
1260 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1261 request != TOG_VIEW_HELP) {
1262 err = view_init_hsplit(view, y);
1263 if (err)
1264 return err;
1267 view->focussed = 0;
1268 new_view->focussed = 1;
1269 new_view->mode = view->mode;
1270 new_view->nlines = request == TOG_VIEW_HELP ?
1271 view->lines : view->lines - y;
1273 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1274 view_transfer_size(new_view, view);
1275 err = view_close_child(view);
1276 if (err)
1277 return err;
1278 err = view_set_child(view, new_view);
1279 if (err)
1280 return err;
1281 view->focus_child = 1;
1282 } else
1283 *requested = new_view;
1285 return NULL;
1288 static void
1289 tog_resizeterm(void)
1291 int cols, lines;
1292 struct winsize size;
1294 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1295 cols = 80; /* Default */
1296 lines = 24;
1297 } else {
1298 cols = size.ws_col;
1299 lines = size.ws_row;
1301 resize_term(lines, cols);
1304 static const struct got_error *
1305 view_search_start(struct tog_view *view, int fast_refresh)
1307 const struct got_error *err = NULL;
1308 struct tog_view *v = view;
1309 char pattern[1024];
1310 int ret;
1312 if (view->search_started) {
1313 regfree(&view->regex);
1314 view->searching = 0;
1315 memset(&view->regmatch, 0, sizeof(view->regmatch));
1317 view->search_started = 0;
1319 if (view->nlines < 1)
1320 return NULL;
1322 if (view_is_hsplit_top(view))
1323 v = view->child;
1324 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1325 v = view->parent;
1327 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1328 wclrtoeol(v->window);
1330 nodelay(v->window, FALSE); /* block for search term input */
1331 nocbreak();
1332 echo();
1333 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1334 wrefresh(v->window);
1335 cbreak();
1336 noecho();
1337 nodelay(v->window, TRUE);
1338 if (!fast_refresh && !using_mock_io)
1339 halfdelay(10);
1340 if (ret == ERR)
1341 return NULL;
1343 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1344 err = view->search_start(view);
1345 if (err) {
1346 regfree(&view->regex);
1347 return err;
1349 view->search_started = 1;
1350 view->searching = TOG_SEARCH_FORWARD;
1351 view->search_next_done = 0;
1352 view->search_next(view);
1355 return NULL;
1358 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1359 static const struct got_error *
1360 switch_split(struct tog_view *view)
1362 const struct got_error *err = NULL;
1363 struct tog_view *v = NULL;
1365 if (view->parent)
1366 v = view->parent;
1367 else
1368 v = view;
1370 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1371 v->mode = TOG_VIEW_SPLIT_VERT;
1372 else
1373 v->mode = TOG_VIEW_SPLIT_HRZN;
1375 if (!v->child)
1376 return NULL;
1377 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1378 v->mode = TOG_VIEW_SPLIT_NONE;
1380 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1381 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1382 v->child->begin_y = v->child->resized_y;
1383 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1384 v->child->begin_x = v->child->resized_x;
1387 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1388 v->ncols = COLS;
1389 v->child->ncols = COLS;
1390 v->child->nscrolled = LINES - v->child->nlines;
1392 err = view_init_hsplit(v, v->child->begin_y);
1393 if (err)
1394 return err;
1396 v->child->mode = v->mode;
1397 v->child->nlines = v->lines - v->child->begin_y;
1398 v->focus_child = 1;
1400 err = view_fullscreen(v);
1401 if (err)
1402 return err;
1403 err = view_splitscreen(v->child);
1404 if (err)
1405 return err;
1407 if (v->mode == TOG_VIEW_SPLIT_NONE)
1408 v->mode = TOG_VIEW_SPLIT_VERT;
1409 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1410 err = offset_selection_down(v);
1411 if (err)
1412 return err;
1413 err = offset_selection_down(v->child);
1414 if (err)
1415 return err;
1416 } else {
1417 offset_selection_up(v);
1418 offset_selection_up(v->child);
1420 if (v->resize)
1421 err = v->resize(v, 0);
1422 else if (v->child->resize)
1423 err = v->child->resize(v->child, 0);
1425 return err;
1429 * Strip trailing whitespace from str starting at byte *n;
1430 * if *n < 0, use strlen(str). Return new str length in *n.
1432 static void
1433 strip_trailing_ws(char *str, int *n)
1435 size_t x = *n;
1437 if (str == NULL || *str == '\0')
1438 return;
1440 if (x < 0)
1441 x = strlen(str);
1443 while (x-- > 0 && isspace((unsigned char)str[x]))
1444 str[x] = '\0';
1446 *n = x + 1;
1450 * Extract visible substring of line y from the curses screen
1451 * and strip trailing whitespace. If vline is set, overwrite
1452 * line[vline] with '|' because the ACS_VLINE character is
1453 * written out as 'x'. Write the line to file f.
1455 static const struct got_error *
1456 view_write_line(FILE *f, int y, int vline)
1458 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1459 int r, w;
1461 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1462 if (r == ERR)
1463 return got_error_fmt(GOT_ERR_RANGE,
1464 "failed to extract line %d", y);
1467 * In some views, lines are padded with blanks to COLS width.
1468 * Strip them so we can diff without the -b flag when testing.
1470 strip_trailing_ws(line, &r);
1472 if (vline > 0)
1473 line[vline] = '|';
1475 w = fprintf(f, "%s\n", line);
1476 if (w != r + 1) /* \n */
1477 return got_ferror(f, GOT_ERR_IO);
1479 return NULL;
1483 * Capture the visible curses screen by writing each line to the
1484 * file at the path set via the TOG_SCR_DUMP environment variable.
1486 static const struct got_error *
1487 screendump(struct tog_view *view)
1489 const struct got_error *err;
1490 int i;
1492 err = got_opentemp_truncate(tog_io.sdump);
1493 if (err)
1494 return err;
1496 if ((view->child && view->child->begin_x) ||
1497 (view->parent && view->begin_x)) {
1498 int ncols = view->child ? view->ncols : view->parent->ncols;
1500 /* vertical splitscreen */
1501 for (i = 0; i < view->nlines; ++i) {
1502 err = view_write_line(tog_io.sdump, i, ncols - 1);
1503 if (err)
1504 goto done;
1506 } else {
1507 int hline = 0;
1509 /* fullscreen or horizontal splitscreen */
1510 if ((view->child && view->child->begin_y) ||
1511 (view->parent && view->begin_y)) /* hsplit */
1512 hline = view->child ?
1513 view->child->begin_y : view->begin_y;
1515 for (i = 0; i < view->lines; i++) {
1516 if (hline && i == hline - 1) {
1517 int c;
1519 /* ACS_HLINE writes out as 'q', overwrite it */
1520 for (c = 0; c < view->cols; ++c)
1521 fputc('-', tog_io.sdump);
1522 fputc('\n', tog_io.sdump);
1523 continue;
1526 err = view_write_line(tog_io.sdump, i, 0);
1527 if (err)
1528 goto done;
1532 done:
1533 return err;
1537 * Compute view->count from numeric input. Assign total to view->count and
1538 * return first non-numeric key entered.
1540 static int
1541 get_compound_key(struct tog_view *view, int c)
1543 struct tog_view *v = view;
1544 int x, n = 0;
1546 if (view_is_hsplit_top(view))
1547 v = view->child;
1548 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1549 v = view->parent;
1551 view->count = 0;
1552 cbreak(); /* block for input */
1553 nodelay(view->window, FALSE);
1554 wmove(v->window, v->nlines - 1, 0);
1555 wclrtoeol(v->window);
1556 waddch(v->window, ':');
1558 do {
1559 x = getcurx(v->window);
1560 if (x != ERR && x < view->ncols) {
1561 waddch(v->window, c);
1562 wrefresh(v->window);
1566 * Don't overflow. Max valid request should be the greatest
1567 * between the longest and total lines; cap at 10 million.
1569 if (n >= 9999999)
1570 n = 9999999;
1571 else
1572 n = n * 10 + (c - '0');
1573 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1575 if (c == 'G' || c == 'g') { /* nG key map */
1576 view->gline = view->hiline = n;
1577 n = 0;
1578 c = 0;
1581 /* Massage excessive or inapplicable values at the input handler. */
1582 view->count = n;
1584 return c;
1587 static void
1588 action_report(struct tog_view *view)
1590 struct tog_view *v = view;
1592 if (view_is_hsplit_top(view))
1593 v = view->child;
1594 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1595 v = view->parent;
1597 wmove(v->window, v->nlines - 1, 0);
1598 wclrtoeol(v->window);
1599 wprintw(v->window, ":%s", view->action);
1600 wrefresh(v->window);
1603 * Clear action status report. Only clear in blame view
1604 * once annotating is complete, otherwise it's too fast.
1606 if (view->type == TOG_VIEW_BLAME) {
1607 if (view->state.blame.blame_complete)
1608 view->action = NULL;
1609 } else
1610 view->action = NULL;
1614 * Read the next line from the test script and assign
1615 * key instruction to *ch. If at EOF, set the *done flag.
1617 static const struct got_error *
1618 tog_read_script_key(FILE *script, struct tog_view *view, int *ch, int *done)
1620 const struct got_error *err = NULL;
1621 char *line = NULL;
1622 size_t linesz = 0;
1624 if (view->count && --view->count) {
1625 *ch = view->ch;
1626 return NULL;
1627 } else
1628 *ch = -1;
1630 if (getline(&line, &linesz, script) == -1) {
1631 if (feof(script)) {
1632 *done = 1;
1633 goto done;
1634 } else {
1635 err = got_ferror(script, GOT_ERR_IO);
1636 goto done;
1640 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1641 tog_io.wait_for_ui = 1;
1642 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1643 *ch = KEY_ENTER;
1644 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1645 *ch = KEY_RIGHT;
1646 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1647 *ch = KEY_LEFT;
1648 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1649 *ch = KEY_DOWN;
1650 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1651 *ch = KEY_UP;
1652 else if (strncasecmp(line, "TAB", 3) == 0)
1653 *ch = '\t';
1654 else if (strncasecmp(line, "SCREENDUMP", 10) == 0)
1655 *ch = TOG_KEY_SCRDUMP;
1656 else if (isdigit((unsigned char)*line)) {
1657 char *t = line;
1659 while (isdigit((unsigned char)*t))
1660 ++t;
1661 view->ch = *ch = *t;
1662 *t = '\0';
1663 /* ignore error, view->count is 0 if instruction is invalid */
1664 view->count = strtonum(line, 0, INT_MAX, NULL);
1665 } else
1666 *ch = *line;
1668 done:
1669 free(line);
1670 return err;
1673 static const struct got_error *
1674 view_input(struct tog_view **new, int *done, struct tog_view *view,
1675 struct tog_view_list_head *views, int fast_refresh)
1677 const struct got_error *err = NULL;
1678 struct tog_view *v;
1679 int ch, errcode;
1681 *new = NULL;
1683 if (view->action)
1684 action_report(view);
1686 /* Clear "no matches" indicator. */
1687 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1688 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1689 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1690 view->count = 0;
1693 if (view->searching && !view->search_next_done) {
1694 errcode = pthread_mutex_unlock(&tog_mutex);
1695 if (errcode)
1696 return got_error_set_errno(errcode,
1697 "pthread_mutex_unlock");
1698 sched_yield();
1699 errcode = pthread_mutex_lock(&tog_mutex);
1700 if (errcode)
1701 return got_error_set_errno(errcode,
1702 "pthread_mutex_lock");
1703 view->search_next(view);
1704 return NULL;
1707 /* Allow threads to make progress while we are waiting for input. */
1708 errcode = pthread_mutex_unlock(&tog_mutex);
1709 if (errcode)
1710 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1712 if (using_mock_io) {
1713 err = tog_read_script_key(tog_io.f, view, &ch, done);
1714 if (err) {
1715 errcode = pthread_mutex_lock(&tog_mutex);
1716 return err;
1718 } else if (view->count && --view->count) {
1719 cbreak();
1720 nodelay(view->window, TRUE);
1721 ch = wgetch(view->window);
1722 /* let C-g or backspace abort unfinished count */
1723 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1724 view->count = 0;
1725 else
1726 ch = view->ch;
1727 } else {
1728 ch = wgetch(view->window);
1729 if (ch >= '1' && ch <= '9')
1730 view->ch = ch = get_compound_key(view, ch);
1732 if (view->hiline && ch != ERR && ch != 0)
1733 view->hiline = 0; /* key pressed, clear line highlight */
1734 nodelay(view->window, TRUE);
1735 errcode = pthread_mutex_lock(&tog_mutex);
1736 if (errcode)
1737 return got_error_set_errno(errcode, "pthread_mutex_lock");
1739 if (tog_sigwinch_received || tog_sigcont_received) {
1740 tog_resizeterm();
1741 tog_sigwinch_received = 0;
1742 tog_sigcont_received = 0;
1743 TAILQ_FOREACH(v, views, entry) {
1744 err = view_resize(v);
1745 if (err)
1746 return err;
1747 err = v->input(new, v, KEY_RESIZE);
1748 if (err)
1749 return err;
1750 if (v->child) {
1751 err = view_resize(v->child);
1752 if (err)
1753 return err;
1754 err = v->child->input(new, v->child,
1755 KEY_RESIZE);
1756 if (err)
1757 return err;
1758 if (v->child->resized_x || v->child->resized_y) {
1759 err = view_resize_split(v, 0);
1760 if (err)
1761 return err;
1767 switch (ch) {
1768 case '?':
1769 case 'H':
1770 case KEY_F(1):
1771 if (view->type == TOG_VIEW_HELP)
1772 err = view->reset(view);
1773 else
1774 err = view_request_new(new, view, TOG_VIEW_HELP);
1775 break;
1776 case '\t':
1777 view->count = 0;
1778 if (view->child) {
1779 view->focussed = 0;
1780 view->child->focussed = 1;
1781 view->focus_child = 1;
1782 } else if (view->parent) {
1783 view->focussed = 0;
1784 view->parent->focussed = 1;
1785 view->parent->focus_child = 0;
1786 if (!view_is_splitscreen(view)) {
1787 if (view->parent->resize) {
1788 err = view->parent->resize(view->parent,
1789 0);
1790 if (err)
1791 return err;
1793 offset_selection_up(view->parent);
1794 err = view_fullscreen(view->parent);
1795 if (err)
1796 return err;
1799 break;
1800 case 'q':
1801 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1802 if (view->parent->resize) {
1803 /* might need more commits to fill fullscreen */
1804 err = view->parent->resize(view->parent, 0);
1805 if (err)
1806 break;
1808 offset_selection_up(view->parent);
1810 err = view->input(new, view, ch);
1811 view->dying = 1;
1812 break;
1813 case 'Q':
1814 *done = 1;
1815 break;
1816 case 'F':
1817 view->count = 0;
1818 if (view_is_parent_view(view)) {
1819 if (view->child == NULL)
1820 break;
1821 if (view_is_splitscreen(view->child)) {
1822 view->focussed = 0;
1823 view->child->focussed = 1;
1824 err = view_fullscreen(view->child);
1825 } else {
1826 err = view_splitscreen(view->child);
1827 if (!err)
1828 err = view_resize_split(view, 0);
1830 if (err)
1831 break;
1832 err = view->child->input(new, view->child,
1833 KEY_RESIZE);
1834 } else {
1835 if (view_is_splitscreen(view)) {
1836 view->parent->focussed = 0;
1837 view->focussed = 1;
1838 err = view_fullscreen(view);
1839 } else {
1840 err = view_splitscreen(view);
1841 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1842 err = view_resize(view->parent);
1843 if (!err)
1844 err = view_resize_split(view, 0);
1846 if (err)
1847 break;
1848 err = view->input(new, view, KEY_RESIZE);
1850 if (err)
1851 break;
1852 if (view->resize) {
1853 err = view->resize(view, 0);
1854 if (err)
1855 break;
1857 if (view->parent) {
1858 if (view->parent->resize) {
1859 err = view->parent->resize(view->parent, 0);
1860 if (err != NULL)
1861 break;
1863 err = offset_selection_down(view->parent);
1864 if (err != NULL)
1865 break;
1867 err = offset_selection_down(view);
1868 break;
1869 case 'S':
1870 view->count = 0;
1871 err = switch_split(view);
1872 break;
1873 case '-':
1874 err = view_resize_split(view, -1);
1875 break;
1876 case '+':
1877 err = view_resize_split(view, 1);
1878 break;
1879 case KEY_RESIZE:
1880 break;
1881 case '/':
1882 view->count = 0;
1883 if (view->search_start)
1884 view_search_start(view, fast_refresh);
1885 else
1886 err = view->input(new, view, ch);
1887 break;
1888 case 'N':
1889 case 'n':
1890 if (view->search_started && view->search_next) {
1891 view->searching = (ch == 'n' ?
1892 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1893 view->search_next_done = 0;
1894 view->search_next(view);
1895 } else
1896 err = view->input(new, view, ch);
1897 break;
1898 case 'A':
1899 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1900 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1901 view->action = "Patience diff algorithm";
1902 } else {
1903 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1904 view->action = "Myers diff algorithm";
1906 TAILQ_FOREACH(v, views, entry) {
1907 if (v->reset) {
1908 err = v->reset(v);
1909 if (err)
1910 return err;
1912 if (v->child && v->child->reset) {
1913 err = v->child->reset(v->child);
1914 if (err)
1915 return err;
1918 break;
1919 case TOG_KEY_SCRDUMP:
1920 err = screendump(view);
1921 break;
1922 default:
1923 err = view->input(new, view, ch);
1924 break;
1927 return err;
1930 static int
1931 view_needs_focus_indication(struct tog_view *view)
1933 if (view_is_parent_view(view)) {
1934 if (view->child == NULL || view->child->focussed)
1935 return 0;
1936 if (!view_is_splitscreen(view->child))
1937 return 0;
1938 } else if (!view_is_splitscreen(view))
1939 return 0;
1941 return view->focussed;
1944 static const struct got_error *
1945 tog_io_close(void)
1947 const struct got_error *err = NULL;
1949 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1950 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1951 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1952 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1953 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1954 err = got_ferror(tog_io.f, GOT_ERR_IO);
1955 if (tog_io.sdump && fclose(tog_io.sdump) == EOF && err == NULL)
1956 err = got_ferror(tog_io.sdump, GOT_ERR_IO);
1958 return err;
1961 static const struct got_error *
1962 view_loop(struct tog_view *view)
1964 const struct got_error *err = NULL;
1965 struct tog_view_list_head views;
1966 struct tog_view *new_view;
1967 char *mode;
1968 int fast_refresh = 10;
1969 int done = 0, errcode;
1971 mode = getenv("TOG_VIEW_SPLIT_MODE");
1972 if (!mode || !(*mode == 'h' || *mode == 'H'))
1973 view->mode = TOG_VIEW_SPLIT_VERT;
1974 else
1975 view->mode = TOG_VIEW_SPLIT_HRZN;
1977 errcode = pthread_mutex_lock(&tog_mutex);
1978 if (errcode)
1979 return got_error_set_errno(errcode, "pthread_mutex_lock");
1981 TAILQ_INIT(&views);
1982 TAILQ_INSERT_HEAD(&views, view, entry);
1984 view->focussed = 1;
1985 err = view->show(view);
1986 if (err)
1987 return err;
1988 update_panels();
1989 doupdate();
1990 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1991 !tog_fatal_signal_received()) {
1992 /* Refresh fast during initialization, then become slower. */
1993 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
1994 halfdelay(10); /* switch to once per second */
1996 err = view_input(&new_view, &done, view, &views, fast_refresh);
1997 if (err)
1998 break;
2000 if (view->dying && view == TAILQ_FIRST(&views) &&
2001 TAILQ_NEXT(view, entry) == NULL)
2002 done = 1;
2003 if (done) {
2004 struct tog_view *v;
2007 * When we quit, scroll the screen up a single line
2008 * so we don't lose any information.
2010 TAILQ_FOREACH(v, &views, entry) {
2011 wmove(v->window, 0, 0);
2012 wdeleteln(v->window);
2013 wnoutrefresh(v->window);
2014 if (v->child && !view_is_fullscreen(v)) {
2015 wmove(v->child->window, 0, 0);
2016 wdeleteln(v->child->window);
2017 wnoutrefresh(v->child->window);
2020 doupdate();
2023 if (view->dying) {
2024 struct tog_view *v, *prev = NULL;
2026 if (view_is_parent_view(view))
2027 prev = TAILQ_PREV(view, tog_view_list_head,
2028 entry);
2029 else if (view->parent)
2030 prev = view->parent;
2032 if (view->parent) {
2033 view->parent->child = NULL;
2034 view->parent->focus_child = 0;
2035 /* Restore fullscreen line height. */
2036 view->parent->nlines = view->parent->lines;
2037 err = view_resize(view->parent);
2038 if (err)
2039 break;
2040 /* Make resized splits persist. */
2041 view_transfer_size(view->parent, view);
2042 } else
2043 TAILQ_REMOVE(&views, view, entry);
2045 err = view_close(view);
2046 if (err)
2047 goto done;
2049 view = NULL;
2050 TAILQ_FOREACH(v, &views, entry) {
2051 if (v->focussed)
2052 break;
2054 if (view == NULL && new_view == NULL) {
2055 /* No view has focus. Try to pick one. */
2056 if (prev)
2057 view = prev;
2058 else if (!TAILQ_EMPTY(&views)) {
2059 view = TAILQ_LAST(&views,
2060 tog_view_list_head);
2062 if (view) {
2063 if (view->focus_child) {
2064 view->child->focussed = 1;
2065 view = view->child;
2066 } else
2067 view->focussed = 1;
2071 if (new_view) {
2072 struct tog_view *v, *t;
2073 /* Only allow one parent view per type. */
2074 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2075 if (v->type != new_view->type)
2076 continue;
2077 TAILQ_REMOVE(&views, v, entry);
2078 err = view_close(v);
2079 if (err)
2080 goto done;
2081 break;
2083 TAILQ_INSERT_TAIL(&views, new_view, entry);
2084 view = new_view;
2086 if (view && !done) {
2087 if (view_is_parent_view(view)) {
2088 if (view->child && view->child->focussed)
2089 view = view->child;
2090 } else {
2091 if (view->parent && view->parent->focussed)
2092 view = view->parent;
2094 show_panel(view->panel);
2095 if (view->child && view_is_splitscreen(view->child))
2096 show_panel(view->child->panel);
2097 if (view->parent && view_is_splitscreen(view)) {
2098 err = view->parent->show(view->parent);
2099 if (err)
2100 goto done;
2102 err = view->show(view);
2103 if (err)
2104 goto done;
2105 if (view->child) {
2106 err = view->child->show(view->child);
2107 if (err)
2108 goto done;
2110 update_panels();
2111 doupdate();
2114 done:
2115 while (!TAILQ_EMPTY(&views)) {
2116 const struct got_error *close_err;
2117 view = TAILQ_FIRST(&views);
2118 TAILQ_REMOVE(&views, view, entry);
2119 close_err = view_close(view);
2120 if (close_err && err == NULL)
2121 err = close_err;
2124 errcode = pthread_mutex_unlock(&tog_mutex);
2125 if (errcode && err == NULL)
2126 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2128 return err;
2131 __dead static void
2132 usage_log(void)
2134 endwin();
2135 fprintf(stderr,
2136 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2137 getprogname());
2138 exit(1);
2141 /* Create newly allocated wide-character string equivalent to a byte string. */
2142 static const struct got_error *
2143 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2145 char *vis = NULL;
2146 const struct got_error *err = NULL;
2148 *ws = NULL;
2149 *wlen = mbstowcs(NULL, s, 0);
2150 if (*wlen == (size_t)-1) {
2151 int vislen;
2152 if (errno != EILSEQ)
2153 return got_error_from_errno("mbstowcs");
2155 /* byte string invalid in current encoding; try to "fix" it */
2156 err = got_mbsavis(&vis, &vislen, s);
2157 if (err)
2158 return err;
2159 *wlen = mbstowcs(NULL, vis, 0);
2160 if (*wlen == (size_t)-1) {
2161 err = got_error_from_errno("mbstowcs"); /* give up */
2162 goto done;
2166 *ws = calloc(*wlen + 1, sizeof(**ws));
2167 if (*ws == NULL) {
2168 err = got_error_from_errno("calloc");
2169 goto done;
2172 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2173 err = got_error_from_errno("mbstowcs");
2174 done:
2175 free(vis);
2176 if (err) {
2177 free(*ws);
2178 *ws = NULL;
2179 *wlen = 0;
2181 return err;
2184 static const struct got_error *
2185 expand_tab(char **ptr, const char *src)
2187 char *dst;
2188 size_t len, n, idx = 0, sz = 0;
2190 *ptr = NULL;
2191 n = len = strlen(src);
2192 dst = malloc(n + 1);
2193 if (dst == NULL)
2194 return got_error_from_errno("malloc");
2196 while (idx < len && src[idx]) {
2197 const char c = src[idx];
2199 if (c == '\t') {
2200 size_t nb = TABSIZE - sz % TABSIZE;
2201 char *p;
2203 p = realloc(dst, n + nb);
2204 if (p == NULL) {
2205 free(dst);
2206 return got_error_from_errno("realloc");
2209 dst = p;
2210 n += nb;
2211 memset(dst + sz, ' ', nb);
2212 sz += nb;
2213 } else
2214 dst[sz++] = src[idx];
2215 ++idx;
2218 dst[sz] = '\0';
2219 *ptr = dst;
2220 return NULL;
2224 * Advance at most n columns from wline starting at offset off.
2225 * Return the index to the first character after the span operation.
2226 * Return the combined column width of all spanned wide characters in
2227 * *rcol.
2229 static int
2230 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2232 int width, i, cols = 0;
2234 if (n == 0) {
2235 *rcol = cols;
2236 return off;
2239 for (i = off; wline[i] != L'\0'; ++i) {
2240 if (wline[i] == L'\t')
2241 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2242 else
2243 width = wcwidth(wline[i]);
2245 if (width == -1) {
2246 width = 1;
2247 wline[i] = L'.';
2250 if (cols + width > n)
2251 break;
2252 cols += width;
2255 *rcol = cols;
2256 return i;
2260 * Format a line for display, ensuring that it won't overflow a width limit.
2261 * With scrolling, the width returned refers to the scrolled version of the
2262 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2264 static const struct got_error *
2265 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2266 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2268 const struct got_error *err = NULL;
2269 int cols;
2270 wchar_t *wline = NULL;
2271 char *exstr = NULL;
2272 size_t wlen;
2273 int i, scrollx;
2275 *wlinep = NULL;
2276 *widthp = 0;
2278 if (expand) {
2279 err = expand_tab(&exstr, line);
2280 if (err)
2281 return err;
2284 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2285 free(exstr);
2286 if (err)
2287 return err;
2289 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2291 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2292 wline[wlen - 1] = L'\0';
2293 wlen--;
2295 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2296 wline[wlen - 1] = L'\0';
2297 wlen--;
2300 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2301 wline[i] = L'\0';
2303 if (widthp)
2304 *widthp = cols;
2305 if (scrollxp)
2306 *scrollxp = scrollx;
2307 if (err)
2308 free(wline);
2309 else
2310 *wlinep = wline;
2311 return err;
2314 static const struct got_error*
2315 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2316 struct got_object_id *id, struct got_repository *repo)
2318 static const struct got_error *err = NULL;
2319 struct got_reflist_entry *re;
2320 char *s;
2321 const char *name;
2323 *refs_str = NULL;
2325 if (refs == NULL)
2326 return NULL;
2328 TAILQ_FOREACH(re, refs, entry) {
2329 struct got_tag_object *tag = NULL;
2330 struct got_object_id *ref_id;
2331 int cmp;
2333 name = got_ref_get_name(re->ref);
2334 if (strcmp(name, GOT_REF_HEAD) == 0)
2335 continue;
2336 if (strncmp(name, "refs/", 5) == 0)
2337 name += 5;
2338 if (strncmp(name, "got/", 4) == 0)
2339 continue;
2340 if (strncmp(name, "heads/", 6) == 0)
2341 name += 6;
2342 if (strncmp(name, "remotes/", 8) == 0) {
2343 name += 8;
2344 s = strstr(name, "/" GOT_REF_HEAD);
2345 if (s != NULL && s[strlen(s)] == '\0')
2346 continue;
2348 err = got_ref_resolve(&ref_id, repo, re->ref);
2349 if (err)
2350 break;
2351 if (strncmp(name, "tags/", 5) == 0) {
2352 err = got_object_open_as_tag(&tag, repo, ref_id);
2353 if (err) {
2354 if (err->code != GOT_ERR_OBJ_TYPE) {
2355 free(ref_id);
2356 break;
2358 /* Ref points at something other than a tag. */
2359 err = NULL;
2360 tag = NULL;
2363 cmp = got_object_id_cmp(tag ?
2364 got_object_tag_get_object_id(tag) : ref_id, id);
2365 free(ref_id);
2366 if (tag)
2367 got_object_tag_close(tag);
2368 if (cmp != 0)
2369 continue;
2370 s = *refs_str;
2371 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2372 s ? ", " : "", name) == -1) {
2373 err = got_error_from_errno("asprintf");
2374 free(s);
2375 *refs_str = NULL;
2376 break;
2378 free(s);
2381 return err;
2384 static const struct got_error *
2385 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2386 int col_tab_align)
2388 char *smallerthan;
2390 smallerthan = strchr(author, '<');
2391 if (smallerthan && smallerthan[1] != '\0')
2392 author = smallerthan + 1;
2393 author[strcspn(author, "@>")] = '\0';
2394 return format_line(wauthor, author_width, NULL, author, 0, limit,
2395 col_tab_align, 0);
2398 static const struct got_error *
2399 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2400 struct got_object_id *id, const size_t date_display_cols,
2401 int author_display_cols)
2403 struct tog_log_view_state *s = &view->state.log;
2404 const struct got_error *err = NULL;
2405 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2406 char *refs_str = NULL;
2407 char *logmsg0 = NULL, *logmsg = NULL;
2408 char *author = NULL;
2409 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2410 int author_width, logmsg_width;
2411 size_t wrefstr_len = 0;
2412 char *newline, *line = NULL;
2413 int col, limit, scrollx;
2414 const int avail = view->ncols;
2415 struct tm tm;
2416 time_t committer_time;
2417 struct tog_color *tc;
2418 struct got_reflist_head *refs;
2420 committer_time = got_object_commit_get_committer_time(commit);
2421 if (gmtime_r(&committer_time, &tm) == NULL)
2422 return got_error_from_errno("gmtime_r");
2423 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2424 return got_error(GOT_ERR_NO_SPACE);
2426 if (avail <= date_display_cols)
2427 limit = MIN(sizeof(datebuf) - 1, avail);
2428 else
2429 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2430 tc = get_color(&s->colors, TOG_COLOR_DATE);
2431 if (tc)
2432 wattr_on(view->window,
2433 COLOR_PAIR(tc->colorpair), NULL);
2434 waddnstr(view->window, datebuf, limit);
2435 if (tc)
2436 wattr_off(view->window,
2437 COLOR_PAIR(tc->colorpair), NULL);
2438 col = limit;
2439 if (col > avail)
2440 goto done;
2442 if (avail >= 120) {
2443 char *id_str;
2444 err = got_object_id_str(&id_str, id);
2445 if (err)
2446 goto done;
2447 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2448 if (tc)
2449 wattr_on(view->window,
2450 COLOR_PAIR(tc->colorpair), NULL);
2451 wprintw(view->window, "%.8s ", id_str);
2452 if (tc)
2453 wattr_off(view->window,
2454 COLOR_PAIR(tc->colorpair), NULL);
2455 free(id_str);
2456 col += 9;
2457 if (col > avail)
2458 goto done;
2461 if (s->use_committer)
2462 author = strdup(got_object_commit_get_committer(commit));
2463 else
2464 author = strdup(got_object_commit_get_author(commit));
2465 if (author == NULL) {
2466 err = got_error_from_errno("strdup");
2467 goto done;
2469 err = format_author(&wauthor, &author_width, author, avail - col, col);
2470 if (err)
2471 goto done;
2472 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2473 if (tc)
2474 wattr_on(view->window,
2475 COLOR_PAIR(tc->colorpair), NULL);
2476 waddwstr(view->window, wauthor);
2477 col += author_width;
2478 while (col < avail && author_width < author_display_cols + 2) {
2479 waddch(view->window, ' ');
2480 col++;
2481 author_width++;
2483 if (tc)
2484 wattr_off(view->window,
2485 COLOR_PAIR(tc->colorpair), NULL);
2486 if (col > avail)
2487 goto done;
2489 err = got_object_commit_get_logmsg(&logmsg0, commit);
2490 if (err)
2491 goto done;
2492 logmsg = logmsg0;
2493 while (*logmsg == '\n')
2494 logmsg++;
2495 newline = strchr(logmsg, '\n');
2496 if (newline)
2497 *newline = '\0';
2499 /* Prepend reference labels to log message if possible .*/
2500 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, id);
2501 err = build_refs_str(&refs_str, refs, id, s->repo);
2502 if (err)
2503 goto done;
2504 if (refs_str) {
2505 char *newlogmsg;
2506 wchar_t *ws;
2509 * The length of this wide-char sub-string will be
2510 * needed later for colorization.
2512 err = mbs2ws(&ws, &wrefstr_len, refs_str);
2513 if (err)
2514 goto done;
2515 free(ws);
2517 wrefstr_len += 2; /* account for '[' and ']' */
2519 if (asprintf(&newlogmsg, "[%s] %s", refs_str, logmsg) == -1) {
2520 err = got_error_from_errno("asprintf");
2521 goto done;
2524 free(logmsg0);
2525 logmsg0 = newlogmsg;
2526 logmsg = logmsg0;
2529 limit = avail - col;
2530 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2531 limit--; /* for the border */
2532 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2533 limit, col, 1);
2534 if (err)
2535 goto done;
2536 if (wrefstr_len > 0 && scrollx < wrefstr_len) {
2537 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2538 if (tc)
2539 wattr_on(view->window,
2540 COLOR_PAIR(tc->colorpair), NULL);
2541 waddnwstr(view->window, &wlogmsg[scrollx],
2542 MIN(logmsg_width, wrefstr_len - scrollx));
2543 if (tc)
2544 wattr_off(view->window,
2545 COLOR_PAIR(tc->colorpair), NULL);
2546 if (col + MIN(logmsg_width, wrefstr_len - scrollx) < avail)
2547 waddwstr(view->window, &wlogmsg[wrefstr_len]);
2548 } else
2549 waddwstr(view->window, &wlogmsg[scrollx]);
2550 col += MAX(logmsg_width, 0);
2551 while (col < avail) {
2552 waddch(view->window, ' ');
2553 col++;
2555 done:
2556 free(logmsg0);
2557 free(wlogmsg);
2558 free(refs_str);
2559 free(author);
2560 free(wauthor);
2561 free(line);
2562 return err;
2565 static struct commit_queue_entry *
2566 alloc_commit_queue_entry(struct got_commit_object *commit,
2567 struct got_object_id *id)
2569 struct commit_queue_entry *entry;
2570 struct got_object_id *dup;
2572 entry = calloc(1, sizeof(*entry));
2573 if (entry == NULL)
2574 return NULL;
2576 dup = got_object_id_dup(id);
2577 if (dup == NULL) {
2578 free(entry);
2579 return NULL;
2582 entry->id = dup;
2583 entry->commit = commit;
2584 return entry;
2587 static void
2588 pop_commit(struct commit_queue *commits)
2590 struct commit_queue_entry *entry;
2592 entry = TAILQ_FIRST(&commits->head);
2593 TAILQ_REMOVE(&commits->head, entry, entry);
2594 got_object_commit_close(entry->commit);
2595 commits->ncommits--;
2596 free(entry->id);
2597 free(entry);
2600 static void
2601 free_commits(struct commit_queue *commits)
2603 while (!TAILQ_EMPTY(&commits->head))
2604 pop_commit(commits);
2607 static const struct got_error *
2608 match_commit(int *have_match, struct got_object_id *id,
2609 struct got_commit_object *commit, regex_t *regex)
2611 const struct got_error *err = NULL;
2612 regmatch_t regmatch;
2613 char *id_str = NULL, *logmsg = NULL;
2615 *have_match = 0;
2617 err = got_object_id_str(&id_str, id);
2618 if (err)
2619 return err;
2621 err = got_object_commit_get_logmsg(&logmsg, commit);
2622 if (err)
2623 goto done;
2625 if (regexec(regex, got_object_commit_get_author(commit), 1,
2626 &regmatch, 0) == 0 ||
2627 regexec(regex, got_object_commit_get_committer(commit), 1,
2628 &regmatch, 0) == 0 ||
2629 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2630 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2631 *have_match = 1;
2632 done:
2633 free(id_str);
2634 free(logmsg);
2635 return err;
2638 static const struct got_error *
2639 queue_commits(struct tog_log_thread_args *a)
2641 const struct got_error *err = NULL;
2644 * We keep all commits open throughout the lifetime of the log
2645 * view in order to avoid having to re-fetch commits from disk
2646 * while updating the display.
2648 do {
2649 struct got_object_id id;
2650 struct got_commit_object *commit;
2651 struct commit_queue_entry *entry;
2652 int limit_match = 0;
2653 int errcode;
2655 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2656 NULL, NULL);
2657 if (err)
2658 break;
2660 err = got_object_open_as_commit(&commit, a->repo, &id);
2661 if (err)
2662 break;
2663 entry = alloc_commit_queue_entry(commit, &id);
2664 if (entry == NULL) {
2665 err = got_error_from_errno("alloc_commit_queue_entry");
2666 break;
2669 errcode = pthread_mutex_lock(&tog_mutex);
2670 if (errcode) {
2671 err = got_error_set_errno(errcode,
2672 "pthread_mutex_lock");
2673 break;
2676 entry->idx = a->real_commits->ncommits;
2677 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2678 a->real_commits->ncommits++;
2680 if (*a->limiting) {
2681 err = match_commit(&limit_match, &id, commit,
2682 a->limit_regex);
2683 if (err)
2684 break;
2686 if (limit_match) {
2687 struct commit_queue_entry *matched;
2689 matched = alloc_commit_queue_entry(
2690 entry->commit, entry->id);
2691 if (matched == NULL) {
2692 err = got_error_from_errno(
2693 "alloc_commit_queue_entry");
2694 break;
2696 matched->commit = entry->commit;
2697 got_object_commit_retain(entry->commit);
2699 matched->idx = a->limit_commits->ncommits;
2700 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2701 matched, entry);
2702 a->limit_commits->ncommits++;
2706 * This is how we signal log_thread() that we
2707 * have found a match, and that it should be
2708 * counted as a new entry for the view.
2710 a->limit_match = limit_match;
2713 if (*a->searching == TOG_SEARCH_FORWARD &&
2714 !*a->search_next_done) {
2715 int have_match;
2716 err = match_commit(&have_match, &id, commit, a->regex);
2717 if (err)
2718 break;
2720 if (*a->limiting) {
2721 if (limit_match && have_match)
2722 *a->search_next_done =
2723 TOG_SEARCH_HAVE_MORE;
2724 } else if (have_match)
2725 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2728 errcode = pthread_mutex_unlock(&tog_mutex);
2729 if (errcode && err == NULL)
2730 err = got_error_set_errno(errcode,
2731 "pthread_mutex_unlock");
2732 if (err)
2733 break;
2734 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2736 return err;
2739 static void
2740 select_commit(struct tog_log_view_state *s)
2742 struct commit_queue_entry *entry;
2743 int ncommits = 0;
2745 entry = s->first_displayed_entry;
2746 while (entry) {
2747 if (ncommits == s->selected) {
2748 s->selected_entry = entry;
2749 break;
2751 entry = TAILQ_NEXT(entry, entry);
2752 ncommits++;
2756 static const struct got_error *
2757 draw_commits(struct tog_view *view)
2759 const struct got_error *err = NULL;
2760 struct tog_log_view_state *s = &view->state.log;
2761 struct commit_queue_entry *entry = s->selected_entry;
2762 int limit = view->nlines;
2763 int width;
2764 int ncommits, author_cols = 4;
2765 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2766 char *refs_str = NULL;
2767 wchar_t *wline;
2768 struct tog_color *tc;
2769 static const size_t date_display_cols = 12;
2771 if (view_is_hsplit_top(view))
2772 --limit; /* account for border */
2774 if (s->selected_entry &&
2775 !(view->searching && view->search_next_done == 0)) {
2776 struct got_reflist_head *refs;
2777 err = got_object_id_str(&id_str, s->selected_entry->id);
2778 if (err)
2779 return err;
2780 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2781 s->selected_entry->id);
2782 err = build_refs_str(&refs_str, refs, s->selected_entry->id,
2783 s->repo);
2784 if (err)
2785 goto done;
2788 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2789 halfdelay(10); /* disable fast refresh */
2791 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2792 if (asprintf(&ncommits_str, " [%d/%d] %s",
2793 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2794 (view->searching && !view->search_next_done) ?
2795 "searching..." : "loading...") == -1) {
2796 err = got_error_from_errno("asprintf");
2797 goto done;
2799 } else {
2800 const char *search_str = NULL;
2801 const char *limit_str = NULL;
2803 if (view->searching) {
2804 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2805 search_str = "no more matches";
2806 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2807 search_str = "no matches found";
2808 else if (!view->search_next_done)
2809 search_str = "searching...";
2812 if (s->limit_view && s->commits->ncommits == 0)
2813 limit_str = "no matches found";
2815 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2816 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2817 search_str ? search_str : (refs_str ? refs_str : ""),
2818 limit_str ? limit_str : "") == -1) {
2819 err = got_error_from_errno("asprintf");
2820 goto done;
2824 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2825 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2826 "........................................",
2827 s->in_repo_path, ncommits_str) == -1) {
2828 err = got_error_from_errno("asprintf");
2829 header = NULL;
2830 goto done;
2832 } else if (asprintf(&header, "commit %s%s",
2833 id_str ? id_str : "........................................",
2834 ncommits_str) == -1) {
2835 err = got_error_from_errno("asprintf");
2836 header = NULL;
2837 goto done;
2839 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2840 if (err)
2841 goto done;
2843 werase(view->window);
2845 if (view_needs_focus_indication(view))
2846 wstandout(view->window);
2847 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2848 if (tc)
2849 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2850 waddwstr(view->window, wline);
2851 while (width < view->ncols) {
2852 waddch(view->window, ' ');
2853 width++;
2855 if (tc)
2856 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2857 if (view_needs_focus_indication(view))
2858 wstandend(view->window);
2859 free(wline);
2860 if (limit <= 1)
2861 goto done;
2863 /* Grow author column size if necessary, and set view->maxx. */
2864 entry = s->first_displayed_entry;
2865 ncommits = 0;
2866 view->maxx = 0;
2867 while (entry) {
2868 struct got_commit_object *c = entry->commit;
2869 char *author, *eol, *msg, *msg0;
2870 wchar_t *wauthor, *wmsg;
2871 int width;
2872 if (ncommits >= limit - 1)
2873 break;
2874 if (s->use_committer)
2875 author = strdup(got_object_commit_get_committer(c));
2876 else
2877 author = strdup(got_object_commit_get_author(c));
2878 if (author == NULL) {
2879 err = got_error_from_errno("strdup");
2880 goto done;
2882 err = format_author(&wauthor, &width, author, COLS,
2883 date_display_cols);
2884 if (author_cols < width)
2885 author_cols = width;
2886 free(wauthor);
2887 free(author);
2888 if (err)
2889 goto done;
2890 err = got_object_commit_get_logmsg(&msg0, c);
2891 if (err)
2892 goto done;
2893 msg = msg0;
2894 while (*msg == '\n')
2895 ++msg;
2896 if ((eol = strchr(msg, '\n')))
2897 *eol = '\0';
2898 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2899 date_display_cols + author_cols, 0);
2900 if (err)
2901 goto done;
2902 view->maxx = MAX(view->maxx, width);
2903 free(msg0);
2904 free(wmsg);
2905 ncommits++;
2906 entry = TAILQ_NEXT(entry, entry);
2909 entry = s->first_displayed_entry;
2910 s->last_displayed_entry = s->first_displayed_entry;
2911 ncommits = 0;
2912 while (entry) {
2913 if (ncommits >= limit - 1)
2914 break;
2915 if (ncommits == s->selected)
2916 wstandout(view->window);
2917 err = draw_commit(view, entry->commit, entry->id,
2918 date_display_cols, author_cols);
2919 if (ncommits == s->selected)
2920 wstandend(view->window);
2921 if (err)
2922 goto done;
2923 ncommits++;
2924 s->last_displayed_entry = entry;
2925 entry = TAILQ_NEXT(entry, entry);
2928 view_border(view);
2929 done:
2930 free(id_str);
2931 free(refs_str);
2932 free(ncommits_str);
2933 free(header);
2934 return err;
2937 static void
2938 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2940 struct commit_queue_entry *entry;
2941 int nscrolled = 0;
2943 entry = TAILQ_FIRST(&s->commits->head);
2944 if (s->first_displayed_entry == entry)
2945 return;
2947 entry = s->first_displayed_entry;
2948 while (entry && nscrolled < maxscroll) {
2949 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2950 if (entry) {
2951 s->first_displayed_entry = entry;
2952 nscrolled++;
2957 static const struct got_error *
2958 trigger_log_thread(struct tog_view *view, int wait)
2960 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2961 int errcode;
2963 if (!using_mock_io)
2964 halfdelay(1); /* fast refresh while loading commits */
2966 while (!ta->log_complete && !tog_thread_error &&
2967 (ta->commits_needed > 0 || ta->load_all)) {
2968 /* Wake the log thread. */
2969 errcode = pthread_cond_signal(&ta->need_commits);
2970 if (errcode)
2971 return got_error_set_errno(errcode,
2972 "pthread_cond_signal");
2975 * The mutex will be released while the view loop waits
2976 * in wgetch(), at which time the log thread will run.
2978 if (!wait)
2979 break;
2981 /* Display progress update in log view. */
2982 show_log_view(view);
2983 update_panels();
2984 doupdate();
2986 /* Wait right here while next commit is being loaded. */
2987 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2988 if (errcode)
2989 return got_error_set_errno(errcode,
2990 "pthread_cond_wait");
2992 /* Display progress update in log view. */
2993 show_log_view(view);
2994 update_panels();
2995 doupdate();
2998 return NULL;
3001 static const struct got_error *
3002 request_log_commits(struct tog_view *view)
3004 struct tog_log_view_state *state = &view->state.log;
3005 const struct got_error *err = NULL;
3007 if (state->thread_args.log_complete)
3008 return NULL;
3010 state->thread_args.commits_needed += view->nscrolled;
3011 err = trigger_log_thread(view, 1);
3012 view->nscrolled = 0;
3014 return err;
3017 static const struct got_error *
3018 log_scroll_down(struct tog_view *view, int maxscroll)
3020 struct tog_log_view_state *s = &view->state.log;
3021 const struct got_error *err = NULL;
3022 struct commit_queue_entry *pentry;
3023 int nscrolled = 0, ncommits_needed;
3025 if (s->last_displayed_entry == NULL)
3026 return NULL;
3028 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
3029 if (s->commits->ncommits < ncommits_needed &&
3030 !s->thread_args.log_complete) {
3032 * Ask the log thread for required amount of commits.
3034 s->thread_args.commits_needed +=
3035 ncommits_needed - s->commits->ncommits;
3036 err = trigger_log_thread(view, 1);
3037 if (err)
3038 return err;
3041 do {
3042 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
3043 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
3044 break;
3046 s->last_displayed_entry = pentry ?
3047 pentry : s->last_displayed_entry;
3049 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3050 if (pentry == NULL)
3051 break;
3052 s->first_displayed_entry = pentry;
3053 } while (++nscrolled < maxscroll);
3055 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3056 view->nscrolled += nscrolled;
3057 else
3058 view->nscrolled = 0;
3060 return err;
3063 static const struct got_error *
3064 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3065 struct got_commit_object *commit, struct got_object_id *commit_id,
3066 struct tog_view *log_view, struct got_repository *repo)
3068 const struct got_error *err;
3069 struct got_object_qid *parent_id;
3070 struct tog_view *diff_view;
3072 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3073 if (diff_view == NULL)
3074 return got_error_from_errno("view_open");
3076 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3077 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3078 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3079 if (err == NULL)
3080 *new_view = diff_view;
3081 return err;
3084 static const struct got_error *
3085 tree_view_visit_subtree(struct tog_tree_view_state *s,
3086 struct got_tree_object *subtree)
3088 struct tog_parent_tree *parent;
3090 parent = calloc(1, sizeof(*parent));
3091 if (parent == NULL)
3092 return got_error_from_errno("calloc");
3094 parent->tree = s->tree;
3095 parent->first_displayed_entry = s->first_displayed_entry;
3096 parent->selected_entry = s->selected_entry;
3097 parent->selected = s->selected;
3098 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3099 s->tree = subtree;
3100 s->selected = 0;
3101 s->first_displayed_entry = NULL;
3102 return NULL;
3105 static const struct got_error *
3106 tree_view_walk_path(struct tog_tree_view_state *s,
3107 struct got_commit_object *commit, const char *path)
3109 const struct got_error *err = NULL;
3110 struct got_tree_object *tree = NULL;
3111 const char *p;
3112 char *slash, *subpath = NULL;
3114 /* Walk the path and open corresponding tree objects. */
3115 p = path;
3116 while (*p) {
3117 struct got_tree_entry *te;
3118 struct got_object_id *tree_id;
3119 char *te_name;
3121 while (p[0] == '/')
3122 p++;
3124 /* Ensure the correct subtree entry is selected. */
3125 slash = strchr(p, '/');
3126 if (slash == NULL)
3127 te_name = strdup(p);
3128 else
3129 te_name = strndup(p, slash - p);
3130 if (te_name == NULL) {
3131 err = got_error_from_errno("strndup");
3132 break;
3134 te = got_object_tree_find_entry(s->tree, te_name);
3135 if (te == NULL) {
3136 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3137 free(te_name);
3138 break;
3140 free(te_name);
3141 s->first_displayed_entry = s->selected_entry = te;
3143 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3144 break; /* jump to this file's entry */
3146 slash = strchr(p, '/');
3147 if (slash)
3148 subpath = strndup(path, slash - path);
3149 else
3150 subpath = strdup(path);
3151 if (subpath == NULL) {
3152 err = got_error_from_errno("strdup");
3153 break;
3156 err = got_object_id_by_path(&tree_id, s->repo, commit,
3157 subpath);
3158 if (err)
3159 break;
3161 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3162 free(tree_id);
3163 if (err)
3164 break;
3166 err = tree_view_visit_subtree(s, tree);
3167 if (err) {
3168 got_object_tree_close(tree);
3169 break;
3171 if (slash == NULL)
3172 break;
3173 free(subpath);
3174 subpath = NULL;
3175 p = slash;
3178 free(subpath);
3179 return err;
3182 static const struct got_error *
3183 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3184 struct commit_queue_entry *entry, const char *path,
3185 const char *head_ref_name, struct got_repository *repo)
3187 const struct got_error *err = NULL;
3188 struct tog_tree_view_state *s;
3189 struct tog_view *tree_view;
3191 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3192 if (tree_view == NULL)
3193 return got_error_from_errno("view_open");
3195 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3196 if (err)
3197 return err;
3198 s = &tree_view->state.tree;
3200 *new_view = tree_view;
3202 if (got_path_is_root_dir(path))
3203 return NULL;
3205 return tree_view_walk_path(s, entry->commit, path);
3208 static const struct got_error *
3209 block_signals_used_by_main_thread(void)
3211 sigset_t sigset;
3212 int errcode;
3214 if (sigemptyset(&sigset) == -1)
3215 return got_error_from_errno("sigemptyset");
3217 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3218 if (sigaddset(&sigset, SIGWINCH) == -1)
3219 return got_error_from_errno("sigaddset");
3220 if (sigaddset(&sigset, SIGCONT) == -1)
3221 return got_error_from_errno("sigaddset");
3222 if (sigaddset(&sigset, SIGINT) == -1)
3223 return got_error_from_errno("sigaddset");
3224 if (sigaddset(&sigset, SIGTERM) == -1)
3225 return got_error_from_errno("sigaddset");
3227 /* ncurses handles SIGTSTP */
3228 if (sigaddset(&sigset, SIGTSTP) == -1)
3229 return got_error_from_errno("sigaddset");
3231 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3232 if (errcode)
3233 return got_error_set_errno(errcode, "pthread_sigmask");
3235 return NULL;
3238 static void *
3239 log_thread(void *arg)
3241 const struct got_error *err = NULL;
3242 int errcode = 0;
3243 struct tog_log_thread_args *a = arg;
3244 int done = 0;
3247 * Sync startup with main thread such that we begin our
3248 * work once view_input() has released the mutex.
3250 errcode = pthread_mutex_lock(&tog_mutex);
3251 if (errcode) {
3252 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3253 return (void *)err;
3256 err = block_signals_used_by_main_thread();
3257 if (err) {
3258 pthread_mutex_unlock(&tog_mutex);
3259 goto done;
3262 while (!done && !err && !tog_fatal_signal_received()) {
3263 errcode = pthread_mutex_unlock(&tog_mutex);
3264 if (errcode) {
3265 err = got_error_set_errno(errcode,
3266 "pthread_mutex_unlock");
3267 goto done;
3269 err = queue_commits(a);
3270 if (err) {
3271 if (err->code != GOT_ERR_ITER_COMPLETED)
3272 goto done;
3273 err = NULL;
3274 done = 1;
3275 } else if (a->commits_needed > 0 && !a->load_all) {
3276 if (*a->limiting) {
3277 if (a->limit_match)
3278 a->commits_needed--;
3279 } else
3280 a->commits_needed--;
3283 errcode = pthread_mutex_lock(&tog_mutex);
3284 if (errcode) {
3285 err = got_error_set_errno(errcode,
3286 "pthread_mutex_lock");
3287 goto done;
3288 } else if (*a->quit)
3289 done = 1;
3290 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3291 *a->first_displayed_entry =
3292 TAILQ_FIRST(&a->limit_commits->head);
3293 *a->selected_entry = *a->first_displayed_entry;
3294 } else if (*a->first_displayed_entry == NULL) {
3295 *a->first_displayed_entry =
3296 TAILQ_FIRST(&a->real_commits->head);
3297 *a->selected_entry = *a->first_displayed_entry;
3300 errcode = pthread_cond_signal(&a->commit_loaded);
3301 if (errcode) {
3302 err = got_error_set_errno(errcode,
3303 "pthread_cond_signal");
3304 pthread_mutex_unlock(&tog_mutex);
3305 goto done;
3308 if (done)
3309 a->commits_needed = 0;
3310 else {
3311 if (a->commits_needed == 0 && !a->load_all) {
3312 errcode = pthread_cond_wait(&a->need_commits,
3313 &tog_mutex);
3314 if (errcode) {
3315 err = got_error_set_errno(errcode,
3316 "pthread_cond_wait");
3317 pthread_mutex_unlock(&tog_mutex);
3318 goto done;
3320 if (*a->quit)
3321 done = 1;
3325 a->log_complete = 1;
3326 errcode = pthread_mutex_unlock(&tog_mutex);
3327 if (errcode)
3328 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3329 done:
3330 if (err) {
3331 tog_thread_error = 1;
3332 pthread_cond_signal(&a->commit_loaded);
3334 return (void *)err;
3337 static const struct got_error *
3338 stop_log_thread(struct tog_log_view_state *s)
3340 const struct got_error *err = NULL, *thread_err = NULL;
3341 int errcode;
3343 if (s->thread) {
3344 s->quit = 1;
3345 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3346 if (errcode)
3347 return got_error_set_errno(errcode,
3348 "pthread_cond_signal");
3349 errcode = pthread_mutex_unlock(&tog_mutex);
3350 if (errcode)
3351 return got_error_set_errno(errcode,
3352 "pthread_mutex_unlock");
3353 errcode = pthread_join(s->thread, (void **)&thread_err);
3354 if (errcode)
3355 return got_error_set_errno(errcode, "pthread_join");
3356 errcode = pthread_mutex_lock(&tog_mutex);
3357 if (errcode)
3358 return got_error_set_errno(errcode,
3359 "pthread_mutex_lock");
3360 s->thread = NULL;
3363 if (s->thread_args.repo) {
3364 err = got_repo_close(s->thread_args.repo);
3365 s->thread_args.repo = NULL;
3368 if (s->thread_args.pack_fds) {
3369 const struct got_error *pack_err =
3370 got_repo_pack_fds_close(s->thread_args.pack_fds);
3371 if (err == NULL)
3372 err = pack_err;
3373 s->thread_args.pack_fds = NULL;
3376 if (s->thread_args.graph) {
3377 got_commit_graph_close(s->thread_args.graph);
3378 s->thread_args.graph = NULL;
3381 return err ? err : thread_err;
3384 static const struct got_error *
3385 close_log_view(struct tog_view *view)
3387 const struct got_error *err = NULL;
3388 struct tog_log_view_state *s = &view->state.log;
3389 int errcode;
3391 err = stop_log_thread(s);
3393 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3394 if (errcode && err == NULL)
3395 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3397 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3398 if (errcode && err == NULL)
3399 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3401 free_commits(&s->limit_commits);
3402 free_commits(&s->real_commits);
3403 free(s->in_repo_path);
3404 s->in_repo_path = NULL;
3405 free(s->start_id);
3406 s->start_id = NULL;
3407 free(s->head_ref_name);
3408 s->head_ref_name = NULL;
3409 return err;
3413 * We use two queues to implement the limit feature: first consists of
3414 * commits matching the current limit_regex; second is the real queue
3415 * of all known commits (real_commits). When the user starts limiting,
3416 * we swap queues such that all movement and displaying functionality
3417 * works with very slight change.
3419 static const struct got_error *
3420 limit_log_view(struct tog_view *view)
3422 struct tog_log_view_state *s = &view->state.log;
3423 struct commit_queue_entry *entry;
3424 struct tog_view *v = view;
3425 const struct got_error *err = NULL;
3426 char pattern[1024];
3427 int ret;
3429 if (view_is_hsplit_top(view))
3430 v = view->child;
3431 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3432 v = view->parent;
3434 /* Get the pattern */
3435 wmove(v->window, v->nlines - 1, 0);
3436 wclrtoeol(v->window);
3437 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3438 nodelay(v->window, FALSE);
3439 nocbreak();
3440 echo();
3441 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3442 cbreak();
3443 noecho();
3444 nodelay(v->window, TRUE);
3445 if (ret == ERR)
3446 return NULL;
3448 if (*pattern == '\0') {
3450 * Safety measure for the situation where the user
3451 * resets limit without previously limiting anything.
3453 if (!s->limit_view)
3454 return NULL;
3457 * User could have pressed Ctrl+L, which refreshed the
3458 * commit queues, it means we can't save previously
3459 * (before limit took place) displayed entries,
3460 * because they would point to already free'ed memory,
3461 * so we are forced to always select first entry of
3462 * the queue.
3464 s->commits = &s->real_commits;
3465 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3466 s->selected_entry = s->first_displayed_entry;
3467 s->selected = 0;
3468 s->limit_view = 0;
3470 return NULL;
3473 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3474 return NULL;
3476 s->limit_view = 1;
3478 /* Clear the screen while loading limit view */
3479 s->first_displayed_entry = NULL;
3480 s->last_displayed_entry = NULL;
3481 s->selected_entry = NULL;
3482 s->commits = &s->limit_commits;
3484 /* Prepare limit queue for new search */
3485 free_commits(&s->limit_commits);
3486 s->limit_commits.ncommits = 0;
3488 /* First process commits, which are in queue already */
3489 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3490 int have_match = 0;
3492 err = match_commit(&have_match, entry->id,
3493 entry->commit, &s->limit_regex);
3494 if (err)
3495 return err;
3497 if (have_match) {
3498 struct commit_queue_entry *matched;
3500 matched = alloc_commit_queue_entry(entry->commit,
3501 entry->id);
3502 if (matched == NULL) {
3503 err = got_error_from_errno(
3504 "alloc_commit_queue_entry");
3505 break;
3507 matched->commit = entry->commit;
3508 got_object_commit_retain(entry->commit);
3510 matched->idx = s->limit_commits.ncommits;
3511 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3512 matched, entry);
3513 s->limit_commits.ncommits++;
3517 /* Second process all the commits, until we fill the screen */
3518 if (s->limit_commits.ncommits < view->nlines - 1 &&
3519 !s->thread_args.log_complete) {
3520 s->thread_args.commits_needed +=
3521 view->nlines - s->limit_commits.ncommits - 1;
3522 err = trigger_log_thread(view, 1);
3523 if (err)
3524 return err;
3527 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3528 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3529 s->selected = 0;
3531 return NULL;
3534 static const struct got_error *
3535 search_start_log_view(struct tog_view *view)
3537 struct tog_log_view_state *s = &view->state.log;
3539 s->matched_entry = NULL;
3540 s->search_entry = NULL;
3541 return NULL;
3544 static const struct got_error *
3545 search_next_log_view(struct tog_view *view)
3547 const struct got_error *err = NULL;
3548 struct tog_log_view_state *s = &view->state.log;
3549 struct commit_queue_entry *entry;
3551 /* Display progress update in log view. */
3552 show_log_view(view);
3553 update_panels();
3554 doupdate();
3556 if (s->search_entry) {
3557 int errcode, ch;
3558 errcode = pthread_mutex_unlock(&tog_mutex);
3559 if (errcode)
3560 return got_error_set_errno(errcode,
3561 "pthread_mutex_unlock");
3562 ch = wgetch(view->window);
3563 errcode = pthread_mutex_lock(&tog_mutex);
3564 if (errcode)
3565 return got_error_set_errno(errcode,
3566 "pthread_mutex_lock");
3567 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3568 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3569 return NULL;
3571 if (view->searching == TOG_SEARCH_FORWARD)
3572 entry = TAILQ_NEXT(s->search_entry, entry);
3573 else
3574 entry = TAILQ_PREV(s->search_entry,
3575 commit_queue_head, entry);
3576 } else if (s->matched_entry) {
3578 * If the user has moved the cursor after we hit a match,
3579 * the position from where we should continue searching
3580 * might have changed.
3582 if (view->searching == TOG_SEARCH_FORWARD)
3583 entry = TAILQ_NEXT(s->selected_entry, entry);
3584 else
3585 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3586 entry);
3587 } else {
3588 entry = s->selected_entry;
3591 while (1) {
3592 int have_match = 0;
3594 if (entry == NULL) {
3595 if (s->thread_args.log_complete ||
3596 view->searching == TOG_SEARCH_BACKWARD) {
3597 view->search_next_done =
3598 (s->matched_entry == NULL ?
3599 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3600 s->search_entry = NULL;
3601 return NULL;
3604 * Poke the log thread for more commits and return,
3605 * allowing the main loop to make progress. Search
3606 * will resume at s->search_entry once we come back.
3608 s->thread_args.commits_needed++;
3609 return trigger_log_thread(view, 0);
3612 err = match_commit(&have_match, entry->id, entry->commit,
3613 &view->regex);
3614 if (err)
3615 break;
3616 if (have_match) {
3617 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3618 s->matched_entry = entry;
3619 break;
3622 s->search_entry = entry;
3623 if (view->searching == TOG_SEARCH_FORWARD)
3624 entry = TAILQ_NEXT(entry, entry);
3625 else
3626 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3629 if (s->matched_entry) {
3630 int cur = s->selected_entry->idx;
3631 while (cur < s->matched_entry->idx) {
3632 err = input_log_view(NULL, view, KEY_DOWN);
3633 if (err)
3634 return err;
3635 cur++;
3637 while (cur > s->matched_entry->idx) {
3638 err = input_log_view(NULL, view, KEY_UP);
3639 if (err)
3640 return err;
3641 cur--;
3645 s->search_entry = NULL;
3647 return NULL;
3650 static const struct got_error *
3651 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3652 struct got_repository *repo, const char *head_ref_name,
3653 const char *in_repo_path, int log_branches)
3655 const struct got_error *err = NULL;
3656 struct tog_log_view_state *s = &view->state.log;
3657 struct got_repository *thread_repo = NULL;
3658 struct got_commit_graph *thread_graph = NULL;
3659 int errcode;
3661 if (in_repo_path != s->in_repo_path) {
3662 free(s->in_repo_path);
3663 s->in_repo_path = strdup(in_repo_path);
3664 if (s->in_repo_path == NULL) {
3665 err = got_error_from_errno("strdup");
3666 goto done;
3670 /* The commit queue only contains commits being displayed. */
3671 TAILQ_INIT(&s->real_commits.head);
3672 s->real_commits.ncommits = 0;
3673 s->commits = &s->real_commits;
3675 TAILQ_INIT(&s->limit_commits.head);
3676 s->limit_view = 0;
3677 s->limit_commits.ncommits = 0;
3679 s->repo = repo;
3680 if (head_ref_name) {
3681 s->head_ref_name = strdup(head_ref_name);
3682 if (s->head_ref_name == NULL) {
3683 err = got_error_from_errno("strdup");
3684 goto done;
3687 s->start_id = got_object_id_dup(start_id);
3688 if (s->start_id == NULL) {
3689 err = got_error_from_errno("got_object_id_dup");
3690 goto done;
3692 s->log_branches = log_branches;
3693 s->use_committer = 1;
3695 STAILQ_INIT(&s->colors);
3696 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3697 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3698 get_color_value("TOG_COLOR_COMMIT"));
3699 if (err)
3700 goto done;
3701 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3702 get_color_value("TOG_COLOR_AUTHOR"));
3703 if (err) {
3704 free_colors(&s->colors);
3705 goto done;
3707 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3708 get_color_value("TOG_COLOR_DATE"));
3709 if (err) {
3710 free_colors(&s->colors);
3711 goto done;
3715 view->show = show_log_view;
3716 view->input = input_log_view;
3717 view->resize = resize_log_view;
3718 view->close = close_log_view;
3719 view->search_start = search_start_log_view;
3720 view->search_next = search_next_log_view;
3722 if (s->thread_args.pack_fds == NULL) {
3723 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3724 if (err)
3725 goto done;
3727 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3728 s->thread_args.pack_fds);
3729 if (err)
3730 goto done;
3731 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3732 !s->log_branches);
3733 if (err)
3734 goto done;
3735 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3736 s->repo, NULL, NULL);
3737 if (err)
3738 goto done;
3740 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3741 if (errcode) {
3742 err = got_error_set_errno(errcode, "pthread_cond_init");
3743 goto done;
3745 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3746 if (errcode) {
3747 err = got_error_set_errno(errcode, "pthread_cond_init");
3748 goto done;
3751 s->thread_args.commits_needed = view->nlines;
3752 s->thread_args.graph = thread_graph;
3753 s->thread_args.real_commits = &s->real_commits;
3754 s->thread_args.limit_commits = &s->limit_commits;
3755 s->thread_args.in_repo_path = s->in_repo_path;
3756 s->thread_args.start_id = s->start_id;
3757 s->thread_args.repo = thread_repo;
3758 s->thread_args.log_complete = 0;
3759 s->thread_args.quit = &s->quit;
3760 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3761 s->thread_args.selected_entry = &s->selected_entry;
3762 s->thread_args.searching = &view->searching;
3763 s->thread_args.search_next_done = &view->search_next_done;
3764 s->thread_args.regex = &view->regex;
3765 s->thread_args.limiting = &s->limit_view;
3766 s->thread_args.limit_regex = &s->limit_regex;
3767 s->thread_args.limit_commits = &s->limit_commits;
3768 done:
3769 if (err) {
3770 if (view->close == NULL)
3771 close_log_view(view);
3772 view_close(view);
3774 return err;
3777 static const struct got_error *
3778 show_log_view(struct tog_view *view)
3780 const struct got_error *err;
3781 struct tog_log_view_state *s = &view->state.log;
3783 if (s->thread == NULL) {
3784 int errcode = pthread_create(&s->thread, NULL, log_thread,
3785 &s->thread_args);
3786 if (errcode)
3787 return got_error_set_errno(errcode, "pthread_create");
3788 if (s->thread_args.commits_needed > 0) {
3789 err = trigger_log_thread(view, 1);
3790 if (err)
3791 return err;
3795 return draw_commits(view);
3798 static void
3799 log_move_cursor_up(struct tog_view *view, int page, int home)
3801 struct tog_log_view_state *s = &view->state.log;
3803 if (s->first_displayed_entry == NULL)
3804 return;
3805 if (s->selected_entry->idx == 0)
3806 view->count = 0;
3808 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3809 || home)
3810 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3812 if (!page && !home && s->selected > 0)
3813 --s->selected;
3814 else
3815 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3817 select_commit(s);
3818 return;
3821 static const struct got_error *
3822 log_move_cursor_down(struct tog_view *view, int page)
3824 struct tog_log_view_state *s = &view->state.log;
3825 const struct got_error *err = NULL;
3826 int eos = view->nlines - 2;
3828 if (s->first_displayed_entry == NULL)
3829 return NULL;
3831 if (s->thread_args.log_complete &&
3832 s->selected_entry->idx >= s->commits->ncommits - 1)
3833 return NULL;
3835 if (view_is_hsplit_top(view))
3836 --eos; /* border consumes the last line */
3838 if (!page) {
3839 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3840 ++s->selected;
3841 else
3842 err = log_scroll_down(view, 1);
3843 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3844 struct commit_queue_entry *entry;
3845 int n;
3847 s->selected = 0;
3848 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3849 s->last_displayed_entry = entry;
3850 for (n = 0; n <= eos; n++) {
3851 if (entry == NULL)
3852 break;
3853 s->first_displayed_entry = entry;
3854 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3856 if (n > 0)
3857 s->selected = n - 1;
3858 } else {
3859 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3860 s->thread_args.log_complete)
3861 s->selected += MIN(page,
3862 s->commits->ncommits - s->selected_entry->idx - 1);
3863 else
3864 err = log_scroll_down(view, page);
3866 if (err)
3867 return err;
3870 * We might necessarily overshoot in horizontal
3871 * splits; if so, select the last displayed commit.
3873 if (s->first_displayed_entry && s->last_displayed_entry) {
3874 s->selected = MIN(s->selected,
3875 s->last_displayed_entry->idx -
3876 s->first_displayed_entry->idx);
3879 select_commit(s);
3881 if (s->thread_args.log_complete &&
3882 s->selected_entry->idx == s->commits->ncommits - 1)
3883 view->count = 0;
3885 return NULL;
3888 static void
3889 view_get_split(struct tog_view *view, int *y, int *x)
3891 *x = 0;
3892 *y = 0;
3894 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3895 if (view->child && view->child->resized_y)
3896 *y = view->child->resized_y;
3897 else if (view->resized_y)
3898 *y = view->resized_y;
3899 else
3900 *y = view_split_begin_y(view->lines);
3901 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3902 if (view->child && view->child->resized_x)
3903 *x = view->child->resized_x;
3904 else if (view->resized_x)
3905 *x = view->resized_x;
3906 else
3907 *x = view_split_begin_x(view->begin_x);
3911 /* Split view horizontally at y and offset view->state->selected line. */
3912 static const struct got_error *
3913 view_init_hsplit(struct tog_view *view, int y)
3915 const struct got_error *err = NULL;
3917 view->nlines = y;
3918 view->ncols = COLS;
3919 err = view_resize(view);
3920 if (err)
3921 return err;
3923 err = offset_selection_down(view);
3925 return err;
3928 static const struct got_error *
3929 log_goto_line(struct tog_view *view, int nlines)
3931 const struct got_error *err = NULL;
3932 struct tog_log_view_state *s = &view->state.log;
3933 int g, idx = s->selected_entry->idx;
3935 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3936 return NULL;
3938 g = view->gline;
3939 view->gline = 0;
3941 if (g >= s->first_displayed_entry->idx + 1 &&
3942 g <= s->last_displayed_entry->idx + 1 &&
3943 g - s->first_displayed_entry->idx - 1 < nlines) {
3944 s->selected = g - s->first_displayed_entry->idx - 1;
3945 select_commit(s);
3946 return NULL;
3949 if (idx + 1 < g) {
3950 err = log_move_cursor_down(view, g - idx - 1);
3951 if (!err && g > s->selected_entry->idx + 1)
3952 err = log_move_cursor_down(view,
3953 g - s->first_displayed_entry->idx - 1);
3954 if (err)
3955 return err;
3956 } else if (idx + 1 > g)
3957 log_move_cursor_up(view, idx - g + 1, 0);
3959 if (g < nlines && s->first_displayed_entry->idx == 0)
3960 s->selected = g - 1;
3962 select_commit(s);
3963 return NULL;
3967 static void
3968 horizontal_scroll_input(struct tog_view *view, int ch)
3971 switch (ch) {
3972 case KEY_LEFT:
3973 case 'h':
3974 view->x -= MIN(view->x, 2);
3975 if (view->x <= 0)
3976 view->count = 0;
3977 break;
3978 case KEY_RIGHT:
3979 case 'l':
3980 if (view->x + view->ncols / 2 < view->maxx)
3981 view->x += 2;
3982 else
3983 view->count = 0;
3984 break;
3985 case '0':
3986 view->x = 0;
3987 break;
3988 case '$':
3989 view->x = MAX(view->maxx - view->ncols / 2, 0);
3990 view->count = 0;
3991 break;
3992 default:
3993 break;
3997 static const struct got_error *
3998 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
4000 const struct got_error *err = NULL;
4001 struct tog_log_view_state *s = &view->state.log;
4002 int eos, nscroll;
4004 if (s->thread_args.load_all) {
4005 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
4006 s->thread_args.load_all = 0;
4007 else if (s->thread_args.log_complete) {
4008 err = log_move_cursor_down(view, s->commits->ncommits);
4009 s->thread_args.load_all = 0;
4011 if (err)
4012 return err;
4015 eos = nscroll = view->nlines - 1;
4016 if (view_is_hsplit_top(view))
4017 --eos; /* border */
4019 if (view->gline)
4020 return log_goto_line(view, eos);
4022 switch (ch) {
4023 case '&':
4024 err = limit_log_view(view);
4025 break;
4026 case 'q':
4027 s->quit = 1;
4028 break;
4029 case '0':
4030 case '$':
4031 case KEY_RIGHT:
4032 case 'l':
4033 case KEY_LEFT:
4034 case 'h':
4035 horizontal_scroll_input(view, ch);
4036 break;
4037 case 'k':
4038 case KEY_UP:
4039 case '<':
4040 case ',':
4041 case CTRL('p'):
4042 log_move_cursor_up(view, 0, 0);
4043 break;
4044 case 'g':
4045 case '=':
4046 case KEY_HOME:
4047 log_move_cursor_up(view, 0, 1);
4048 view->count = 0;
4049 break;
4050 case CTRL('u'):
4051 case 'u':
4052 nscroll /= 2;
4053 /* FALL THROUGH */
4054 case KEY_PPAGE:
4055 case CTRL('b'):
4056 case 'b':
4057 log_move_cursor_up(view, nscroll, 0);
4058 break;
4059 case 'j':
4060 case KEY_DOWN:
4061 case '>':
4062 case '.':
4063 case CTRL('n'):
4064 err = log_move_cursor_down(view, 0);
4065 break;
4066 case '@':
4067 s->use_committer = !s->use_committer;
4068 view->action = s->use_committer ?
4069 "show committer" : "show commit author";
4070 break;
4071 case 'G':
4072 case '*':
4073 case KEY_END: {
4074 /* We don't know yet how many commits, so we're forced to
4075 * traverse them all. */
4076 view->count = 0;
4077 s->thread_args.load_all = 1;
4078 if (!s->thread_args.log_complete)
4079 return trigger_log_thread(view, 0);
4080 err = log_move_cursor_down(view, s->commits->ncommits);
4081 s->thread_args.load_all = 0;
4082 break;
4084 case CTRL('d'):
4085 case 'd':
4086 nscroll /= 2;
4087 /* FALL THROUGH */
4088 case KEY_NPAGE:
4089 case CTRL('f'):
4090 case 'f':
4091 case ' ':
4092 err = log_move_cursor_down(view, nscroll);
4093 break;
4094 case KEY_RESIZE:
4095 if (s->selected > view->nlines - 2)
4096 s->selected = view->nlines - 2;
4097 if (s->selected > s->commits->ncommits - 1)
4098 s->selected = s->commits->ncommits - 1;
4099 select_commit(s);
4100 if (s->commits->ncommits < view->nlines - 1 &&
4101 !s->thread_args.log_complete) {
4102 s->thread_args.commits_needed += (view->nlines - 1) -
4103 s->commits->ncommits;
4104 err = trigger_log_thread(view, 1);
4106 break;
4107 case KEY_ENTER:
4108 case '\r':
4109 view->count = 0;
4110 if (s->selected_entry == NULL)
4111 break;
4112 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4113 break;
4114 case 'T':
4115 view->count = 0;
4116 if (s->selected_entry == NULL)
4117 break;
4118 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4119 break;
4120 case KEY_BACKSPACE:
4121 case CTRL('l'):
4122 case 'B':
4123 view->count = 0;
4124 if (ch == KEY_BACKSPACE &&
4125 got_path_is_root_dir(s->in_repo_path))
4126 break;
4127 err = stop_log_thread(s);
4128 if (err)
4129 return err;
4130 if (ch == KEY_BACKSPACE) {
4131 char *parent_path;
4132 err = got_path_dirname(&parent_path, s->in_repo_path);
4133 if (err)
4134 return err;
4135 free(s->in_repo_path);
4136 s->in_repo_path = parent_path;
4137 s->thread_args.in_repo_path = s->in_repo_path;
4138 } else if (ch == CTRL('l')) {
4139 struct got_object_id *start_id;
4140 err = got_repo_match_object_id(&start_id, NULL,
4141 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4142 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4143 if (err) {
4144 if (s->head_ref_name == NULL ||
4145 err->code != GOT_ERR_NOT_REF)
4146 return err;
4147 /* Try to cope with deleted references. */
4148 free(s->head_ref_name);
4149 s->head_ref_name = NULL;
4150 err = got_repo_match_object_id(&start_id,
4151 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4152 &tog_refs, s->repo);
4153 if (err)
4154 return err;
4156 free(s->start_id);
4157 s->start_id = start_id;
4158 s->thread_args.start_id = s->start_id;
4159 } else /* 'B' */
4160 s->log_branches = !s->log_branches;
4162 if (s->thread_args.pack_fds == NULL) {
4163 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4164 if (err)
4165 return err;
4167 err = got_repo_open(&s->thread_args.repo,
4168 got_repo_get_path(s->repo), NULL,
4169 s->thread_args.pack_fds);
4170 if (err)
4171 return err;
4172 tog_free_refs();
4173 err = tog_load_refs(s->repo, 0);
4174 if (err)
4175 return err;
4176 err = got_commit_graph_open(&s->thread_args.graph,
4177 s->in_repo_path, !s->log_branches);
4178 if (err)
4179 return err;
4180 err = got_commit_graph_iter_start(s->thread_args.graph,
4181 s->start_id, s->repo, NULL, NULL);
4182 if (err)
4183 return err;
4184 free_commits(&s->real_commits);
4185 free_commits(&s->limit_commits);
4186 s->first_displayed_entry = NULL;
4187 s->last_displayed_entry = NULL;
4188 s->selected_entry = NULL;
4189 s->selected = 0;
4190 s->thread_args.log_complete = 0;
4191 s->quit = 0;
4192 s->thread_args.commits_needed = view->lines;
4193 s->matched_entry = NULL;
4194 s->search_entry = NULL;
4195 view->offset = 0;
4196 break;
4197 case 'R':
4198 view->count = 0;
4199 err = view_request_new(new_view, view, TOG_VIEW_REF);
4200 break;
4201 default:
4202 view->count = 0;
4203 break;
4206 return err;
4209 static const struct got_error *
4210 apply_unveil(const char *repo_path, const char *worktree_path)
4212 const struct got_error *error;
4214 #ifdef PROFILE
4215 if (unveil("gmon.out", "rwc") != 0)
4216 return got_error_from_errno2("unveil", "gmon.out");
4217 #endif
4218 if (repo_path && unveil(repo_path, "r") != 0)
4219 return got_error_from_errno2("unveil", repo_path);
4221 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4222 return got_error_from_errno2("unveil", worktree_path);
4224 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4225 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4227 error = got_privsep_unveil_exec_helpers();
4228 if (error != NULL)
4229 return error;
4231 if (unveil(NULL, NULL) != 0)
4232 return got_error_from_errno("unveil");
4234 return NULL;
4237 static const struct got_error *
4238 init_mock_term(const char *test_script_path)
4240 const struct got_error *err = NULL;
4241 const char *screen_dump_path;
4242 int in;
4244 if (test_script_path == NULL || *test_script_path == '\0')
4245 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4247 tog_io.f = fopen(test_script_path, "re");
4248 if (tog_io.f == NULL) {
4249 err = got_error_from_errno_fmt("fopen: %s",
4250 test_script_path);
4251 goto done;
4254 /* test mode, we don't want any output */
4255 tog_io.cout = fopen("/dev/null", "w+");
4256 if (tog_io.cout == NULL) {
4257 err = got_error_from_errno2("fopen", "/dev/null");
4258 goto done;
4261 in = dup(fileno(tog_io.cout));
4262 if (in == -1) {
4263 err = got_error_from_errno("dup");
4264 goto done;
4266 tog_io.cin = fdopen(in, "r");
4267 if (tog_io.cin == NULL) {
4268 err = got_error_from_errno("fdopen");
4269 close(in);
4270 goto done;
4273 screen_dump_path = getenv("TOG_SCR_DUMP");
4274 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4275 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4276 tog_io.sdump = fopen(screen_dump_path, "wex");
4277 if (tog_io.sdump == NULL) {
4278 err = got_error_from_errno2("fopen", screen_dump_path);
4279 goto done;
4282 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4283 err = got_error_from_errno("fseeko");
4284 goto done;
4287 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4288 err = got_error_msg(GOT_ERR_IO,
4289 "newterm: failed to initialise curses");
4291 using_mock_io = 1;
4293 done:
4294 if (err)
4295 tog_io_close();
4296 return err;
4299 static void
4300 init_curses(void)
4303 * Override default signal handlers before starting ncurses.
4304 * This should prevent ncurses from installing its own
4305 * broken cleanup() signal handler.
4307 signal(SIGWINCH, tog_sigwinch);
4308 signal(SIGPIPE, tog_sigpipe);
4309 signal(SIGCONT, tog_sigcont);
4310 signal(SIGINT, tog_sigint);
4311 signal(SIGTERM, tog_sigterm);
4313 if (using_mock_io) /* In test mode we use a fake terminal */
4314 return;
4316 initscr();
4318 cbreak();
4319 halfdelay(1); /* Fast refresh while initial view is loading. */
4320 noecho();
4321 nonl();
4322 intrflush(stdscr, FALSE);
4323 keypad(stdscr, TRUE);
4324 curs_set(0);
4325 if (getenv("TOG_COLORS") != NULL) {
4326 start_color();
4327 use_default_colors();
4330 return;
4333 static const struct got_error *
4334 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4335 struct got_repository *repo, struct got_worktree *worktree)
4337 const struct got_error *err = NULL;
4339 if (argc == 0) {
4340 *in_repo_path = strdup("/");
4341 if (*in_repo_path == NULL)
4342 return got_error_from_errno("strdup");
4343 return NULL;
4346 if (worktree) {
4347 const char *prefix = got_worktree_get_path_prefix(worktree);
4348 char *p;
4350 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4351 if (err)
4352 return err;
4353 if (asprintf(in_repo_path, "%s%s%s", prefix,
4354 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4355 p) == -1) {
4356 err = got_error_from_errno("asprintf");
4357 *in_repo_path = NULL;
4359 free(p);
4360 } else
4361 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4363 return err;
4366 static const struct got_error *
4367 cmd_log(int argc, char *argv[])
4369 const struct got_error *error;
4370 struct got_repository *repo = NULL;
4371 struct got_worktree *worktree = NULL;
4372 struct got_object_id *start_id = NULL;
4373 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4374 char *start_commit = NULL, *label = NULL;
4375 struct got_reference *ref = NULL;
4376 const char *head_ref_name = NULL;
4377 int ch, log_branches = 0;
4378 struct tog_view *view;
4379 int *pack_fds = NULL;
4381 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4382 switch (ch) {
4383 case 'b':
4384 log_branches = 1;
4385 break;
4386 case 'c':
4387 start_commit = optarg;
4388 break;
4389 case 'r':
4390 repo_path = realpath(optarg, NULL);
4391 if (repo_path == NULL)
4392 return got_error_from_errno2("realpath",
4393 optarg);
4394 break;
4395 default:
4396 usage_log();
4397 /* NOTREACHED */
4401 argc -= optind;
4402 argv += optind;
4404 if (argc > 1)
4405 usage_log();
4407 error = got_repo_pack_fds_open(&pack_fds);
4408 if (error != NULL)
4409 goto done;
4411 if (repo_path == NULL) {
4412 cwd = getcwd(NULL, 0);
4413 if (cwd == NULL)
4414 return got_error_from_errno("getcwd");
4415 error = got_worktree_open(&worktree, cwd);
4416 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4417 goto done;
4418 if (worktree)
4419 repo_path =
4420 strdup(got_worktree_get_repo_path(worktree));
4421 else
4422 repo_path = strdup(cwd);
4423 if (repo_path == NULL) {
4424 error = got_error_from_errno("strdup");
4425 goto done;
4429 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4430 if (error != NULL)
4431 goto done;
4433 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4434 repo, worktree);
4435 if (error)
4436 goto done;
4438 init_curses();
4440 error = apply_unveil(got_repo_get_path(repo),
4441 worktree ? got_worktree_get_root_path(worktree) : NULL);
4442 if (error)
4443 goto done;
4445 /* already loaded by tog_log_with_path()? */
4446 if (TAILQ_EMPTY(&tog_refs)) {
4447 error = tog_load_refs(repo, 0);
4448 if (error)
4449 goto done;
4452 if (start_commit == NULL) {
4453 error = got_repo_match_object_id(&start_id, &label,
4454 worktree ? got_worktree_get_head_ref_name(worktree) :
4455 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4456 if (error)
4457 goto done;
4458 head_ref_name = label;
4459 } else {
4460 error = got_ref_open(&ref, repo, start_commit, 0);
4461 if (error == NULL)
4462 head_ref_name = got_ref_get_name(ref);
4463 else if (error->code != GOT_ERR_NOT_REF)
4464 goto done;
4465 error = got_repo_match_object_id(&start_id, NULL,
4466 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4467 if (error)
4468 goto done;
4471 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4472 if (view == NULL) {
4473 error = got_error_from_errno("view_open");
4474 goto done;
4476 error = open_log_view(view, start_id, repo, head_ref_name,
4477 in_repo_path, log_branches);
4478 if (error)
4479 goto done;
4480 if (worktree) {
4481 /* Release work tree lock. */
4482 got_worktree_close(worktree);
4483 worktree = NULL;
4485 error = view_loop(view);
4486 done:
4487 free(in_repo_path);
4488 free(repo_path);
4489 free(cwd);
4490 free(start_id);
4491 free(label);
4492 if (ref)
4493 got_ref_close(ref);
4494 if (repo) {
4495 const struct got_error *close_err = got_repo_close(repo);
4496 if (error == NULL)
4497 error = close_err;
4499 if (worktree)
4500 got_worktree_close(worktree);
4501 if (pack_fds) {
4502 const struct got_error *pack_err =
4503 got_repo_pack_fds_close(pack_fds);
4504 if (error == NULL)
4505 error = pack_err;
4507 tog_free_refs();
4508 return error;
4511 __dead static void
4512 usage_diff(void)
4514 endwin();
4515 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4516 "object1 object2\n", getprogname());
4517 exit(1);
4520 static int
4521 match_line(const char *line, regex_t *regex, size_t nmatch,
4522 regmatch_t *regmatch)
4524 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4527 static struct tog_color *
4528 match_color(struct tog_colors *colors, const char *line)
4530 struct tog_color *tc = NULL;
4532 STAILQ_FOREACH(tc, colors, entry) {
4533 if (match_line(line, &tc->regex, 0, NULL))
4534 return tc;
4537 return NULL;
4540 static const struct got_error *
4541 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4542 WINDOW *window, int skipcol, regmatch_t *regmatch)
4544 const struct got_error *err = NULL;
4545 char *exstr = NULL;
4546 wchar_t *wline = NULL;
4547 int rme, rms, n, width, scrollx;
4548 int width0 = 0, width1 = 0, width2 = 0;
4549 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4551 *wtotal = 0;
4553 rms = regmatch->rm_so;
4554 rme = regmatch->rm_eo;
4556 err = expand_tab(&exstr, line);
4557 if (err)
4558 return err;
4560 /* Split the line into 3 segments, according to match offsets. */
4561 seg0 = strndup(exstr, rms);
4562 if (seg0 == NULL) {
4563 err = got_error_from_errno("strndup");
4564 goto done;
4566 seg1 = strndup(exstr + rms, rme - rms);
4567 if (seg1 == NULL) {
4568 err = got_error_from_errno("strndup");
4569 goto done;
4571 seg2 = strdup(exstr + rme);
4572 if (seg2 == NULL) {
4573 err = got_error_from_errno("strndup");
4574 goto done;
4577 /* draw up to matched token if we haven't scrolled past it */
4578 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4579 col_tab_align, 1);
4580 if (err)
4581 goto done;
4582 n = MAX(width0 - skipcol, 0);
4583 if (n) {
4584 free(wline);
4585 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4586 wlimit, col_tab_align, 1);
4587 if (err)
4588 goto done;
4589 waddwstr(window, &wline[scrollx]);
4590 wlimit -= width;
4591 *wtotal += width;
4594 if (wlimit > 0) {
4595 int i = 0, w = 0;
4596 size_t wlen;
4598 free(wline);
4599 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4600 col_tab_align, 1);
4601 if (err)
4602 goto done;
4603 wlen = wcslen(wline);
4604 while (i < wlen) {
4605 width = wcwidth(wline[i]);
4606 if (width == -1) {
4607 /* should not happen, tabs are expanded */
4608 err = got_error(GOT_ERR_RANGE);
4609 goto done;
4611 if (width0 + w + width > skipcol)
4612 break;
4613 w += width;
4614 i++;
4616 /* draw (visible part of) matched token (if scrolled into it) */
4617 if (width1 - w > 0) {
4618 wattron(window, A_STANDOUT);
4619 waddwstr(window, &wline[i]);
4620 wattroff(window, A_STANDOUT);
4621 wlimit -= (width1 - w);
4622 *wtotal += (width1 - w);
4626 if (wlimit > 0) { /* draw rest of line */
4627 free(wline);
4628 if (skipcol > width0 + width1) {
4629 err = format_line(&wline, &width2, &scrollx, seg2,
4630 skipcol - (width0 + width1), wlimit,
4631 col_tab_align, 1);
4632 if (err)
4633 goto done;
4634 waddwstr(window, &wline[scrollx]);
4635 } else {
4636 err = format_line(&wline, &width2, NULL, seg2, 0,
4637 wlimit, col_tab_align, 1);
4638 if (err)
4639 goto done;
4640 waddwstr(window, wline);
4642 *wtotal += width2;
4644 done:
4645 free(wline);
4646 free(exstr);
4647 free(seg0);
4648 free(seg1);
4649 free(seg2);
4650 return err;
4653 static int
4654 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4656 FILE *f = NULL;
4657 int *eof, *first, *selected;
4659 if (view->type == TOG_VIEW_DIFF) {
4660 struct tog_diff_view_state *s = &view->state.diff;
4662 first = &s->first_displayed_line;
4663 selected = first;
4664 eof = &s->eof;
4665 f = s->f;
4666 } else if (view->type == TOG_VIEW_HELP) {
4667 struct tog_help_view_state *s = &view->state.help;
4669 first = &s->first_displayed_line;
4670 selected = first;
4671 eof = &s->eof;
4672 f = s->f;
4673 } else if (view->type == TOG_VIEW_BLAME) {
4674 struct tog_blame_view_state *s = &view->state.blame;
4676 first = &s->first_displayed_line;
4677 selected = &s->selected_line;
4678 eof = &s->eof;
4679 f = s->blame.f;
4680 } else
4681 return 0;
4683 /* Center gline in the middle of the page like vi(1). */
4684 if (*lineno < view->gline - (view->nlines - 3) / 2)
4685 return 0;
4686 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4687 rewind(f);
4688 *eof = 0;
4689 *first = 1;
4690 *lineno = 0;
4691 *nprinted = 0;
4692 return 0;
4695 *selected = view->gline <= (view->nlines - 3) / 2 ?
4696 view->gline : (view->nlines - 3) / 2 + 1;
4697 view->gline = 0;
4699 return 1;
4702 static const struct got_error *
4703 draw_file(struct tog_view *view, const char *header)
4705 struct tog_diff_view_state *s = &view->state.diff;
4706 regmatch_t *regmatch = &view->regmatch;
4707 const struct got_error *err;
4708 int nprinted = 0;
4709 char *line;
4710 size_t linesize = 0;
4711 ssize_t linelen;
4712 wchar_t *wline;
4713 int width;
4714 int max_lines = view->nlines;
4715 int nlines = s->nlines;
4716 off_t line_offset;
4718 s->lineno = s->first_displayed_line - 1;
4719 line_offset = s->lines[s->first_displayed_line - 1].offset;
4720 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4721 return got_error_from_errno("fseek");
4723 werase(view->window);
4725 if (view->gline > s->nlines - 1)
4726 view->gline = s->nlines - 1;
4728 if (header) {
4729 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4730 1 : view->gline - (view->nlines - 3) / 2 :
4731 s->lineno + s->selected_line;
4733 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4734 return got_error_from_errno("asprintf");
4735 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4736 0, 0);
4737 free(line);
4738 if (err)
4739 return err;
4741 if (view_needs_focus_indication(view))
4742 wstandout(view->window);
4743 waddwstr(view->window, wline);
4744 free(wline);
4745 wline = NULL;
4746 while (width++ < view->ncols)
4747 waddch(view->window, ' ');
4748 if (view_needs_focus_indication(view))
4749 wstandend(view->window);
4751 if (max_lines <= 1)
4752 return NULL;
4753 max_lines--;
4756 s->eof = 0;
4757 view->maxx = 0;
4758 line = NULL;
4759 while (max_lines > 0 && nprinted < max_lines) {
4760 enum got_diff_line_type linetype;
4761 attr_t attr = 0;
4763 linelen = getline(&line, &linesize, s->f);
4764 if (linelen == -1) {
4765 if (feof(s->f)) {
4766 s->eof = 1;
4767 break;
4769 free(line);
4770 return got_ferror(s->f, GOT_ERR_IO);
4773 if (++s->lineno < s->first_displayed_line)
4774 continue;
4775 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4776 continue;
4777 if (s->lineno == view->hiline)
4778 attr = A_STANDOUT;
4780 /* Set view->maxx based on full line length. */
4781 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4782 view->x ? 1 : 0);
4783 if (err) {
4784 free(line);
4785 return err;
4787 view->maxx = MAX(view->maxx, width);
4788 free(wline);
4789 wline = NULL;
4791 linetype = s->lines[s->lineno].type;
4792 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4793 linetype < GOT_DIFF_LINE_CONTEXT)
4794 attr |= COLOR_PAIR(linetype);
4795 if (attr)
4796 wattron(view->window, attr);
4797 if (s->first_displayed_line + nprinted == s->matched_line &&
4798 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4799 err = add_matched_line(&width, line, view->ncols, 0,
4800 view->window, view->x, regmatch);
4801 if (err) {
4802 free(line);
4803 return err;
4805 } else {
4806 int skip;
4807 err = format_line(&wline, &width, &skip, line,
4808 view->x, view->ncols, 0, view->x ? 1 : 0);
4809 if (err) {
4810 free(line);
4811 return err;
4813 waddwstr(view->window, &wline[skip]);
4814 free(wline);
4815 wline = NULL;
4817 if (s->lineno == view->hiline) {
4818 /* highlight full gline length */
4819 while (width++ < view->ncols)
4820 waddch(view->window, ' ');
4821 } else {
4822 if (width <= view->ncols - 1)
4823 waddch(view->window, '\n');
4825 if (attr)
4826 wattroff(view->window, attr);
4827 if (++nprinted == 1)
4828 s->first_displayed_line = s->lineno;
4830 free(line);
4831 if (nprinted >= 1)
4832 s->last_displayed_line = s->first_displayed_line +
4833 (nprinted - 1);
4834 else
4835 s->last_displayed_line = s->first_displayed_line;
4837 view_border(view);
4839 if (s->eof) {
4840 while (nprinted < view->nlines) {
4841 waddch(view->window, '\n');
4842 nprinted++;
4845 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4846 view->ncols, 0, 0);
4847 if (err) {
4848 return err;
4851 wstandout(view->window);
4852 waddwstr(view->window, wline);
4853 free(wline);
4854 wline = NULL;
4855 wstandend(view->window);
4858 return NULL;
4861 static char *
4862 get_datestr(time_t *time, char *datebuf)
4864 struct tm mytm, *tm;
4865 char *p, *s;
4867 tm = gmtime_r(time, &mytm);
4868 if (tm == NULL)
4869 return NULL;
4870 s = asctime_r(tm, datebuf);
4871 if (s == NULL)
4872 return NULL;
4873 p = strchr(s, '\n');
4874 if (p)
4875 *p = '\0';
4876 return s;
4879 static const struct got_error *
4880 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4881 off_t off, uint8_t type)
4883 struct got_diff_line *p;
4885 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4886 if (p == NULL)
4887 return got_error_from_errno("reallocarray");
4888 *lines = p;
4889 (*lines)[*nlines].offset = off;
4890 (*lines)[*nlines].type = type;
4891 (*nlines)++;
4893 return NULL;
4896 static const struct got_error *
4897 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4898 struct got_diff_line *s_lines, size_t s_nlines)
4900 struct got_diff_line *p;
4901 char buf[BUFSIZ];
4902 size_t i, r;
4904 if (fseeko(src, 0L, SEEK_SET) == -1)
4905 return got_error_from_errno("fseeko");
4907 for (;;) {
4908 r = fread(buf, 1, sizeof(buf), src);
4909 if (r == 0) {
4910 if (ferror(src))
4911 return got_error_from_errno("fread");
4912 if (feof(src))
4913 break;
4915 if (fwrite(buf, 1, r, dst) != r)
4916 return got_ferror(dst, GOT_ERR_IO);
4919 if (s_nlines == 0 && *d_nlines == 0)
4920 return NULL;
4923 * If commit info was in dst, increment line offsets
4924 * of the appended diff content, but skip s_lines[0]
4925 * because offset zero is already in *d_lines.
4927 if (*d_nlines > 0) {
4928 for (i = 1; i < s_nlines; ++i)
4929 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4931 if (s_nlines > 0) {
4932 --s_nlines;
4933 ++s_lines;
4937 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4938 if (p == NULL) {
4939 /* d_lines is freed in close_diff_view() */
4940 return got_error_from_errno("reallocarray");
4943 *d_lines = p;
4945 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4946 *d_nlines += s_nlines;
4948 return NULL;
4951 static const struct got_error *
4952 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4953 struct got_object_id *commit_id, struct got_reflist_head *refs,
4954 struct got_repository *repo, int ignore_ws, int force_text_diff,
4955 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4957 const struct got_error *err = NULL;
4958 char datebuf[26], *datestr;
4959 struct got_commit_object *commit;
4960 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4961 time_t committer_time;
4962 const char *author, *committer;
4963 char *refs_str = NULL;
4964 struct got_pathlist_entry *pe;
4965 off_t outoff = 0;
4966 int n;
4968 err = build_refs_str(&refs_str, refs, commit_id, repo);
4969 if (err)
4970 return err;
4972 err = got_object_open_as_commit(&commit, repo, commit_id);
4973 if (err)
4974 return err;
4976 err = got_object_id_str(&id_str, commit_id);
4977 if (err) {
4978 err = got_error_from_errno("got_object_id_str");
4979 goto done;
4982 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4983 if (err)
4984 goto done;
4986 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4987 refs_str ? refs_str : "", refs_str ? ")" : "");
4988 if (n < 0) {
4989 err = got_error_from_errno("fprintf");
4990 goto done;
4992 outoff += n;
4993 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4994 if (err)
4995 goto done;
4997 n = fprintf(outfile, "from: %s\n",
4998 got_object_commit_get_author(commit));
4999 if (n < 0) {
5000 err = got_error_from_errno("fprintf");
5001 goto done;
5003 outoff += n;
5004 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
5005 if (err)
5006 goto done;
5008 author = got_object_commit_get_author(commit);
5009 committer = got_object_commit_get_committer(commit);
5010 if (strcmp(author, committer) != 0) {
5011 n = fprintf(outfile, "via: %s\n", committer);
5012 if (n < 0) {
5013 err = got_error_from_errno("fprintf");
5014 goto done;
5016 outoff += n;
5017 err = add_line_metadata(lines, nlines, outoff,
5018 GOT_DIFF_LINE_AUTHOR);
5019 if (err)
5020 goto done;
5022 committer_time = got_object_commit_get_committer_time(commit);
5023 datestr = get_datestr(&committer_time, datebuf);
5024 if (datestr) {
5025 n = fprintf(outfile, "date: %s UTC\n", datestr);
5026 if (n < 0) {
5027 err = got_error_from_errno("fprintf");
5028 goto done;
5030 outoff += n;
5031 err = add_line_metadata(lines, nlines, outoff,
5032 GOT_DIFF_LINE_DATE);
5033 if (err)
5034 goto done;
5036 if (got_object_commit_get_nparents(commit) > 1) {
5037 const struct got_object_id_queue *parent_ids;
5038 struct got_object_qid *qid;
5039 int pn = 1;
5040 parent_ids = got_object_commit_get_parent_ids(commit);
5041 STAILQ_FOREACH(qid, parent_ids, entry) {
5042 err = got_object_id_str(&id_str, &qid->id);
5043 if (err)
5044 goto done;
5045 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5046 if (n < 0) {
5047 err = got_error_from_errno("fprintf");
5048 goto done;
5050 outoff += n;
5051 err = add_line_metadata(lines, nlines, outoff,
5052 GOT_DIFF_LINE_META);
5053 if (err)
5054 goto done;
5055 free(id_str);
5056 id_str = NULL;
5060 err = got_object_commit_get_logmsg(&logmsg, commit);
5061 if (err)
5062 goto done;
5063 s = logmsg;
5064 while ((line = strsep(&s, "\n")) != NULL) {
5065 n = fprintf(outfile, "%s\n", line);
5066 if (n < 0) {
5067 err = got_error_from_errno("fprintf");
5068 goto done;
5070 outoff += n;
5071 err = add_line_metadata(lines, nlines, outoff,
5072 GOT_DIFF_LINE_LOGMSG);
5073 if (err)
5074 goto done;
5077 TAILQ_FOREACH(pe, dsa->paths, entry) {
5078 struct got_diff_changed_path *cp = pe->data;
5079 int pad = dsa->max_path_len - pe->path_len + 1;
5081 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5082 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5083 dsa->rm_cols + 1, cp->rm);
5084 if (n < 0) {
5085 err = got_error_from_errno("fprintf");
5086 goto done;
5088 outoff += n;
5089 err = add_line_metadata(lines, nlines, outoff,
5090 GOT_DIFF_LINE_CHANGES);
5091 if (err)
5092 goto done;
5095 fputc('\n', outfile);
5096 outoff++;
5097 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5098 if (err)
5099 goto done;
5101 n = fprintf(outfile,
5102 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5103 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5104 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5105 if (n < 0) {
5106 err = got_error_from_errno("fprintf");
5107 goto done;
5109 outoff += n;
5110 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5111 if (err)
5112 goto done;
5114 fputc('\n', outfile);
5115 outoff++;
5116 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5117 done:
5118 free(id_str);
5119 free(logmsg);
5120 free(refs_str);
5121 got_object_commit_close(commit);
5122 if (err) {
5123 free(*lines);
5124 *lines = NULL;
5125 *nlines = 0;
5127 return err;
5130 static const struct got_error *
5131 create_diff(struct tog_diff_view_state *s)
5133 const struct got_error *err = NULL;
5134 FILE *f = NULL, *tmp_diff_file = NULL;
5135 int obj_type;
5136 struct got_diff_line *lines = NULL;
5137 struct got_pathlist_head changed_paths;
5139 TAILQ_INIT(&changed_paths);
5141 free(s->lines);
5142 s->lines = malloc(sizeof(*s->lines));
5143 if (s->lines == NULL)
5144 return got_error_from_errno("malloc");
5145 s->nlines = 0;
5147 f = got_opentemp();
5148 if (f == NULL) {
5149 err = got_error_from_errno("got_opentemp");
5150 goto done;
5152 tmp_diff_file = got_opentemp();
5153 if (tmp_diff_file == NULL) {
5154 err = got_error_from_errno("got_opentemp");
5155 goto done;
5157 if (s->f && fclose(s->f) == EOF) {
5158 err = got_error_from_errno("fclose");
5159 goto done;
5161 s->f = f;
5163 if (s->id1)
5164 err = got_object_get_type(&obj_type, s->repo, s->id1);
5165 else
5166 err = got_object_get_type(&obj_type, s->repo, s->id2);
5167 if (err)
5168 goto done;
5170 switch (obj_type) {
5171 case GOT_OBJ_TYPE_BLOB:
5172 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5173 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5174 s->label1, s->label2, tog_diff_algo, s->diff_context,
5175 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5176 s->f);
5177 break;
5178 case GOT_OBJ_TYPE_TREE:
5179 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5180 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5181 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5182 s->force_text_diff, NULL, s->repo, s->f);
5183 break;
5184 case GOT_OBJ_TYPE_COMMIT: {
5185 const struct got_object_id_queue *parent_ids;
5186 struct got_object_qid *pid;
5187 struct got_commit_object *commit2;
5188 struct got_reflist_head *refs;
5189 size_t nlines = 0;
5190 struct got_diffstat_cb_arg dsa = {
5191 0, 0, 0, 0, 0, 0,
5192 &changed_paths,
5193 s->ignore_whitespace,
5194 s->force_text_diff,
5195 tog_diff_algo
5198 lines = malloc(sizeof(*lines));
5199 if (lines == NULL) {
5200 err = got_error_from_errno("malloc");
5201 goto done;
5204 /* build diff first in tmp file then append to commit info */
5205 err = got_diff_objects_as_commits(&lines, &nlines,
5206 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5207 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5208 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5209 if (err)
5210 break;
5212 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5213 if (err)
5214 goto done;
5215 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5216 /* Show commit info if we're diffing to a parent/root commit. */
5217 if (s->id1 == NULL) {
5218 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5219 refs, s->repo, s->ignore_whitespace,
5220 s->force_text_diff, &dsa, s->f);
5221 if (err)
5222 goto done;
5223 } else {
5224 parent_ids = got_object_commit_get_parent_ids(commit2);
5225 STAILQ_FOREACH(pid, parent_ids, entry) {
5226 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5227 err = write_commit_info(&s->lines,
5228 &s->nlines, s->id2, refs, s->repo,
5229 s->ignore_whitespace,
5230 s->force_text_diff, &dsa, s->f);
5231 if (err)
5232 goto done;
5233 break;
5237 got_object_commit_close(commit2);
5239 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5240 lines, nlines);
5241 break;
5243 default:
5244 err = got_error(GOT_ERR_OBJ_TYPE);
5245 break;
5247 done:
5248 free(lines);
5249 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5250 if (s->f && fflush(s->f) != 0 && err == NULL)
5251 err = got_error_from_errno("fflush");
5252 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5253 err = got_error_from_errno("fclose");
5254 return err;
5257 static void
5258 diff_view_indicate_progress(struct tog_view *view)
5260 mvwaddstr(view->window, 0, 0, "diffing...");
5261 update_panels();
5262 doupdate();
5265 static const struct got_error *
5266 search_start_diff_view(struct tog_view *view)
5268 struct tog_diff_view_state *s = &view->state.diff;
5270 s->matched_line = 0;
5271 return NULL;
5274 static void
5275 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5276 size_t *nlines, int **first, int **last, int **match, int **selected)
5278 struct tog_diff_view_state *s = &view->state.diff;
5280 *f = s->f;
5281 *nlines = s->nlines;
5282 *line_offsets = NULL;
5283 *match = &s->matched_line;
5284 *first = &s->first_displayed_line;
5285 *last = &s->last_displayed_line;
5286 *selected = &s->selected_line;
5289 static const struct got_error *
5290 search_next_view_match(struct tog_view *view)
5292 const struct got_error *err = NULL;
5293 FILE *f;
5294 int lineno;
5295 char *line = NULL;
5296 size_t linesize = 0;
5297 ssize_t linelen;
5298 off_t *line_offsets;
5299 size_t nlines = 0;
5300 int *first, *last, *match, *selected;
5302 if (!view->search_setup)
5303 return got_error_msg(GOT_ERR_NOT_IMPL,
5304 "view search not supported");
5305 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5306 &match, &selected);
5308 if (!view->searching) {
5309 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5310 return NULL;
5313 if (*match) {
5314 if (view->searching == TOG_SEARCH_FORWARD)
5315 lineno = *first + 1;
5316 else
5317 lineno = *first - 1;
5318 } else
5319 lineno = *first - 1 + *selected;
5321 while (1) {
5322 off_t offset;
5324 if (lineno <= 0 || lineno > nlines) {
5325 if (*match == 0) {
5326 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5327 break;
5330 if (view->searching == TOG_SEARCH_FORWARD)
5331 lineno = 1;
5332 else
5333 lineno = nlines;
5336 offset = view->type == TOG_VIEW_DIFF ?
5337 view->state.diff.lines[lineno - 1].offset :
5338 line_offsets[lineno - 1];
5339 if (fseeko(f, offset, SEEK_SET) != 0) {
5340 free(line);
5341 return got_error_from_errno("fseeko");
5343 linelen = getline(&line, &linesize, f);
5344 if (linelen != -1) {
5345 char *exstr;
5346 err = expand_tab(&exstr, line);
5347 if (err)
5348 break;
5349 if (match_line(exstr, &view->regex, 1,
5350 &view->regmatch)) {
5351 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5352 *match = lineno;
5353 free(exstr);
5354 break;
5356 free(exstr);
5358 if (view->searching == TOG_SEARCH_FORWARD)
5359 lineno++;
5360 else
5361 lineno--;
5363 free(line);
5365 if (*match) {
5366 *first = *match;
5367 *selected = 1;
5370 return err;
5373 static const struct got_error *
5374 close_diff_view(struct tog_view *view)
5376 const struct got_error *err = NULL;
5377 struct tog_diff_view_state *s = &view->state.diff;
5379 free(s->id1);
5380 s->id1 = NULL;
5381 free(s->id2);
5382 s->id2 = NULL;
5383 if (s->f && fclose(s->f) == EOF)
5384 err = got_error_from_errno("fclose");
5385 s->f = NULL;
5386 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5387 err = got_error_from_errno("fclose");
5388 s->f1 = NULL;
5389 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5390 err = got_error_from_errno("fclose");
5391 s->f2 = NULL;
5392 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5393 err = got_error_from_errno("close");
5394 s->fd1 = -1;
5395 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5396 err = got_error_from_errno("close");
5397 s->fd2 = -1;
5398 free(s->lines);
5399 s->lines = NULL;
5400 s->nlines = 0;
5401 return err;
5404 static const struct got_error *
5405 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5406 struct got_object_id *id2, const char *label1, const char *label2,
5407 int diff_context, int ignore_whitespace, int force_text_diff,
5408 struct tog_view *parent_view, struct got_repository *repo)
5410 const struct got_error *err;
5411 struct tog_diff_view_state *s = &view->state.diff;
5413 memset(s, 0, sizeof(*s));
5414 s->fd1 = -1;
5415 s->fd2 = -1;
5417 if (id1 != NULL && id2 != NULL) {
5418 int type1, type2;
5420 err = got_object_get_type(&type1, repo, id1);
5421 if (err)
5422 goto done;
5423 err = got_object_get_type(&type2, repo, id2);
5424 if (err)
5425 goto done;
5427 if (type1 != type2) {
5428 err = got_error(GOT_ERR_OBJ_TYPE);
5429 goto done;
5432 s->first_displayed_line = 1;
5433 s->last_displayed_line = view->nlines;
5434 s->selected_line = 1;
5435 s->repo = repo;
5436 s->id1 = id1;
5437 s->id2 = id2;
5438 s->label1 = label1;
5439 s->label2 = label2;
5441 if (id1) {
5442 s->id1 = got_object_id_dup(id1);
5443 if (s->id1 == NULL) {
5444 err = got_error_from_errno("got_object_id_dup");
5445 goto done;
5447 } else
5448 s->id1 = NULL;
5450 s->id2 = got_object_id_dup(id2);
5451 if (s->id2 == NULL) {
5452 err = got_error_from_errno("got_object_id_dup");
5453 goto done;
5456 s->f1 = got_opentemp();
5457 if (s->f1 == NULL) {
5458 err = got_error_from_errno("got_opentemp");
5459 goto done;
5462 s->f2 = got_opentemp();
5463 if (s->f2 == NULL) {
5464 err = got_error_from_errno("got_opentemp");
5465 goto done;
5468 s->fd1 = got_opentempfd();
5469 if (s->fd1 == -1) {
5470 err = got_error_from_errno("got_opentempfd");
5471 goto done;
5474 s->fd2 = got_opentempfd();
5475 if (s->fd2 == -1) {
5476 err = got_error_from_errno("got_opentempfd");
5477 goto done;
5480 s->diff_context = diff_context;
5481 s->ignore_whitespace = ignore_whitespace;
5482 s->force_text_diff = force_text_diff;
5483 s->parent_view = parent_view;
5484 s->repo = repo;
5486 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5487 int rc;
5489 rc = init_pair(GOT_DIFF_LINE_MINUS,
5490 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5491 if (rc != ERR)
5492 rc = init_pair(GOT_DIFF_LINE_PLUS,
5493 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5494 if (rc != ERR)
5495 rc = init_pair(GOT_DIFF_LINE_HUNK,
5496 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5497 if (rc != ERR)
5498 rc = init_pair(GOT_DIFF_LINE_META,
5499 get_color_value("TOG_COLOR_DIFF_META"), -1);
5500 if (rc != ERR)
5501 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5502 get_color_value("TOG_COLOR_DIFF_META"), -1);
5503 if (rc != ERR)
5504 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5505 get_color_value("TOG_COLOR_DIFF_META"), -1);
5506 if (rc != ERR)
5507 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5508 get_color_value("TOG_COLOR_DIFF_META"), -1);
5509 if (rc != ERR)
5510 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5511 get_color_value("TOG_COLOR_AUTHOR"), -1);
5512 if (rc != ERR)
5513 rc = init_pair(GOT_DIFF_LINE_DATE,
5514 get_color_value("TOG_COLOR_DATE"), -1);
5515 if (rc == ERR) {
5516 err = got_error(GOT_ERR_RANGE);
5517 goto done;
5521 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5522 view_is_splitscreen(view))
5523 show_log_view(parent_view); /* draw border */
5524 diff_view_indicate_progress(view);
5526 err = create_diff(s);
5528 view->show = show_diff_view;
5529 view->input = input_diff_view;
5530 view->reset = reset_diff_view;
5531 view->close = close_diff_view;
5532 view->search_start = search_start_diff_view;
5533 view->search_setup = search_setup_diff_view;
5534 view->search_next = search_next_view_match;
5535 done:
5536 if (err) {
5537 if (view->close == NULL)
5538 close_diff_view(view);
5539 view_close(view);
5541 return err;
5544 static const struct got_error *
5545 show_diff_view(struct tog_view *view)
5547 const struct got_error *err;
5548 struct tog_diff_view_state *s = &view->state.diff;
5549 char *id_str1 = NULL, *id_str2, *header;
5550 const char *label1, *label2;
5552 if (s->id1) {
5553 err = got_object_id_str(&id_str1, s->id1);
5554 if (err)
5555 return err;
5556 label1 = s->label1 ? s->label1 : id_str1;
5557 } else
5558 label1 = "/dev/null";
5560 err = got_object_id_str(&id_str2, s->id2);
5561 if (err)
5562 return err;
5563 label2 = s->label2 ? s->label2 : id_str2;
5565 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5566 err = got_error_from_errno("asprintf");
5567 free(id_str1);
5568 free(id_str2);
5569 return err;
5571 free(id_str1);
5572 free(id_str2);
5574 err = draw_file(view, header);
5575 free(header);
5576 return err;
5579 static const struct got_error *
5580 set_selected_commit(struct tog_diff_view_state *s,
5581 struct commit_queue_entry *entry)
5583 const struct got_error *err;
5584 const struct got_object_id_queue *parent_ids;
5585 struct got_commit_object *selected_commit;
5586 struct got_object_qid *pid;
5588 free(s->id2);
5589 s->id2 = got_object_id_dup(entry->id);
5590 if (s->id2 == NULL)
5591 return got_error_from_errno("got_object_id_dup");
5593 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5594 if (err)
5595 return err;
5596 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5597 free(s->id1);
5598 pid = STAILQ_FIRST(parent_ids);
5599 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5600 got_object_commit_close(selected_commit);
5601 return NULL;
5604 static const struct got_error *
5605 reset_diff_view(struct tog_view *view)
5607 struct tog_diff_view_state *s = &view->state.diff;
5609 view->count = 0;
5610 wclear(view->window);
5611 s->first_displayed_line = 1;
5612 s->last_displayed_line = view->nlines;
5613 s->matched_line = 0;
5614 diff_view_indicate_progress(view);
5615 return create_diff(s);
5618 static void
5619 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5621 int start, i;
5623 i = start = s->first_displayed_line - 1;
5625 while (s->lines[i].type != type) {
5626 if (i == 0)
5627 i = s->nlines - 1;
5628 if (--i == start)
5629 return; /* do nothing, requested type not in file */
5632 s->selected_line = 1;
5633 s->first_displayed_line = i;
5636 static void
5637 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5639 int start, i;
5641 i = start = s->first_displayed_line + 1;
5643 while (s->lines[i].type != type) {
5644 if (i == s->nlines - 1)
5645 i = 0;
5646 if (++i == start)
5647 return; /* do nothing, requested type not in file */
5650 s->selected_line = 1;
5651 s->first_displayed_line = i;
5654 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5655 int, int, int);
5656 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5657 int, int);
5659 static const struct got_error *
5660 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5662 const struct got_error *err = NULL;
5663 struct tog_diff_view_state *s = &view->state.diff;
5664 struct tog_log_view_state *ls;
5665 struct commit_queue_entry *old_selected_entry;
5666 char *line = NULL;
5667 size_t linesize = 0;
5668 ssize_t linelen;
5669 int i, nscroll = view->nlines - 1, up = 0;
5671 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5673 switch (ch) {
5674 case '0':
5675 case '$':
5676 case KEY_RIGHT:
5677 case 'l':
5678 case KEY_LEFT:
5679 case 'h':
5680 horizontal_scroll_input(view, ch);
5681 break;
5682 case 'a':
5683 case 'w':
5684 if (ch == 'a') {
5685 s->force_text_diff = !s->force_text_diff;
5686 view->action = s->force_text_diff ?
5687 "force ASCII text enabled" :
5688 "force ASCII text disabled";
5690 else if (ch == 'w') {
5691 s->ignore_whitespace = !s->ignore_whitespace;
5692 view->action = s->ignore_whitespace ?
5693 "ignore whitespace enabled" :
5694 "ignore whitespace disabled";
5696 err = reset_diff_view(view);
5697 break;
5698 case 'g':
5699 case KEY_HOME:
5700 s->first_displayed_line = 1;
5701 view->count = 0;
5702 break;
5703 case 'G':
5704 case KEY_END:
5705 view->count = 0;
5706 if (s->eof)
5707 break;
5709 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5710 s->eof = 1;
5711 break;
5712 case 'k':
5713 case KEY_UP:
5714 case CTRL('p'):
5715 if (s->first_displayed_line > 1)
5716 s->first_displayed_line--;
5717 else
5718 view->count = 0;
5719 break;
5720 case CTRL('u'):
5721 case 'u':
5722 nscroll /= 2;
5723 /* FALL THROUGH */
5724 case KEY_PPAGE:
5725 case CTRL('b'):
5726 case 'b':
5727 if (s->first_displayed_line == 1) {
5728 view->count = 0;
5729 break;
5731 i = 0;
5732 while (i++ < nscroll && s->first_displayed_line > 1)
5733 s->first_displayed_line--;
5734 break;
5735 case 'j':
5736 case KEY_DOWN:
5737 case CTRL('n'):
5738 if (!s->eof)
5739 s->first_displayed_line++;
5740 else
5741 view->count = 0;
5742 break;
5743 case CTRL('d'):
5744 case 'd':
5745 nscroll /= 2;
5746 /* FALL THROUGH */
5747 case KEY_NPAGE:
5748 case CTRL('f'):
5749 case 'f':
5750 case ' ':
5751 if (s->eof) {
5752 view->count = 0;
5753 break;
5755 i = 0;
5756 while (!s->eof && i++ < nscroll) {
5757 linelen = getline(&line, &linesize, s->f);
5758 s->first_displayed_line++;
5759 if (linelen == -1) {
5760 if (feof(s->f)) {
5761 s->eof = 1;
5762 } else
5763 err = got_ferror(s->f, GOT_ERR_IO);
5764 break;
5767 free(line);
5768 break;
5769 case '(':
5770 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5771 break;
5772 case ')':
5773 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5774 break;
5775 case '{':
5776 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5777 break;
5778 case '}':
5779 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5780 break;
5781 case '[':
5782 if (s->diff_context > 0) {
5783 s->diff_context--;
5784 s->matched_line = 0;
5785 diff_view_indicate_progress(view);
5786 err = create_diff(s);
5787 if (s->first_displayed_line + view->nlines - 1 >
5788 s->nlines) {
5789 s->first_displayed_line = 1;
5790 s->last_displayed_line = view->nlines;
5792 } else
5793 view->count = 0;
5794 break;
5795 case ']':
5796 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5797 s->diff_context++;
5798 s->matched_line = 0;
5799 diff_view_indicate_progress(view);
5800 err = create_diff(s);
5801 } else
5802 view->count = 0;
5803 break;
5804 case '<':
5805 case ',':
5806 case 'K':
5807 up = 1;
5808 /* FALL THROUGH */
5809 case '>':
5810 case '.':
5811 case 'J':
5812 if (s->parent_view == NULL) {
5813 view->count = 0;
5814 break;
5816 s->parent_view->count = view->count;
5818 if (s->parent_view->type == TOG_VIEW_LOG) {
5819 ls = &s->parent_view->state.log;
5820 old_selected_entry = ls->selected_entry;
5822 err = input_log_view(NULL, s->parent_view,
5823 up ? KEY_UP : KEY_DOWN);
5824 if (err)
5825 break;
5826 view->count = s->parent_view->count;
5828 if (old_selected_entry == ls->selected_entry)
5829 break;
5831 err = set_selected_commit(s, ls->selected_entry);
5832 if (err)
5833 break;
5834 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5835 struct tog_blame_view_state *bs;
5836 struct got_object_id *id, *prev_id;
5838 bs = &s->parent_view->state.blame;
5839 prev_id = get_annotation_for_line(bs->blame.lines,
5840 bs->blame.nlines, bs->last_diffed_line);
5842 err = input_blame_view(&view, s->parent_view,
5843 up ? KEY_UP : KEY_DOWN);
5844 if (err)
5845 break;
5846 view->count = s->parent_view->count;
5848 if (prev_id == NULL)
5849 break;
5850 id = get_selected_commit_id(bs->blame.lines,
5851 bs->blame.nlines, bs->first_displayed_line,
5852 bs->selected_line);
5853 if (id == NULL)
5854 break;
5856 if (!got_object_id_cmp(prev_id, id))
5857 break;
5859 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5860 if (err)
5861 break;
5863 s->first_displayed_line = 1;
5864 s->last_displayed_line = view->nlines;
5865 s->matched_line = 0;
5866 view->x = 0;
5868 diff_view_indicate_progress(view);
5869 err = create_diff(s);
5870 break;
5871 default:
5872 view->count = 0;
5873 break;
5876 return err;
5879 static const struct got_error *
5880 cmd_diff(int argc, char *argv[])
5882 const struct got_error *error;
5883 struct got_repository *repo = NULL;
5884 struct got_worktree *worktree = NULL;
5885 struct got_object_id *id1 = NULL, *id2 = NULL;
5886 char *repo_path = NULL, *cwd = NULL;
5887 char *id_str1 = NULL, *id_str2 = NULL;
5888 char *label1 = NULL, *label2 = NULL;
5889 int diff_context = 3, ignore_whitespace = 0;
5890 int ch, force_text_diff = 0;
5891 const char *errstr;
5892 struct tog_view *view;
5893 int *pack_fds = NULL;
5895 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5896 switch (ch) {
5897 case 'a':
5898 force_text_diff = 1;
5899 break;
5900 case 'C':
5901 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5902 &errstr);
5903 if (errstr != NULL)
5904 errx(1, "number of context lines is %s: %s",
5905 errstr, errstr);
5906 break;
5907 case 'r':
5908 repo_path = realpath(optarg, NULL);
5909 if (repo_path == NULL)
5910 return got_error_from_errno2("realpath",
5911 optarg);
5912 got_path_strip_trailing_slashes(repo_path);
5913 break;
5914 case 'w':
5915 ignore_whitespace = 1;
5916 break;
5917 default:
5918 usage_diff();
5919 /* NOTREACHED */
5923 argc -= optind;
5924 argv += optind;
5926 if (argc == 0) {
5927 usage_diff(); /* TODO show local worktree changes */
5928 } else if (argc == 2) {
5929 id_str1 = argv[0];
5930 id_str2 = argv[1];
5931 } else
5932 usage_diff();
5934 error = got_repo_pack_fds_open(&pack_fds);
5935 if (error)
5936 goto done;
5938 if (repo_path == NULL) {
5939 cwd = getcwd(NULL, 0);
5940 if (cwd == NULL)
5941 return got_error_from_errno("getcwd");
5942 error = got_worktree_open(&worktree, cwd);
5943 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5944 goto done;
5945 if (worktree)
5946 repo_path =
5947 strdup(got_worktree_get_repo_path(worktree));
5948 else
5949 repo_path = strdup(cwd);
5950 if (repo_path == NULL) {
5951 error = got_error_from_errno("strdup");
5952 goto done;
5956 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5957 if (error)
5958 goto done;
5960 init_curses();
5962 error = apply_unveil(got_repo_get_path(repo), NULL);
5963 if (error)
5964 goto done;
5966 error = tog_load_refs(repo, 0);
5967 if (error)
5968 goto done;
5970 error = got_repo_match_object_id(&id1, &label1, id_str1,
5971 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5972 if (error)
5973 goto done;
5975 error = got_repo_match_object_id(&id2, &label2, id_str2,
5976 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5977 if (error)
5978 goto done;
5980 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5981 if (view == NULL) {
5982 error = got_error_from_errno("view_open");
5983 goto done;
5985 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5986 ignore_whitespace, force_text_diff, NULL, repo);
5987 if (error)
5988 goto done;
5989 error = view_loop(view);
5990 done:
5991 free(label1);
5992 free(label2);
5993 free(repo_path);
5994 free(cwd);
5995 if (repo) {
5996 const struct got_error *close_err = got_repo_close(repo);
5997 if (error == NULL)
5998 error = close_err;
6000 if (worktree)
6001 got_worktree_close(worktree);
6002 if (pack_fds) {
6003 const struct got_error *pack_err =
6004 got_repo_pack_fds_close(pack_fds);
6005 if (error == NULL)
6006 error = pack_err;
6008 tog_free_refs();
6009 return error;
6012 __dead static void
6013 usage_blame(void)
6015 endwin();
6016 fprintf(stderr,
6017 "usage: %s blame [-c commit] [-r repository-path] path\n",
6018 getprogname());
6019 exit(1);
6022 struct tog_blame_line {
6023 int annotated;
6024 struct got_object_id *id;
6027 static const struct got_error *
6028 draw_blame(struct tog_view *view)
6030 struct tog_blame_view_state *s = &view->state.blame;
6031 struct tog_blame *blame = &s->blame;
6032 regmatch_t *regmatch = &view->regmatch;
6033 const struct got_error *err;
6034 int lineno = 0, nprinted = 0;
6035 char *line = NULL;
6036 size_t linesize = 0;
6037 ssize_t linelen;
6038 wchar_t *wline;
6039 int width;
6040 struct tog_blame_line *blame_line;
6041 struct got_object_id *prev_id = NULL;
6042 char *id_str;
6043 struct tog_color *tc;
6045 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6046 if (err)
6047 return err;
6049 rewind(blame->f);
6050 werase(view->window);
6052 if (asprintf(&line, "commit %s", id_str) == -1) {
6053 err = got_error_from_errno("asprintf");
6054 free(id_str);
6055 return err;
6058 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6059 free(line);
6060 line = NULL;
6061 if (err)
6062 return err;
6063 if (view_needs_focus_indication(view))
6064 wstandout(view->window);
6065 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6066 if (tc)
6067 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6068 waddwstr(view->window, wline);
6069 while (width++ < view->ncols)
6070 waddch(view->window, ' ');
6071 if (tc)
6072 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6073 if (view_needs_focus_indication(view))
6074 wstandend(view->window);
6075 free(wline);
6076 wline = NULL;
6078 if (view->gline > blame->nlines)
6079 view->gline = blame->nlines;
6081 if (tog_io.wait_for_ui) {
6082 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6083 int rc;
6085 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6086 if (rc)
6087 return got_error_set_errno(rc, "pthread_cond_wait");
6088 tog_io.wait_for_ui = 0;
6091 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6092 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6093 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6094 free(id_str);
6095 return got_error_from_errno("asprintf");
6097 free(id_str);
6098 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6099 free(line);
6100 line = NULL;
6101 if (err)
6102 return err;
6103 waddwstr(view->window, wline);
6104 free(wline);
6105 wline = NULL;
6106 if (width < view->ncols - 1)
6107 waddch(view->window, '\n');
6109 s->eof = 0;
6110 view->maxx = 0;
6111 while (nprinted < view->nlines - 2) {
6112 linelen = getline(&line, &linesize, blame->f);
6113 if (linelen == -1) {
6114 if (feof(blame->f)) {
6115 s->eof = 1;
6116 break;
6118 free(line);
6119 return got_ferror(blame->f, GOT_ERR_IO);
6121 if (++lineno < s->first_displayed_line)
6122 continue;
6123 if (view->gline && !gotoline(view, &lineno, &nprinted))
6124 continue;
6126 /* Set view->maxx based on full line length. */
6127 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6128 if (err) {
6129 free(line);
6130 return err;
6132 free(wline);
6133 wline = NULL;
6134 view->maxx = MAX(view->maxx, width);
6136 if (nprinted == s->selected_line - 1)
6137 wstandout(view->window);
6139 if (blame->nlines > 0) {
6140 blame_line = &blame->lines[lineno - 1];
6141 if (blame_line->annotated && prev_id &&
6142 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6143 !(nprinted == s->selected_line - 1)) {
6144 waddstr(view->window, " ");
6145 } else if (blame_line->annotated) {
6146 char *id_str;
6147 err = got_object_id_str(&id_str,
6148 blame_line->id);
6149 if (err) {
6150 free(line);
6151 return err;
6153 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6154 if (tc)
6155 wattr_on(view->window,
6156 COLOR_PAIR(tc->colorpair), NULL);
6157 wprintw(view->window, "%.8s", id_str);
6158 if (tc)
6159 wattr_off(view->window,
6160 COLOR_PAIR(tc->colorpair), NULL);
6161 free(id_str);
6162 prev_id = blame_line->id;
6163 } else {
6164 waddstr(view->window, "........");
6165 prev_id = NULL;
6167 } else {
6168 waddstr(view->window, "........");
6169 prev_id = NULL;
6172 if (nprinted == s->selected_line - 1)
6173 wstandend(view->window);
6174 waddstr(view->window, " ");
6176 if (view->ncols <= 9) {
6177 width = 9;
6178 } else if (s->first_displayed_line + nprinted ==
6179 s->matched_line &&
6180 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6181 err = add_matched_line(&width, line, view->ncols - 9, 9,
6182 view->window, view->x, regmatch);
6183 if (err) {
6184 free(line);
6185 return err;
6187 width += 9;
6188 } else {
6189 int skip;
6190 err = format_line(&wline, &width, &skip, line,
6191 view->x, view->ncols - 9, 9, 1);
6192 if (err) {
6193 free(line);
6194 return err;
6196 waddwstr(view->window, &wline[skip]);
6197 width += 9;
6198 free(wline);
6199 wline = NULL;
6202 if (width <= view->ncols - 1)
6203 waddch(view->window, '\n');
6204 if (++nprinted == 1)
6205 s->first_displayed_line = lineno;
6207 free(line);
6208 s->last_displayed_line = lineno;
6210 view_border(view);
6212 return NULL;
6215 static const struct got_error *
6216 blame_cb(void *arg, int nlines, int lineno,
6217 struct got_commit_object *commit, struct got_object_id *id)
6219 const struct got_error *err = NULL;
6220 struct tog_blame_cb_args *a = arg;
6221 struct tog_blame_line *line;
6222 int errcode;
6224 if (nlines != a->nlines ||
6225 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6226 return got_error(GOT_ERR_RANGE);
6228 errcode = pthread_mutex_lock(&tog_mutex);
6229 if (errcode)
6230 return got_error_set_errno(errcode, "pthread_mutex_lock");
6232 if (*a->quit) { /* user has quit the blame view */
6233 err = got_error(GOT_ERR_ITER_COMPLETED);
6234 goto done;
6237 if (lineno == -1)
6238 goto done; /* no change in this commit */
6240 line = &a->lines[lineno - 1];
6241 if (line->annotated)
6242 goto done;
6244 line->id = got_object_id_dup(id);
6245 if (line->id == NULL) {
6246 err = got_error_from_errno("got_object_id_dup");
6247 goto done;
6249 line->annotated = 1;
6250 done:
6251 errcode = pthread_mutex_unlock(&tog_mutex);
6252 if (errcode)
6253 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6254 return err;
6257 static void *
6258 blame_thread(void *arg)
6260 const struct got_error *err, *close_err;
6261 struct tog_blame_thread_args *ta = arg;
6262 struct tog_blame_cb_args *a = ta->cb_args;
6263 int errcode, fd1 = -1, fd2 = -1;
6264 FILE *f1 = NULL, *f2 = NULL;
6266 fd1 = got_opentempfd();
6267 if (fd1 == -1)
6268 return (void *)got_error_from_errno("got_opentempfd");
6270 fd2 = got_opentempfd();
6271 if (fd2 == -1) {
6272 err = got_error_from_errno("got_opentempfd");
6273 goto done;
6276 f1 = got_opentemp();
6277 if (f1 == NULL) {
6278 err = (void *)got_error_from_errno("got_opentemp");
6279 goto done;
6281 f2 = got_opentemp();
6282 if (f2 == NULL) {
6283 err = (void *)got_error_from_errno("got_opentemp");
6284 goto done;
6287 err = block_signals_used_by_main_thread();
6288 if (err)
6289 goto done;
6291 err = got_blame(ta->path, a->commit_id, ta->repo,
6292 tog_diff_algo, blame_cb, ta->cb_args,
6293 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6294 if (err && err->code == GOT_ERR_CANCELLED)
6295 err = NULL;
6297 errcode = pthread_mutex_lock(&tog_mutex);
6298 if (errcode) {
6299 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6300 goto done;
6303 close_err = got_repo_close(ta->repo);
6304 if (err == NULL)
6305 err = close_err;
6306 ta->repo = NULL;
6307 *ta->complete = 1;
6309 if (tog_io.wait_for_ui) {
6310 errcode = pthread_cond_signal(&ta->blame_complete);
6311 if (errcode && err == NULL)
6312 err = got_error_set_errno(errcode,
6313 "pthread_cond_signal");
6316 errcode = pthread_mutex_unlock(&tog_mutex);
6317 if (errcode && err == NULL)
6318 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6320 done:
6321 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6322 err = got_error_from_errno("close");
6323 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6324 err = got_error_from_errno("close");
6325 if (f1 && fclose(f1) == EOF && err == NULL)
6326 err = got_error_from_errno("fclose");
6327 if (f2 && fclose(f2) == EOF && err == NULL)
6328 err = got_error_from_errno("fclose");
6330 return (void *)err;
6333 static struct got_object_id *
6334 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6335 int first_displayed_line, int selected_line)
6337 struct tog_blame_line *line;
6339 if (nlines <= 0)
6340 return NULL;
6342 line = &lines[first_displayed_line - 1 + selected_line - 1];
6343 if (!line->annotated)
6344 return NULL;
6346 return line->id;
6349 static struct got_object_id *
6350 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6351 int lineno)
6353 struct tog_blame_line *line;
6355 if (nlines <= 0 || lineno >= nlines)
6356 return NULL;
6358 line = &lines[lineno - 1];
6359 if (!line->annotated)
6360 return NULL;
6362 return line->id;
6365 static const struct got_error *
6366 stop_blame(struct tog_blame *blame)
6368 const struct got_error *err = NULL;
6369 int i;
6371 if (blame->thread) {
6372 int errcode;
6373 errcode = pthread_mutex_unlock(&tog_mutex);
6374 if (errcode)
6375 return got_error_set_errno(errcode,
6376 "pthread_mutex_unlock");
6377 errcode = pthread_join(blame->thread, (void **)&err);
6378 if (errcode)
6379 return got_error_set_errno(errcode, "pthread_join");
6380 errcode = pthread_mutex_lock(&tog_mutex);
6381 if (errcode)
6382 return got_error_set_errno(errcode,
6383 "pthread_mutex_lock");
6384 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6385 err = NULL;
6386 blame->thread = NULL;
6388 if (blame->thread_args.repo) {
6389 const struct got_error *close_err;
6390 close_err = got_repo_close(blame->thread_args.repo);
6391 if (err == NULL)
6392 err = close_err;
6393 blame->thread_args.repo = NULL;
6395 if (blame->f) {
6396 if (fclose(blame->f) == EOF && err == NULL)
6397 err = got_error_from_errno("fclose");
6398 blame->f = NULL;
6400 if (blame->lines) {
6401 for (i = 0; i < blame->nlines; i++)
6402 free(blame->lines[i].id);
6403 free(blame->lines);
6404 blame->lines = NULL;
6406 free(blame->cb_args.commit_id);
6407 blame->cb_args.commit_id = NULL;
6408 if (blame->pack_fds) {
6409 const struct got_error *pack_err =
6410 got_repo_pack_fds_close(blame->pack_fds);
6411 if (err == NULL)
6412 err = pack_err;
6413 blame->pack_fds = NULL;
6415 return err;
6418 static const struct got_error *
6419 cancel_blame_view(void *arg)
6421 const struct got_error *err = NULL;
6422 int *done = arg;
6423 int errcode;
6425 errcode = pthread_mutex_lock(&tog_mutex);
6426 if (errcode)
6427 return got_error_set_errno(errcode,
6428 "pthread_mutex_unlock");
6430 if (*done)
6431 err = got_error(GOT_ERR_CANCELLED);
6433 errcode = pthread_mutex_unlock(&tog_mutex);
6434 if (errcode)
6435 return got_error_set_errno(errcode,
6436 "pthread_mutex_lock");
6438 return err;
6441 static const struct got_error *
6442 run_blame(struct tog_view *view)
6444 struct tog_blame_view_state *s = &view->state.blame;
6445 struct tog_blame *blame = &s->blame;
6446 const struct got_error *err = NULL;
6447 struct got_commit_object *commit = NULL;
6448 struct got_blob_object *blob = NULL;
6449 struct got_repository *thread_repo = NULL;
6450 struct got_object_id *obj_id = NULL;
6451 int obj_type, fd = -1;
6452 int *pack_fds = NULL;
6454 err = got_object_open_as_commit(&commit, s->repo,
6455 &s->blamed_commit->id);
6456 if (err)
6457 return err;
6459 fd = got_opentempfd();
6460 if (fd == -1) {
6461 err = got_error_from_errno("got_opentempfd");
6462 goto done;
6465 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6466 if (err)
6467 goto done;
6469 err = got_object_get_type(&obj_type, s->repo, obj_id);
6470 if (err)
6471 goto done;
6473 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6474 err = got_error(GOT_ERR_OBJ_TYPE);
6475 goto done;
6478 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6479 if (err)
6480 goto done;
6481 blame->f = got_opentemp();
6482 if (blame->f == NULL) {
6483 err = got_error_from_errno("got_opentemp");
6484 goto done;
6486 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6487 &blame->line_offsets, blame->f, blob);
6488 if (err)
6489 goto done;
6490 if (blame->nlines == 0) {
6491 s->blame_complete = 1;
6492 goto done;
6495 /* Don't include \n at EOF in the blame line count. */
6496 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6497 blame->nlines--;
6499 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6500 if (blame->lines == NULL) {
6501 err = got_error_from_errno("calloc");
6502 goto done;
6505 err = got_repo_pack_fds_open(&pack_fds);
6506 if (err)
6507 goto done;
6508 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6509 pack_fds);
6510 if (err)
6511 goto done;
6513 blame->pack_fds = pack_fds;
6514 blame->cb_args.view = view;
6515 blame->cb_args.lines = blame->lines;
6516 blame->cb_args.nlines = blame->nlines;
6517 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6518 if (blame->cb_args.commit_id == NULL) {
6519 err = got_error_from_errno("got_object_id_dup");
6520 goto done;
6522 blame->cb_args.quit = &s->done;
6524 blame->thread_args.path = s->path;
6525 blame->thread_args.repo = thread_repo;
6526 blame->thread_args.cb_args = &blame->cb_args;
6527 blame->thread_args.complete = &s->blame_complete;
6528 blame->thread_args.cancel_cb = cancel_blame_view;
6529 blame->thread_args.cancel_arg = &s->done;
6530 s->blame_complete = 0;
6532 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6533 s->first_displayed_line = 1;
6534 s->last_displayed_line = view->nlines;
6535 s->selected_line = 1;
6537 s->matched_line = 0;
6539 done:
6540 if (commit)
6541 got_object_commit_close(commit);
6542 if (fd != -1 && close(fd) == -1 && err == NULL)
6543 err = got_error_from_errno("close");
6544 if (blob)
6545 got_object_blob_close(blob);
6546 free(obj_id);
6547 if (err)
6548 stop_blame(blame);
6549 return err;
6552 static const struct got_error *
6553 open_blame_view(struct tog_view *view, char *path,
6554 struct got_object_id *commit_id, struct got_repository *repo)
6556 const struct got_error *err = NULL;
6557 struct tog_blame_view_state *s = &view->state.blame;
6559 STAILQ_INIT(&s->blamed_commits);
6561 s->path = strdup(path);
6562 if (s->path == NULL)
6563 return got_error_from_errno("strdup");
6565 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6566 if (err) {
6567 free(s->path);
6568 return err;
6571 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6572 s->first_displayed_line = 1;
6573 s->last_displayed_line = view->nlines;
6574 s->selected_line = 1;
6575 s->blame_complete = 0;
6576 s->repo = repo;
6577 s->commit_id = commit_id;
6578 memset(&s->blame, 0, sizeof(s->blame));
6580 STAILQ_INIT(&s->colors);
6581 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6582 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6583 get_color_value("TOG_COLOR_COMMIT"));
6584 if (err)
6585 return err;
6588 view->show = show_blame_view;
6589 view->input = input_blame_view;
6590 view->reset = reset_blame_view;
6591 view->close = close_blame_view;
6592 view->search_start = search_start_blame_view;
6593 view->search_setup = search_setup_blame_view;
6594 view->search_next = search_next_view_match;
6596 if (using_mock_io) {
6597 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6598 int rc;
6600 rc = pthread_cond_init(&bta->blame_complete, NULL);
6601 if (rc)
6602 return got_error_set_errno(rc, "pthread_cond_init");
6605 return run_blame(view);
6608 static const struct got_error *
6609 close_blame_view(struct tog_view *view)
6611 const struct got_error *err = NULL;
6612 struct tog_blame_view_state *s = &view->state.blame;
6614 if (s->blame.thread)
6615 err = stop_blame(&s->blame);
6617 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6618 struct got_object_qid *blamed_commit;
6619 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6620 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6621 got_object_qid_free(blamed_commit);
6624 if (using_mock_io) {
6625 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6626 int rc;
6628 rc = pthread_cond_destroy(&bta->blame_complete);
6629 if (rc && err == NULL)
6630 err = got_error_set_errno(rc, "pthread_cond_destroy");
6633 free(s->path);
6634 free_colors(&s->colors);
6635 return err;
6638 static const struct got_error *
6639 search_start_blame_view(struct tog_view *view)
6641 struct tog_blame_view_state *s = &view->state.blame;
6643 s->matched_line = 0;
6644 return NULL;
6647 static void
6648 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6649 size_t *nlines, int **first, int **last, int **match, int **selected)
6651 struct tog_blame_view_state *s = &view->state.blame;
6653 *f = s->blame.f;
6654 *nlines = s->blame.nlines;
6655 *line_offsets = s->blame.line_offsets;
6656 *match = &s->matched_line;
6657 *first = &s->first_displayed_line;
6658 *last = &s->last_displayed_line;
6659 *selected = &s->selected_line;
6662 static const struct got_error *
6663 show_blame_view(struct tog_view *view)
6665 const struct got_error *err = NULL;
6666 struct tog_blame_view_state *s = &view->state.blame;
6667 int errcode;
6669 if (s->blame.thread == NULL && !s->blame_complete) {
6670 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6671 &s->blame.thread_args);
6672 if (errcode)
6673 return got_error_set_errno(errcode, "pthread_create");
6675 if (!using_mock_io)
6676 halfdelay(1); /* fast refresh while annotating */
6679 if (s->blame_complete && !using_mock_io)
6680 halfdelay(10); /* disable fast refresh */
6682 err = draw_blame(view);
6684 view_border(view);
6685 return err;
6688 static const struct got_error *
6689 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6690 struct got_repository *repo, struct got_object_id *id)
6692 struct tog_view *log_view;
6693 const struct got_error *err = NULL;
6695 *new_view = NULL;
6697 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6698 if (log_view == NULL)
6699 return got_error_from_errno("view_open");
6701 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6702 if (err)
6703 view_close(log_view);
6704 else
6705 *new_view = log_view;
6707 return err;
6710 static const struct got_error *
6711 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6713 const struct got_error *err = NULL, *thread_err = NULL;
6714 struct tog_view *diff_view;
6715 struct tog_blame_view_state *s = &view->state.blame;
6716 int eos, nscroll, begin_y = 0, begin_x = 0;
6718 eos = nscroll = view->nlines - 2;
6719 if (view_is_hsplit_top(view))
6720 --eos; /* border */
6722 switch (ch) {
6723 case '0':
6724 case '$':
6725 case KEY_RIGHT:
6726 case 'l':
6727 case KEY_LEFT:
6728 case 'h':
6729 horizontal_scroll_input(view, ch);
6730 break;
6731 case 'q':
6732 s->done = 1;
6733 break;
6734 case 'g':
6735 case KEY_HOME:
6736 s->selected_line = 1;
6737 s->first_displayed_line = 1;
6738 view->count = 0;
6739 break;
6740 case 'G':
6741 case KEY_END:
6742 if (s->blame.nlines < eos) {
6743 s->selected_line = s->blame.nlines;
6744 s->first_displayed_line = 1;
6745 } else {
6746 s->selected_line = eos;
6747 s->first_displayed_line = s->blame.nlines - (eos - 1);
6749 view->count = 0;
6750 break;
6751 case 'k':
6752 case KEY_UP:
6753 case CTRL('p'):
6754 if (s->selected_line > 1)
6755 s->selected_line--;
6756 else if (s->selected_line == 1 &&
6757 s->first_displayed_line > 1)
6758 s->first_displayed_line--;
6759 else
6760 view->count = 0;
6761 break;
6762 case CTRL('u'):
6763 case 'u':
6764 nscroll /= 2;
6765 /* FALL THROUGH */
6766 case KEY_PPAGE:
6767 case CTRL('b'):
6768 case 'b':
6769 if (s->first_displayed_line == 1) {
6770 if (view->count > 1)
6771 nscroll += nscroll;
6772 s->selected_line = MAX(1, s->selected_line - nscroll);
6773 view->count = 0;
6774 break;
6776 if (s->first_displayed_line > nscroll)
6777 s->first_displayed_line -= nscroll;
6778 else
6779 s->first_displayed_line = 1;
6780 break;
6781 case 'j':
6782 case KEY_DOWN:
6783 case CTRL('n'):
6784 if (s->selected_line < eos && s->first_displayed_line +
6785 s->selected_line <= s->blame.nlines)
6786 s->selected_line++;
6787 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6788 s->first_displayed_line++;
6789 else
6790 view->count = 0;
6791 break;
6792 case 'c':
6793 case 'p': {
6794 struct got_object_id *id = NULL;
6796 view->count = 0;
6797 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6798 s->first_displayed_line, s->selected_line);
6799 if (id == NULL)
6800 break;
6801 if (ch == 'p') {
6802 struct got_commit_object *commit, *pcommit;
6803 struct got_object_qid *pid;
6804 struct got_object_id *blob_id = NULL;
6805 int obj_type;
6806 err = got_object_open_as_commit(&commit,
6807 s->repo, id);
6808 if (err)
6809 break;
6810 pid = STAILQ_FIRST(
6811 got_object_commit_get_parent_ids(commit));
6812 if (pid == NULL) {
6813 got_object_commit_close(commit);
6814 break;
6816 /* Check if path history ends here. */
6817 err = got_object_open_as_commit(&pcommit,
6818 s->repo, &pid->id);
6819 if (err)
6820 break;
6821 err = got_object_id_by_path(&blob_id, s->repo,
6822 pcommit, s->path);
6823 got_object_commit_close(pcommit);
6824 if (err) {
6825 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6826 err = NULL;
6827 got_object_commit_close(commit);
6828 break;
6830 err = got_object_get_type(&obj_type, s->repo,
6831 blob_id);
6832 free(blob_id);
6833 /* Can't blame non-blob type objects. */
6834 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6835 got_object_commit_close(commit);
6836 break;
6838 err = got_object_qid_alloc(&s->blamed_commit,
6839 &pid->id);
6840 got_object_commit_close(commit);
6841 } else {
6842 if (got_object_id_cmp(id,
6843 &s->blamed_commit->id) == 0)
6844 break;
6845 err = got_object_qid_alloc(&s->blamed_commit,
6846 id);
6848 if (err)
6849 break;
6850 s->done = 1;
6851 thread_err = stop_blame(&s->blame);
6852 s->done = 0;
6853 if (thread_err)
6854 break;
6855 STAILQ_INSERT_HEAD(&s->blamed_commits,
6856 s->blamed_commit, entry);
6857 err = run_blame(view);
6858 if (err)
6859 break;
6860 break;
6862 case 'C': {
6863 struct got_object_qid *first;
6865 view->count = 0;
6866 first = STAILQ_FIRST(&s->blamed_commits);
6867 if (!got_object_id_cmp(&first->id, s->commit_id))
6868 break;
6869 s->done = 1;
6870 thread_err = stop_blame(&s->blame);
6871 s->done = 0;
6872 if (thread_err)
6873 break;
6874 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6875 got_object_qid_free(s->blamed_commit);
6876 s->blamed_commit =
6877 STAILQ_FIRST(&s->blamed_commits);
6878 err = run_blame(view);
6879 if (err)
6880 break;
6881 break;
6883 case 'L':
6884 view->count = 0;
6885 s->id_to_log = get_selected_commit_id(s->blame.lines,
6886 s->blame.nlines, s->first_displayed_line, s->selected_line);
6887 if (s->id_to_log)
6888 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6889 break;
6890 case KEY_ENTER:
6891 case '\r': {
6892 struct got_object_id *id = NULL;
6893 struct got_object_qid *pid;
6894 struct got_commit_object *commit = NULL;
6896 view->count = 0;
6897 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6898 s->first_displayed_line, s->selected_line);
6899 if (id == NULL)
6900 break;
6901 err = got_object_open_as_commit(&commit, s->repo, id);
6902 if (err)
6903 break;
6904 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6905 if (*new_view) {
6906 /* traversed from diff view, release diff resources */
6907 err = close_diff_view(*new_view);
6908 if (err)
6909 break;
6910 diff_view = *new_view;
6911 } else {
6912 if (view_is_parent_view(view))
6913 view_get_split(view, &begin_y, &begin_x);
6915 diff_view = view_open(0, 0, begin_y, begin_x,
6916 TOG_VIEW_DIFF);
6917 if (diff_view == NULL) {
6918 got_object_commit_close(commit);
6919 err = got_error_from_errno("view_open");
6920 break;
6923 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6924 id, NULL, NULL, 3, 0, 0, view, s->repo);
6925 got_object_commit_close(commit);
6926 if (err) {
6927 view_close(diff_view);
6928 break;
6930 s->last_diffed_line = s->first_displayed_line - 1 +
6931 s->selected_line;
6932 if (*new_view)
6933 break; /* still open from active diff view */
6934 if (view_is_parent_view(view) &&
6935 view->mode == TOG_VIEW_SPLIT_HRZN) {
6936 err = view_init_hsplit(view, begin_y);
6937 if (err)
6938 break;
6941 view->focussed = 0;
6942 diff_view->focussed = 1;
6943 diff_view->mode = view->mode;
6944 diff_view->nlines = view->lines - begin_y;
6945 if (view_is_parent_view(view)) {
6946 view_transfer_size(diff_view, view);
6947 err = view_close_child(view);
6948 if (err)
6949 break;
6950 err = view_set_child(view, diff_view);
6951 if (err)
6952 break;
6953 view->focus_child = 1;
6954 } else
6955 *new_view = diff_view;
6956 if (err)
6957 break;
6958 break;
6960 case CTRL('d'):
6961 case 'd':
6962 nscroll /= 2;
6963 /* FALL THROUGH */
6964 case KEY_NPAGE:
6965 case CTRL('f'):
6966 case 'f':
6967 case ' ':
6968 if (s->last_displayed_line >= s->blame.nlines &&
6969 s->selected_line >= MIN(s->blame.nlines,
6970 view->nlines - 2)) {
6971 view->count = 0;
6972 break;
6974 if (s->last_displayed_line >= s->blame.nlines &&
6975 s->selected_line < view->nlines - 2) {
6976 s->selected_line +=
6977 MIN(nscroll, s->last_displayed_line -
6978 s->first_displayed_line - s->selected_line + 1);
6980 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6981 s->first_displayed_line += nscroll;
6982 else
6983 s->first_displayed_line =
6984 s->blame.nlines - (view->nlines - 3);
6985 break;
6986 case KEY_RESIZE:
6987 if (s->selected_line > view->nlines - 2) {
6988 s->selected_line = MIN(s->blame.nlines,
6989 view->nlines - 2);
6991 break;
6992 default:
6993 view->count = 0;
6994 break;
6996 return thread_err ? thread_err : err;
6999 static const struct got_error *
7000 reset_blame_view(struct tog_view *view)
7002 const struct got_error *err;
7003 struct tog_blame_view_state *s = &view->state.blame;
7005 view->count = 0;
7006 s->done = 1;
7007 err = stop_blame(&s->blame);
7008 s->done = 0;
7009 if (err)
7010 return err;
7011 return run_blame(view);
7014 static const struct got_error *
7015 cmd_blame(int argc, char *argv[])
7017 const struct got_error *error;
7018 struct got_repository *repo = NULL;
7019 struct got_worktree *worktree = NULL;
7020 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7021 char *link_target = NULL;
7022 struct got_object_id *commit_id = NULL;
7023 struct got_commit_object *commit = NULL;
7024 char *commit_id_str = NULL;
7025 int ch;
7026 struct tog_view *view = NULL;
7027 int *pack_fds = NULL;
7029 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7030 switch (ch) {
7031 case 'c':
7032 commit_id_str = optarg;
7033 break;
7034 case 'r':
7035 repo_path = realpath(optarg, NULL);
7036 if (repo_path == NULL)
7037 return got_error_from_errno2("realpath",
7038 optarg);
7039 break;
7040 default:
7041 usage_blame();
7042 /* NOTREACHED */
7046 argc -= optind;
7047 argv += optind;
7049 if (argc != 1)
7050 usage_blame();
7052 error = got_repo_pack_fds_open(&pack_fds);
7053 if (error != NULL)
7054 goto done;
7056 if (repo_path == NULL) {
7057 cwd = getcwd(NULL, 0);
7058 if (cwd == NULL)
7059 return got_error_from_errno("getcwd");
7060 error = got_worktree_open(&worktree, cwd);
7061 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7062 goto done;
7063 if (worktree)
7064 repo_path =
7065 strdup(got_worktree_get_repo_path(worktree));
7066 else
7067 repo_path = strdup(cwd);
7068 if (repo_path == NULL) {
7069 error = got_error_from_errno("strdup");
7070 goto done;
7074 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7075 if (error != NULL)
7076 goto done;
7078 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7079 worktree);
7080 if (error)
7081 goto done;
7083 init_curses();
7085 error = apply_unveil(got_repo_get_path(repo), NULL);
7086 if (error)
7087 goto done;
7089 error = tog_load_refs(repo, 0);
7090 if (error)
7091 goto done;
7093 if (commit_id_str == NULL) {
7094 struct got_reference *head_ref;
7095 error = got_ref_open(&head_ref, repo, worktree ?
7096 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7097 if (error != NULL)
7098 goto done;
7099 error = got_ref_resolve(&commit_id, repo, head_ref);
7100 got_ref_close(head_ref);
7101 } else {
7102 error = got_repo_match_object_id(&commit_id, NULL,
7103 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7105 if (error != NULL)
7106 goto done;
7108 error = got_object_open_as_commit(&commit, repo, commit_id);
7109 if (error)
7110 goto done;
7112 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7113 commit, repo);
7114 if (error)
7115 goto done;
7117 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7118 if (view == NULL) {
7119 error = got_error_from_errno("view_open");
7120 goto done;
7122 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7123 commit_id, repo);
7124 if (error != NULL) {
7125 if (view->close == NULL)
7126 close_blame_view(view);
7127 view_close(view);
7128 goto done;
7130 if (worktree) {
7131 /* Release work tree lock. */
7132 got_worktree_close(worktree);
7133 worktree = NULL;
7135 error = view_loop(view);
7136 done:
7137 free(repo_path);
7138 free(in_repo_path);
7139 free(link_target);
7140 free(cwd);
7141 free(commit_id);
7142 if (commit)
7143 got_object_commit_close(commit);
7144 if (worktree)
7145 got_worktree_close(worktree);
7146 if (repo) {
7147 const struct got_error *close_err = got_repo_close(repo);
7148 if (error == NULL)
7149 error = close_err;
7151 if (pack_fds) {
7152 const struct got_error *pack_err =
7153 got_repo_pack_fds_close(pack_fds);
7154 if (error == NULL)
7155 error = pack_err;
7157 tog_free_refs();
7158 return error;
7161 static const struct got_error *
7162 draw_tree_entries(struct tog_view *view, const char *parent_path)
7164 struct tog_tree_view_state *s = &view->state.tree;
7165 const struct got_error *err = NULL;
7166 struct got_tree_entry *te;
7167 wchar_t *wline;
7168 char *index = NULL;
7169 struct tog_color *tc;
7170 int width, n, nentries, scrollx, i = 1;
7171 int limit = view->nlines;
7173 s->ndisplayed = 0;
7174 if (view_is_hsplit_top(view))
7175 --limit; /* border */
7177 werase(view->window);
7179 if (limit == 0)
7180 return NULL;
7182 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7183 0, 0);
7184 if (err)
7185 return err;
7186 if (view_needs_focus_indication(view))
7187 wstandout(view->window);
7188 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7189 if (tc)
7190 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7191 waddwstr(view->window, wline);
7192 free(wline);
7193 wline = NULL;
7194 while (width++ < view->ncols)
7195 waddch(view->window, ' ');
7196 if (tc)
7197 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7198 if (view_needs_focus_indication(view))
7199 wstandend(view->window);
7200 if (--limit <= 0)
7201 return NULL;
7203 i += s->selected;
7204 if (s->first_displayed_entry) {
7205 i += got_tree_entry_get_index(s->first_displayed_entry);
7206 if (s->tree != s->root)
7207 ++i; /* account for ".." entry */
7209 nentries = got_object_tree_get_nentries(s->tree);
7210 if (asprintf(&index, "[%d/%d] %s",
7211 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7212 return got_error_from_errno("asprintf");
7213 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7214 free(index);
7215 if (err)
7216 return err;
7217 waddwstr(view->window, wline);
7218 free(wline);
7219 wline = NULL;
7220 if (width < view->ncols - 1)
7221 waddch(view->window, '\n');
7222 if (--limit <= 0)
7223 return NULL;
7224 waddch(view->window, '\n');
7225 if (--limit <= 0)
7226 return NULL;
7228 if (s->first_displayed_entry == NULL) {
7229 te = got_object_tree_get_first_entry(s->tree);
7230 if (s->selected == 0) {
7231 if (view->focussed)
7232 wstandout(view->window);
7233 s->selected_entry = NULL;
7235 waddstr(view->window, " ..\n"); /* parent directory */
7236 if (s->selected == 0 && view->focussed)
7237 wstandend(view->window);
7238 s->ndisplayed++;
7239 if (--limit <= 0)
7240 return NULL;
7241 n = 1;
7242 } else {
7243 n = 0;
7244 te = s->first_displayed_entry;
7247 view->maxx = 0;
7248 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7249 char *line = NULL, *id_str = NULL, *link_target = NULL;
7250 const char *modestr = "";
7251 mode_t mode;
7253 te = got_object_tree_get_entry(s->tree, i);
7254 mode = got_tree_entry_get_mode(te);
7256 if (s->show_ids) {
7257 err = got_object_id_str(&id_str,
7258 got_tree_entry_get_id(te));
7259 if (err)
7260 return got_error_from_errno(
7261 "got_object_id_str");
7263 if (got_object_tree_entry_is_submodule(te))
7264 modestr = "$";
7265 else if (S_ISLNK(mode)) {
7266 int i;
7268 err = got_tree_entry_get_symlink_target(&link_target,
7269 te, s->repo);
7270 if (err) {
7271 free(id_str);
7272 return err;
7274 for (i = 0; i < strlen(link_target); i++) {
7275 if (!isprint((unsigned char)link_target[i]))
7276 link_target[i] = '?';
7278 modestr = "@";
7280 else if (S_ISDIR(mode))
7281 modestr = "/";
7282 else if (mode & S_IXUSR)
7283 modestr = "*";
7284 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7285 got_tree_entry_get_name(te), modestr,
7286 link_target ? " -> ": "",
7287 link_target ? link_target : "") == -1) {
7288 free(id_str);
7289 free(link_target);
7290 return got_error_from_errno("asprintf");
7292 free(id_str);
7293 free(link_target);
7295 /* use full line width to determine view->maxx */
7296 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7297 if (err) {
7298 free(line);
7299 break;
7301 view->maxx = MAX(view->maxx, width);
7302 free(wline);
7303 wline = NULL;
7305 err = format_line(&wline, &width, &scrollx, line, view->x,
7306 view->ncols, 0, 0);
7307 if (err) {
7308 free(line);
7309 break;
7311 if (n == s->selected) {
7312 if (view->focussed)
7313 wstandout(view->window);
7314 s->selected_entry = te;
7316 tc = match_color(&s->colors, line);
7317 if (tc)
7318 wattr_on(view->window,
7319 COLOR_PAIR(tc->colorpair), NULL);
7320 waddwstr(view->window, &wline[scrollx]);
7321 if (tc)
7322 wattr_off(view->window,
7323 COLOR_PAIR(tc->colorpair), NULL);
7324 if (width < view->ncols)
7325 waddch(view->window, '\n');
7326 if (n == s->selected && view->focussed)
7327 wstandend(view->window);
7328 free(line);
7329 free(wline);
7330 wline = NULL;
7331 n++;
7332 s->ndisplayed++;
7333 s->last_displayed_entry = te;
7334 if (--limit <= 0)
7335 break;
7338 return err;
7341 static void
7342 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7344 struct got_tree_entry *te;
7345 int isroot = s->tree == s->root;
7346 int i = 0;
7348 if (s->first_displayed_entry == NULL)
7349 return;
7351 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7352 while (i++ < maxscroll) {
7353 if (te == NULL) {
7354 if (!isroot)
7355 s->first_displayed_entry = NULL;
7356 break;
7358 s->first_displayed_entry = te;
7359 te = got_tree_entry_get_prev(s->tree, te);
7363 static const struct got_error *
7364 tree_scroll_down(struct tog_view *view, int maxscroll)
7366 struct tog_tree_view_state *s = &view->state.tree;
7367 struct got_tree_entry *next, *last;
7368 int n = 0;
7370 if (s->first_displayed_entry)
7371 next = got_tree_entry_get_next(s->tree,
7372 s->first_displayed_entry);
7373 else
7374 next = got_object_tree_get_first_entry(s->tree);
7376 last = s->last_displayed_entry;
7377 while (next && n++ < maxscroll) {
7378 if (last) {
7379 s->last_displayed_entry = last;
7380 last = got_tree_entry_get_next(s->tree, last);
7382 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7383 s->first_displayed_entry = next;
7384 next = got_tree_entry_get_next(s->tree, next);
7388 return NULL;
7391 static const struct got_error *
7392 tree_entry_path(char **path, struct tog_parent_trees *parents,
7393 struct got_tree_entry *te)
7395 const struct got_error *err = NULL;
7396 struct tog_parent_tree *pt;
7397 size_t len = 2; /* for leading slash and NUL */
7399 TAILQ_FOREACH(pt, parents, entry)
7400 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7401 + 1 /* slash */;
7402 if (te)
7403 len += strlen(got_tree_entry_get_name(te));
7405 *path = calloc(1, len);
7406 if (path == NULL)
7407 return got_error_from_errno("calloc");
7409 (*path)[0] = '/';
7410 pt = TAILQ_LAST(parents, tog_parent_trees);
7411 while (pt) {
7412 const char *name = got_tree_entry_get_name(pt->selected_entry);
7413 if (strlcat(*path, name, len) >= len) {
7414 err = got_error(GOT_ERR_NO_SPACE);
7415 goto done;
7417 if (strlcat(*path, "/", len) >= len) {
7418 err = got_error(GOT_ERR_NO_SPACE);
7419 goto done;
7421 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7423 if (te) {
7424 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7425 err = got_error(GOT_ERR_NO_SPACE);
7426 goto done;
7429 done:
7430 if (err) {
7431 free(*path);
7432 *path = NULL;
7434 return err;
7437 static const struct got_error *
7438 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7439 struct got_tree_entry *te, struct tog_parent_trees *parents,
7440 struct got_object_id *commit_id, struct got_repository *repo)
7442 const struct got_error *err = NULL;
7443 char *path;
7444 struct tog_view *blame_view;
7446 *new_view = NULL;
7448 err = tree_entry_path(&path, parents, te);
7449 if (err)
7450 return err;
7452 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7453 if (blame_view == NULL) {
7454 err = got_error_from_errno("view_open");
7455 goto done;
7458 err = open_blame_view(blame_view, path, commit_id, repo);
7459 if (err) {
7460 if (err->code == GOT_ERR_CANCELLED)
7461 err = NULL;
7462 view_close(blame_view);
7463 } else
7464 *new_view = blame_view;
7465 done:
7466 free(path);
7467 return err;
7470 static const struct got_error *
7471 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7472 struct tog_tree_view_state *s)
7474 struct tog_view *log_view;
7475 const struct got_error *err = NULL;
7476 char *path;
7478 *new_view = NULL;
7480 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7481 if (log_view == NULL)
7482 return got_error_from_errno("view_open");
7484 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7485 if (err)
7486 return err;
7488 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7489 path, 0);
7490 if (err)
7491 view_close(log_view);
7492 else
7493 *new_view = log_view;
7494 free(path);
7495 return err;
7498 static const struct got_error *
7499 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7500 const char *head_ref_name, struct got_repository *repo)
7502 const struct got_error *err = NULL;
7503 char *commit_id_str = NULL;
7504 struct tog_tree_view_state *s = &view->state.tree;
7505 struct got_commit_object *commit = NULL;
7507 TAILQ_INIT(&s->parents);
7508 STAILQ_INIT(&s->colors);
7510 s->commit_id = got_object_id_dup(commit_id);
7511 if (s->commit_id == NULL) {
7512 err = got_error_from_errno("got_object_id_dup");
7513 goto done;
7516 err = got_object_open_as_commit(&commit, repo, commit_id);
7517 if (err)
7518 goto done;
7521 * The root is opened here and will be closed when the view is closed.
7522 * Any visited subtrees and their path-wise parents are opened and
7523 * closed on demand.
7525 err = got_object_open_as_tree(&s->root, repo,
7526 got_object_commit_get_tree_id(commit));
7527 if (err)
7528 goto done;
7529 s->tree = s->root;
7531 err = got_object_id_str(&commit_id_str, commit_id);
7532 if (err != NULL)
7533 goto done;
7535 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7536 err = got_error_from_errno("asprintf");
7537 goto done;
7540 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7541 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7542 if (head_ref_name) {
7543 s->head_ref_name = strdup(head_ref_name);
7544 if (s->head_ref_name == NULL) {
7545 err = got_error_from_errno("strdup");
7546 goto done;
7549 s->repo = repo;
7551 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7552 err = add_color(&s->colors, "\\$$",
7553 TOG_COLOR_TREE_SUBMODULE,
7554 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7555 if (err)
7556 goto done;
7557 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7558 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7559 if (err)
7560 goto done;
7561 err = add_color(&s->colors, "/$",
7562 TOG_COLOR_TREE_DIRECTORY,
7563 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7564 if (err)
7565 goto done;
7567 err = add_color(&s->colors, "\\*$",
7568 TOG_COLOR_TREE_EXECUTABLE,
7569 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7570 if (err)
7571 goto done;
7573 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7574 get_color_value("TOG_COLOR_COMMIT"));
7575 if (err)
7576 goto done;
7579 view->show = show_tree_view;
7580 view->input = input_tree_view;
7581 view->close = close_tree_view;
7582 view->search_start = search_start_tree_view;
7583 view->search_next = search_next_tree_view;
7584 done:
7585 free(commit_id_str);
7586 if (commit)
7587 got_object_commit_close(commit);
7588 if (err) {
7589 if (view->close == NULL)
7590 close_tree_view(view);
7591 view_close(view);
7593 return err;
7596 static const struct got_error *
7597 close_tree_view(struct tog_view *view)
7599 struct tog_tree_view_state *s = &view->state.tree;
7601 free_colors(&s->colors);
7602 free(s->tree_label);
7603 s->tree_label = NULL;
7604 free(s->commit_id);
7605 s->commit_id = NULL;
7606 free(s->head_ref_name);
7607 s->head_ref_name = NULL;
7608 while (!TAILQ_EMPTY(&s->parents)) {
7609 struct tog_parent_tree *parent;
7610 parent = TAILQ_FIRST(&s->parents);
7611 TAILQ_REMOVE(&s->parents, parent, entry);
7612 if (parent->tree != s->root)
7613 got_object_tree_close(parent->tree);
7614 free(parent);
7617 if (s->tree != NULL && s->tree != s->root)
7618 got_object_tree_close(s->tree);
7619 if (s->root)
7620 got_object_tree_close(s->root);
7621 return NULL;
7624 static const struct got_error *
7625 search_start_tree_view(struct tog_view *view)
7627 struct tog_tree_view_state *s = &view->state.tree;
7629 s->matched_entry = NULL;
7630 return NULL;
7633 static int
7634 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7636 regmatch_t regmatch;
7638 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7639 0) == 0;
7642 static const struct got_error *
7643 search_next_tree_view(struct tog_view *view)
7645 struct tog_tree_view_state *s = &view->state.tree;
7646 struct got_tree_entry *te = NULL;
7648 if (!view->searching) {
7649 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7650 return NULL;
7653 if (s->matched_entry) {
7654 if (view->searching == TOG_SEARCH_FORWARD) {
7655 if (s->selected_entry)
7656 te = got_tree_entry_get_next(s->tree,
7657 s->selected_entry);
7658 else
7659 te = got_object_tree_get_first_entry(s->tree);
7660 } else {
7661 if (s->selected_entry == NULL)
7662 te = got_object_tree_get_last_entry(s->tree);
7663 else
7664 te = got_tree_entry_get_prev(s->tree,
7665 s->selected_entry);
7667 } else {
7668 if (s->selected_entry)
7669 te = s->selected_entry;
7670 else if (view->searching == TOG_SEARCH_FORWARD)
7671 te = got_object_tree_get_first_entry(s->tree);
7672 else
7673 te = got_object_tree_get_last_entry(s->tree);
7676 while (1) {
7677 if (te == NULL) {
7678 if (s->matched_entry == NULL) {
7679 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7680 return NULL;
7682 if (view->searching == TOG_SEARCH_FORWARD)
7683 te = got_object_tree_get_first_entry(s->tree);
7684 else
7685 te = got_object_tree_get_last_entry(s->tree);
7688 if (match_tree_entry(te, &view->regex)) {
7689 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7690 s->matched_entry = te;
7691 break;
7694 if (view->searching == TOG_SEARCH_FORWARD)
7695 te = got_tree_entry_get_next(s->tree, te);
7696 else
7697 te = got_tree_entry_get_prev(s->tree, te);
7700 if (s->matched_entry) {
7701 s->first_displayed_entry = s->matched_entry;
7702 s->selected = 0;
7705 return NULL;
7708 static const struct got_error *
7709 show_tree_view(struct tog_view *view)
7711 const struct got_error *err = NULL;
7712 struct tog_tree_view_state *s = &view->state.tree;
7713 char *parent_path;
7715 err = tree_entry_path(&parent_path, &s->parents, NULL);
7716 if (err)
7717 return err;
7719 err = draw_tree_entries(view, parent_path);
7720 free(parent_path);
7722 view_border(view);
7723 return err;
7726 static const struct got_error *
7727 tree_goto_line(struct tog_view *view, int nlines)
7729 const struct got_error *err = NULL;
7730 struct tog_tree_view_state *s = &view->state.tree;
7731 struct got_tree_entry **fte, **lte, **ste;
7732 int g, last, first = 1, i = 1;
7733 int root = s->tree == s->root;
7734 int off = root ? 1 : 2;
7736 g = view->gline;
7737 view->gline = 0;
7739 if (g == 0)
7740 g = 1;
7741 else if (g > got_object_tree_get_nentries(s->tree))
7742 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7744 fte = &s->first_displayed_entry;
7745 lte = &s->last_displayed_entry;
7746 ste = &s->selected_entry;
7748 if (*fte != NULL) {
7749 first = got_tree_entry_get_index(*fte);
7750 first += off; /* account for ".." */
7752 last = got_tree_entry_get_index(*lte);
7753 last += off;
7755 if (g >= first && g <= last && g - first < nlines) {
7756 s->selected = g - first;
7757 return NULL; /* gline is on the current page */
7760 if (*ste != NULL) {
7761 i = got_tree_entry_get_index(*ste);
7762 i += off;
7765 if (i < g) {
7766 err = tree_scroll_down(view, g - i);
7767 if (err)
7768 return err;
7769 if (got_tree_entry_get_index(*lte) >=
7770 got_object_tree_get_nentries(s->tree) - 1 &&
7771 first + s->selected < g &&
7772 s->selected < s->ndisplayed - 1) {
7773 first = got_tree_entry_get_index(*fte);
7774 first += off;
7775 s->selected = g - first;
7777 } else if (i > g)
7778 tree_scroll_up(s, i - g);
7780 if (g < nlines &&
7781 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7782 s->selected = g - 1;
7784 return NULL;
7787 static const struct got_error *
7788 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7790 const struct got_error *err = NULL;
7791 struct tog_tree_view_state *s = &view->state.tree;
7792 struct got_tree_entry *te;
7793 int n, nscroll = view->nlines - 3;
7795 if (view->gline)
7796 return tree_goto_line(view, nscroll);
7798 switch (ch) {
7799 case '0':
7800 case '$':
7801 case KEY_RIGHT:
7802 case 'l':
7803 case KEY_LEFT:
7804 case 'h':
7805 horizontal_scroll_input(view, ch);
7806 break;
7807 case 'i':
7808 s->show_ids = !s->show_ids;
7809 view->count = 0;
7810 break;
7811 case 'L':
7812 view->count = 0;
7813 if (!s->selected_entry)
7814 break;
7815 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7816 break;
7817 case 'R':
7818 view->count = 0;
7819 err = view_request_new(new_view, view, TOG_VIEW_REF);
7820 break;
7821 case 'g':
7822 case '=':
7823 case KEY_HOME:
7824 s->selected = 0;
7825 view->count = 0;
7826 if (s->tree == s->root)
7827 s->first_displayed_entry =
7828 got_object_tree_get_first_entry(s->tree);
7829 else
7830 s->first_displayed_entry = NULL;
7831 break;
7832 case 'G':
7833 case '*':
7834 case KEY_END: {
7835 int eos = view->nlines - 3;
7837 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7838 --eos; /* border */
7839 s->selected = 0;
7840 view->count = 0;
7841 te = got_object_tree_get_last_entry(s->tree);
7842 for (n = 0; n < eos; n++) {
7843 if (te == NULL) {
7844 if (s->tree != s->root) {
7845 s->first_displayed_entry = NULL;
7846 n++;
7848 break;
7850 s->first_displayed_entry = te;
7851 te = got_tree_entry_get_prev(s->tree, te);
7853 if (n > 0)
7854 s->selected = n - 1;
7855 break;
7857 case 'k':
7858 case KEY_UP:
7859 case CTRL('p'):
7860 if (s->selected > 0) {
7861 s->selected--;
7862 break;
7864 tree_scroll_up(s, 1);
7865 if (s->selected_entry == NULL ||
7866 (s->tree == s->root && s->selected_entry ==
7867 got_object_tree_get_first_entry(s->tree)))
7868 view->count = 0;
7869 break;
7870 case CTRL('u'):
7871 case 'u':
7872 nscroll /= 2;
7873 /* FALL THROUGH */
7874 case KEY_PPAGE:
7875 case CTRL('b'):
7876 case 'b':
7877 if (s->tree == s->root) {
7878 if (got_object_tree_get_first_entry(s->tree) ==
7879 s->first_displayed_entry)
7880 s->selected -= MIN(s->selected, nscroll);
7881 } else {
7882 if (s->first_displayed_entry == NULL)
7883 s->selected -= MIN(s->selected, nscroll);
7885 tree_scroll_up(s, MAX(0, nscroll));
7886 if (s->selected_entry == NULL ||
7887 (s->tree == s->root && s->selected_entry ==
7888 got_object_tree_get_first_entry(s->tree)))
7889 view->count = 0;
7890 break;
7891 case 'j':
7892 case KEY_DOWN:
7893 case CTRL('n'):
7894 if (s->selected < s->ndisplayed - 1) {
7895 s->selected++;
7896 break;
7898 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7899 == NULL) {
7900 /* can't scroll any further */
7901 view->count = 0;
7902 break;
7904 tree_scroll_down(view, 1);
7905 break;
7906 case CTRL('d'):
7907 case 'd':
7908 nscroll /= 2;
7909 /* FALL THROUGH */
7910 case KEY_NPAGE:
7911 case CTRL('f'):
7912 case 'f':
7913 case ' ':
7914 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7915 == NULL) {
7916 /* can't scroll any further; move cursor down */
7917 if (s->selected < s->ndisplayed - 1)
7918 s->selected += MIN(nscroll,
7919 s->ndisplayed - s->selected - 1);
7920 else
7921 view->count = 0;
7922 break;
7924 tree_scroll_down(view, nscroll);
7925 break;
7926 case KEY_ENTER:
7927 case '\r':
7928 case KEY_BACKSPACE:
7929 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7930 struct tog_parent_tree *parent;
7931 /* user selected '..' */
7932 if (s->tree == s->root) {
7933 view->count = 0;
7934 break;
7936 parent = TAILQ_FIRST(&s->parents);
7937 TAILQ_REMOVE(&s->parents, parent,
7938 entry);
7939 got_object_tree_close(s->tree);
7940 s->tree = parent->tree;
7941 s->first_displayed_entry =
7942 parent->first_displayed_entry;
7943 s->selected_entry =
7944 parent->selected_entry;
7945 s->selected = parent->selected;
7946 if (s->selected > view->nlines - 3) {
7947 err = offset_selection_down(view);
7948 if (err)
7949 break;
7951 free(parent);
7952 } else if (S_ISDIR(got_tree_entry_get_mode(
7953 s->selected_entry))) {
7954 struct got_tree_object *subtree;
7955 view->count = 0;
7956 err = got_object_open_as_tree(&subtree, s->repo,
7957 got_tree_entry_get_id(s->selected_entry));
7958 if (err)
7959 break;
7960 err = tree_view_visit_subtree(s, subtree);
7961 if (err) {
7962 got_object_tree_close(subtree);
7963 break;
7965 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7966 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7967 break;
7968 case KEY_RESIZE:
7969 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7970 s->selected = view->nlines - 4;
7971 view->count = 0;
7972 break;
7973 default:
7974 view->count = 0;
7975 break;
7978 return err;
7981 __dead static void
7982 usage_tree(void)
7984 endwin();
7985 fprintf(stderr,
7986 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7987 getprogname());
7988 exit(1);
7991 static const struct got_error *
7992 cmd_tree(int argc, char *argv[])
7994 const struct got_error *error;
7995 struct got_repository *repo = NULL;
7996 struct got_worktree *worktree = NULL;
7997 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7998 struct got_object_id *commit_id = NULL;
7999 struct got_commit_object *commit = NULL;
8000 const char *commit_id_arg = NULL;
8001 char *label = NULL;
8002 struct got_reference *ref = NULL;
8003 const char *head_ref_name = NULL;
8004 int ch;
8005 struct tog_view *view;
8006 int *pack_fds = NULL;
8008 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
8009 switch (ch) {
8010 case 'c':
8011 commit_id_arg = optarg;
8012 break;
8013 case 'r':
8014 repo_path = realpath(optarg, NULL);
8015 if (repo_path == NULL)
8016 return got_error_from_errno2("realpath",
8017 optarg);
8018 break;
8019 default:
8020 usage_tree();
8021 /* NOTREACHED */
8025 argc -= optind;
8026 argv += optind;
8028 if (argc > 1)
8029 usage_tree();
8031 error = got_repo_pack_fds_open(&pack_fds);
8032 if (error != NULL)
8033 goto done;
8035 if (repo_path == NULL) {
8036 cwd = getcwd(NULL, 0);
8037 if (cwd == NULL)
8038 return got_error_from_errno("getcwd");
8039 error = got_worktree_open(&worktree, cwd);
8040 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8041 goto done;
8042 if (worktree)
8043 repo_path =
8044 strdup(got_worktree_get_repo_path(worktree));
8045 else
8046 repo_path = strdup(cwd);
8047 if (repo_path == NULL) {
8048 error = got_error_from_errno("strdup");
8049 goto done;
8053 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8054 if (error != NULL)
8055 goto done;
8057 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8058 repo, worktree);
8059 if (error)
8060 goto done;
8062 init_curses();
8064 error = apply_unveil(got_repo_get_path(repo), NULL);
8065 if (error)
8066 goto done;
8068 error = tog_load_refs(repo, 0);
8069 if (error)
8070 goto done;
8072 if (commit_id_arg == NULL) {
8073 error = got_repo_match_object_id(&commit_id, &label,
8074 worktree ? got_worktree_get_head_ref_name(worktree) :
8075 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8076 if (error)
8077 goto done;
8078 head_ref_name = label;
8079 } else {
8080 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8081 if (error == NULL)
8082 head_ref_name = got_ref_get_name(ref);
8083 else if (error->code != GOT_ERR_NOT_REF)
8084 goto done;
8085 error = got_repo_match_object_id(&commit_id, NULL,
8086 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8087 if (error)
8088 goto done;
8091 error = got_object_open_as_commit(&commit, repo, commit_id);
8092 if (error)
8093 goto done;
8095 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8096 if (view == NULL) {
8097 error = got_error_from_errno("view_open");
8098 goto done;
8100 error = open_tree_view(view, commit_id, head_ref_name, repo);
8101 if (error)
8102 goto done;
8103 if (!got_path_is_root_dir(in_repo_path)) {
8104 error = tree_view_walk_path(&view->state.tree, commit,
8105 in_repo_path);
8106 if (error)
8107 goto done;
8110 if (worktree) {
8111 /* Release work tree lock. */
8112 got_worktree_close(worktree);
8113 worktree = NULL;
8115 error = view_loop(view);
8116 done:
8117 free(repo_path);
8118 free(cwd);
8119 free(commit_id);
8120 free(label);
8121 if (ref)
8122 got_ref_close(ref);
8123 if (repo) {
8124 const struct got_error *close_err = got_repo_close(repo);
8125 if (error == NULL)
8126 error = close_err;
8128 if (pack_fds) {
8129 const struct got_error *pack_err =
8130 got_repo_pack_fds_close(pack_fds);
8131 if (error == NULL)
8132 error = pack_err;
8134 tog_free_refs();
8135 return error;
8138 static const struct got_error *
8139 ref_view_load_refs(struct tog_ref_view_state *s)
8141 struct got_reflist_entry *sre;
8142 struct tog_reflist_entry *re;
8144 s->nrefs = 0;
8145 TAILQ_FOREACH(sre, &tog_refs, entry) {
8146 if (strncmp(got_ref_get_name(sre->ref),
8147 "refs/got/", 9) == 0 &&
8148 strncmp(got_ref_get_name(sre->ref),
8149 "refs/got/backup/", 16) != 0)
8150 continue;
8152 re = malloc(sizeof(*re));
8153 if (re == NULL)
8154 return got_error_from_errno("malloc");
8156 re->ref = got_ref_dup(sre->ref);
8157 if (re->ref == NULL)
8158 return got_error_from_errno("got_ref_dup");
8159 re->idx = s->nrefs++;
8160 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8163 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8164 return NULL;
8167 static void
8168 ref_view_free_refs(struct tog_ref_view_state *s)
8170 struct tog_reflist_entry *re;
8172 while (!TAILQ_EMPTY(&s->refs)) {
8173 re = TAILQ_FIRST(&s->refs);
8174 TAILQ_REMOVE(&s->refs, re, entry);
8175 got_ref_close(re->ref);
8176 free(re);
8180 static const struct got_error *
8181 open_ref_view(struct tog_view *view, struct got_repository *repo)
8183 const struct got_error *err = NULL;
8184 struct tog_ref_view_state *s = &view->state.ref;
8186 s->selected_entry = 0;
8187 s->repo = repo;
8189 TAILQ_INIT(&s->refs);
8190 STAILQ_INIT(&s->colors);
8192 err = ref_view_load_refs(s);
8193 if (err)
8194 goto done;
8196 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8197 err = add_color(&s->colors, "^refs/heads/",
8198 TOG_COLOR_REFS_HEADS,
8199 get_color_value("TOG_COLOR_REFS_HEADS"));
8200 if (err)
8201 goto done;
8203 err = add_color(&s->colors, "^refs/tags/",
8204 TOG_COLOR_REFS_TAGS,
8205 get_color_value("TOG_COLOR_REFS_TAGS"));
8206 if (err)
8207 goto done;
8209 err = add_color(&s->colors, "^refs/remotes/",
8210 TOG_COLOR_REFS_REMOTES,
8211 get_color_value("TOG_COLOR_REFS_REMOTES"));
8212 if (err)
8213 goto done;
8215 err = add_color(&s->colors, "^refs/got/backup/",
8216 TOG_COLOR_REFS_BACKUP,
8217 get_color_value("TOG_COLOR_REFS_BACKUP"));
8218 if (err)
8219 goto done;
8222 view->show = show_ref_view;
8223 view->input = input_ref_view;
8224 view->close = close_ref_view;
8225 view->search_start = search_start_ref_view;
8226 view->search_next = search_next_ref_view;
8227 done:
8228 if (err) {
8229 if (view->close == NULL)
8230 close_ref_view(view);
8231 view_close(view);
8233 return err;
8236 static const struct got_error *
8237 close_ref_view(struct tog_view *view)
8239 struct tog_ref_view_state *s = &view->state.ref;
8241 ref_view_free_refs(s);
8242 free_colors(&s->colors);
8244 return NULL;
8247 static const struct got_error *
8248 resolve_reflist_entry(struct got_object_id **commit_id,
8249 struct tog_reflist_entry *re, struct got_repository *repo)
8251 const struct got_error *err = NULL;
8252 struct got_object_id *obj_id;
8253 struct got_tag_object *tag = NULL;
8254 int obj_type;
8256 *commit_id = NULL;
8258 err = got_ref_resolve(&obj_id, repo, re->ref);
8259 if (err)
8260 return err;
8262 err = got_object_get_type(&obj_type, repo, obj_id);
8263 if (err)
8264 goto done;
8266 switch (obj_type) {
8267 case GOT_OBJ_TYPE_COMMIT:
8268 *commit_id = obj_id;
8269 break;
8270 case GOT_OBJ_TYPE_TAG:
8271 err = got_object_open_as_tag(&tag, repo, obj_id);
8272 if (err)
8273 goto done;
8274 free(obj_id);
8275 err = got_object_get_type(&obj_type, repo,
8276 got_object_tag_get_object_id(tag));
8277 if (err)
8278 goto done;
8279 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8280 err = got_error(GOT_ERR_OBJ_TYPE);
8281 goto done;
8283 *commit_id = got_object_id_dup(
8284 got_object_tag_get_object_id(tag));
8285 if (*commit_id == NULL) {
8286 err = got_error_from_errno("got_object_id_dup");
8287 goto done;
8289 break;
8290 default:
8291 err = got_error(GOT_ERR_OBJ_TYPE);
8292 break;
8295 done:
8296 if (tag)
8297 got_object_tag_close(tag);
8298 if (err) {
8299 free(*commit_id);
8300 *commit_id = NULL;
8302 return err;
8305 static const struct got_error *
8306 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8307 struct tog_reflist_entry *re, struct got_repository *repo)
8309 struct tog_view *log_view;
8310 const struct got_error *err = NULL;
8311 struct got_object_id *commit_id = NULL;
8313 *new_view = NULL;
8315 err = resolve_reflist_entry(&commit_id, re, repo);
8316 if (err) {
8317 if (err->code != GOT_ERR_OBJ_TYPE)
8318 return err;
8319 else
8320 return NULL;
8323 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8324 if (log_view == NULL) {
8325 err = got_error_from_errno("view_open");
8326 goto done;
8329 err = open_log_view(log_view, commit_id, repo,
8330 got_ref_get_name(re->ref), "", 0);
8331 done:
8332 if (err)
8333 view_close(log_view);
8334 else
8335 *new_view = log_view;
8336 free(commit_id);
8337 return err;
8340 static void
8341 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8343 struct tog_reflist_entry *re;
8344 int i = 0;
8346 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8347 return;
8349 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8350 while (i++ < maxscroll) {
8351 if (re == NULL)
8352 break;
8353 s->first_displayed_entry = re;
8354 re = TAILQ_PREV(re, tog_reflist_head, entry);
8358 static const struct got_error *
8359 ref_scroll_down(struct tog_view *view, int maxscroll)
8361 struct tog_ref_view_state *s = &view->state.ref;
8362 struct tog_reflist_entry *next, *last;
8363 int n = 0;
8365 if (s->first_displayed_entry)
8366 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8367 else
8368 next = TAILQ_FIRST(&s->refs);
8370 last = s->last_displayed_entry;
8371 while (next && n++ < maxscroll) {
8372 if (last) {
8373 s->last_displayed_entry = last;
8374 last = TAILQ_NEXT(last, entry);
8376 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8377 s->first_displayed_entry = next;
8378 next = TAILQ_NEXT(next, entry);
8382 return NULL;
8385 static const struct got_error *
8386 search_start_ref_view(struct tog_view *view)
8388 struct tog_ref_view_state *s = &view->state.ref;
8390 s->matched_entry = NULL;
8391 return NULL;
8394 static int
8395 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8397 regmatch_t regmatch;
8399 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8400 0) == 0;
8403 static const struct got_error *
8404 search_next_ref_view(struct tog_view *view)
8406 struct tog_ref_view_state *s = &view->state.ref;
8407 struct tog_reflist_entry *re = NULL;
8409 if (!view->searching) {
8410 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8411 return NULL;
8414 if (s->matched_entry) {
8415 if (view->searching == TOG_SEARCH_FORWARD) {
8416 if (s->selected_entry)
8417 re = TAILQ_NEXT(s->selected_entry, entry);
8418 else
8419 re = TAILQ_PREV(s->selected_entry,
8420 tog_reflist_head, entry);
8421 } else {
8422 if (s->selected_entry == NULL)
8423 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8424 else
8425 re = TAILQ_PREV(s->selected_entry,
8426 tog_reflist_head, entry);
8428 } else {
8429 if (s->selected_entry)
8430 re = s->selected_entry;
8431 else if (view->searching == TOG_SEARCH_FORWARD)
8432 re = TAILQ_FIRST(&s->refs);
8433 else
8434 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8437 while (1) {
8438 if (re == NULL) {
8439 if (s->matched_entry == NULL) {
8440 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8441 return NULL;
8443 if (view->searching == TOG_SEARCH_FORWARD)
8444 re = TAILQ_FIRST(&s->refs);
8445 else
8446 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8449 if (match_reflist_entry(re, &view->regex)) {
8450 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8451 s->matched_entry = re;
8452 break;
8455 if (view->searching == TOG_SEARCH_FORWARD)
8456 re = TAILQ_NEXT(re, entry);
8457 else
8458 re = TAILQ_PREV(re, tog_reflist_head, entry);
8461 if (s->matched_entry) {
8462 s->first_displayed_entry = s->matched_entry;
8463 s->selected = 0;
8466 return NULL;
8469 static const struct got_error *
8470 show_ref_view(struct tog_view *view)
8472 const struct got_error *err = NULL;
8473 struct tog_ref_view_state *s = &view->state.ref;
8474 struct tog_reflist_entry *re;
8475 char *line = NULL;
8476 wchar_t *wline;
8477 struct tog_color *tc;
8478 int width, n, scrollx;
8479 int limit = view->nlines;
8481 werase(view->window);
8483 s->ndisplayed = 0;
8484 if (view_is_hsplit_top(view))
8485 --limit; /* border */
8487 if (limit == 0)
8488 return NULL;
8490 re = s->first_displayed_entry;
8492 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8493 s->nrefs) == -1)
8494 return got_error_from_errno("asprintf");
8496 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8497 if (err) {
8498 free(line);
8499 return err;
8501 if (view_needs_focus_indication(view))
8502 wstandout(view->window);
8503 waddwstr(view->window, wline);
8504 while (width++ < view->ncols)
8505 waddch(view->window, ' ');
8506 if (view_needs_focus_indication(view))
8507 wstandend(view->window);
8508 free(wline);
8509 wline = NULL;
8510 free(line);
8511 line = NULL;
8512 if (--limit <= 0)
8513 return NULL;
8515 n = 0;
8516 view->maxx = 0;
8517 while (re && limit > 0) {
8518 char *line = NULL;
8519 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8521 if (s->show_date) {
8522 struct got_commit_object *ci;
8523 struct got_tag_object *tag;
8524 struct got_object_id *id;
8525 struct tm tm;
8526 time_t t;
8528 err = got_ref_resolve(&id, s->repo, re->ref);
8529 if (err)
8530 return err;
8531 err = got_object_open_as_tag(&tag, s->repo, id);
8532 if (err) {
8533 if (err->code != GOT_ERR_OBJ_TYPE) {
8534 free(id);
8535 return err;
8537 err = got_object_open_as_commit(&ci, s->repo,
8538 id);
8539 if (err) {
8540 free(id);
8541 return err;
8543 t = got_object_commit_get_committer_time(ci);
8544 got_object_commit_close(ci);
8545 } else {
8546 t = got_object_tag_get_tagger_time(tag);
8547 got_object_tag_close(tag);
8549 free(id);
8550 if (gmtime_r(&t, &tm) == NULL)
8551 return got_error_from_errno("gmtime_r");
8552 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8553 return got_error(GOT_ERR_NO_SPACE);
8555 if (got_ref_is_symbolic(re->ref)) {
8556 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8557 ymd : "", got_ref_get_name(re->ref),
8558 got_ref_get_symref_target(re->ref)) == -1)
8559 return got_error_from_errno("asprintf");
8560 } else if (s->show_ids) {
8561 struct got_object_id *id;
8562 char *id_str;
8563 err = got_ref_resolve(&id, s->repo, re->ref);
8564 if (err)
8565 return err;
8566 err = got_object_id_str(&id_str, id);
8567 if (err) {
8568 free(id);
8569 return err;
8571 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8572 got_ref_get_name(re->ref), id_str) == -1) {
8573 err = got_error_from_errno("asprintf");
8574 free(id);
8575 free(id_str);
8576 return err;
8578 free(id);
8579 free(id_str);
8580 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8581 got_ref_get_name(re->ref)) == -1)
8582 return got_error_from_errno("asprintf");
8584 /* use full line width to determine view->maxx */
8585 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8586 if (err) {
8587 free(line);
8588 return err;
8590 view->maxx = MAX(view->maxx, width);
8591 free(wline);
8592 wline = NULL;
8594 err = format_line(&wline, &width, &scrollx, line, view->x,
8595 view->ncols, 0, 0);
8596 if (err) {
8597 free(line);
8598 return err;
8600 if (n == s->selected) {
8601 if (view->focussed)
8602 wstandout(view->window);
8603 s->selected_entry = re;
8605 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8606 if (tc)
8607 wattr_on(view->window,
8608 COLOR_PAIR(tc->colorpair), NULL);
8609 waddwstr(view->window, &wline[scrollx]);
8610 if (tc)
8611 wattr_off(view->window,
8612 COLOR_PAIR(tc->colorpair), NULL);
8613 if (width < view->ncols)
8614 waddch(view->window, '\n');
8615 if (n == s->selected && view->focussed)
8616 wstandend(view->window);
8617 free(line);
8618 free(wline);
8619 wline = NULL;
8620 n++;
8621 s->ndisplayed++;
8622 s->last_displayed_entry = re;
8624 limit--;
8625 re = TAILQ_NEXT(re, entry);
8628 view_border(view);
8629 return err;
8632 static const struct got_error *
8633 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8634 struct tog_reflist_entry *re, struct got_repository *repo)
8636 const struct got_error *err = NULL;
8637 struct got_object_id *commit_id = NULL;
8638 struct tog_view *tree_view;
8640 *new_view = NULL;
8642 err = resolve_reflist_entry(&commit_id, re, repo);
8643 if (err) {
8644 if (err->code != GOT_ERR_OBJ_TYPE)
8645 return err;
8646 else
8647 return NULL;
8651 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8652 if (tree_view == NULL) {
8653 err = got_error_from_errno("view_open");
8654 goto done;
8657 err = open_tree_view(tree_view, commit_id,
8658 got_ref_get_name(re->ref), repo);
8659 if (err)
8660 goto done;
8662 *new_view = tree_view;
8663 done:
8664 free(commit_id);
8665 return err;
8668 static const struct got_error *
8669 ref_goto_line(struct tog_view *view, int nlines)
8671 const struct got_error *err = NULL;
8672 struct tog_ref_view_state *s = &view->state.ref;
8673 int g, idx = s->selected_entry->idx;
8675 g = view->gline;
8676 view->gline = 0;
8678 if (g == 0)
8679 g = 1;
8680 else if (g > s->nrefs)
8681 g = s->nrefs;
8683 if (g >= s->first_displayed_entry->idx + 1 &&
8684 g <= s->last_displayed_entry->idx + 1 &&
8685 g - s->first_displayed_entry->idx - 1 < nlines) {
8686 s->selected = g - s->first_displayed_entry->idx - 1;
8687 return NULL;
8690 if (idx + 1 < g) {
8691 err = ref_scroll_down(view, g - idx - 1);
8692 if (err)
8693 return err;
8694 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8695 s->first_displayed_entry->idx + s->selected < g &&
8696 s->selected < s->ndisplayed - 1)
8697 s->selected = g - s->first_displayed_entry->idx - 1;
8698 } else if (idx + 1 > g)
8699 ref_scroll_up(s, idx - g + 1);
8701 if (g < nlines && s->first_displayed_entry->idx == 0)
8702 s->selected = g - 1;
8704 return NULL;
8708 static const struct got_error *
8709 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8711 const struct got_error *err = NULL;
8712 struct tog_ref_view_state *s = &view->state.ref;
8713 struct tog_reflist_entry *re;
8714 int n, nscroll = view->nlines - 1;
8716 if (view->gline)
8717 return ref_goto_line(view, nscroll);
8719 switch (ch) {
8720 case '0':
8721 case '$':
8722 case KEY_RIGHT:
8723 case 'l':
8724 case KEY_LEFT:
8725 case 'h':
8726 horizontal_scroll_input(view, ch);
8727 break;
8728 case 'i':
8729 s->show_ids = !s->show_ids;
8730 view->count = 0;
8731 break;
8732 case 'm':
8733 s->show_date = !s->show_date;
8734 view->count = 0;
8735 break;
8736 case 'o':
8737 s->sort_by_date = !s->sort_by_date;
8738 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8739 view->count = 0;
8740 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8741 got_ref_cmp_by_commit_timestamp_descending :
8742 tog_ref_cmp_by_name, s->repo);
8743 if (err)
8744 break;
8745 got_reflist_object_id_map_free(tog_refs_idmap);
8746 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8747 &tog_refs, s->repo);
8748 if (err)
8749 break;
8750 ref_view_free_refs(s);
8751 err = ref_view_load_refs(s);
8752 break;
8753 case KEY_ENTER:
8754 case '\r':
8755 view->count = 0;
8756 if (!s->selected_entry)
8757 break;
8758 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8759 break;
8760 case 'T':
8761 view->count = 0;
8762 if (!s->selected_entry)
8763 break;
8764 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8765 break;
8766 case 'g':
8767 case '=':
8768 case KEY_HOME:
8769 s->selected = 0;
8770 view->count = 0;
8771 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8772 break;
8773 case 'G':
8774 case '*':
8775 case KEY_END: {
8776 int eos = view->nlines - 1;
8778 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8779 --eos; /* border */
8780 s->selected = 0;
8781 view->count = 0;
8782 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8783 for (n = 0; n < eos; n++) {
8784 if (re == NULL)
8785 break;
8786 s->first_displayed_entry = re;
8787 re = TAILQ_PREV(re, tog_reflist_head, entry);
8789 if (n > 0)
8790 s->selected = n - 1;
8791 break;
8793 case 'k':
8794 case KEY_UP:
8795 case CTRL('p'):
8796 if (s->selected > 0) {
8797 s->selected--;
8798 break;
8800 ref_scroll_up(s, 1);
8801 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8802 view->count = 0;
8803 break;
8804 case CTRL('u'):
8805 case 'u':
8806 nscroll /= 2;
8807 /* FALL THROUGH */
8808 case KEY_PPAGE:
8809 case CTRL('b'):
8810 case 'b':
8811 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8812 s->selected -= MIN(nscroll, s->selected);
8813 ref_scroll_up(s, MAX(0, nscroll));
8814 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8815 view->count = 0;
8816 break;
8817 case 'j':
8818 case KEY_DOWN:
8819 case CTRL('n'):
8820 if (s->selected < s->ndisplayed - 1) {
8821 s->selected++;
8822 break;
8824 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8825 /* can't scroll any further */
8826 view->count = 0;
8827 break;
8829 ref_scroll_down(view, 1);
8830 break;
8831 case CTRL('d'):
8832 case 'd':
8833 nscroll /= 2;
8834 /* FALL THROUGH */
8835 case KEY_NPAGE:
8836 case CTRL('f'):
8837 case 'f':
8838 case ' ':
8839 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8840 /* can't scroll any further; move cursor down */
8841 if (s->selected < s->ndisplayed - 1)
8842 s->selected += MIN(nscroll,
8843 s->ndisplayed - s->selected - 1);
8844 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8845 s->selected += s->ndisplayed - s->selected - 1;
8846 view->count = 0;
8847 break;
8849 ref_scroll_down(view, nscroll);
8850 break;
8851 case CTRL('l'):
8852 view->count = 0;
8853 tog_free_refs();
8854 err = tog_load_refs(s->repo, s->sort_by_date);
8855 if (err)
8856 break;
8857 ref_view_free_refs(s);
8858 err = ref_view_load_refs(s);
8859 break;
8860 case KEY_RESIZE:
8861 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8862 s->selected = view->nlines - 2;
8863 break;
8864 default:
8865 view->count = 0;
8866 break;
8869 return err;
8872 __dead static void
8873 usage_ref(void)
8875 endwin();
8876 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8877 getprogname());
8878 exit(1);
8881 static const struct got_error *
8882 cmd_ref(int argc, char *argv[])
8884 const struct got_error *error;
8885 struct got_repository *repo = NULL;
8886 struct got_worktree *worktree = NULL;
8887 char *cwd = NULL, *repo_path = NULL;
8888 int ch;
8889 struct tog_view *view;
8890 int *pack_fds = NULL;
8892 while ((ch = getopt(argc, argv, "r:")) != -1) {
8893 switch (ch) {
8894 case 'r':
8895 repo_path = realpath(optarg, NULL);
8896 if (repo_path == NULL)
8897 return got_error_from_errno2("realpath",
8898 optarg);
8899 break;
8900 default:
8901 usage_ref();
8902 /* NOTREACHED */
8906 argc -= optind;
8907 argv += optind;
8909 if (argc > 1)
8910 usage_ref();
8912 error = got_repo_pack_fds_open(&pack_fds);
8913 if (error != NULL)
8914 goto done;
8916 if (repo_path == NULL) {
8917 cwd = getcwd(NULL, 0);
8918 if (cwd == NULL)
8919 return got_error_from_errno("getcwd");
8920 error = got_worktree_open(&worktree, cwd);
8921 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8922 goto done;
8923 if (worktree)
8924 repo_path =
8925 strdup(got_worktree_get_repo_path(worktree));
8926 else
8927 repo_path = strdup(cwd);
8928 if (repo_path == NULL) {
8929 error = got_error_from_errno("strdup");
8930 goto done;
8934 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8935 if (error != NULL)
8936 goto done;
8938 init_curses();
8940 error = apply_unveil(got_repo_get_path(repo), NULL);
8941 if (error)
8942 goto done;
8944 error = tog_load_refs(repo, 0);
8945 if (error)
8946 goto done;
8948 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8949 if (view == NULL) {
8950 error = got_error_from_errno("view_open");
8951 goto done;
8954 error = open_ref_view(view, repo);
8955 if (error)
8956 goto done;
8958 if (worktree) {
8959 /* Release work tree lock. */
8960 got_worktree_close(worktree);
8961 worktree = NULL;
8963 error = view_loop(view);
8964 done:
8965 free(repo_path);
8966 free(cwd);
8967 if (repo) {
8968 const struct got_error *close_err = got_repo_close(repo);
8969 if (close_err)
8970 error = close_err;
8972 if (pack_fds) {
8973 const struct got_error *pack_err =
8974 got_repo_pack_fds_close(pack_fds);
8975 if (error == NULL)
8976 error = pack_err;
8978 tog_free_refs();
8979 return error;
8982 static const struct got_error*
8983 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8984 const char *str)
8986 size_t len;
8988 if (win == NULL)
8989 win = stdscr;
8991 len = strlen(str);
8992 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8994 if (focus)
8995 wstandout(win);
8996 if (mvwprintw(win, y, x, "%s", str) == ERR)
8997 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8998 if (focus)
8999 wstandend(win);
9001 return NULL;
9004 static const struct got_error *
9005 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
9007 off_t *p;
9009 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
9010 if (p == NULL) {
9011 free(*line_offsets);
9012 *line_offsets = NULL;
9013 return got_error_from_errno("reallocarray");
9016 *line_offsets = p;
9017 (*line_offsets)[*nlines] = off;
9018 ++(*nlines);
9019 return NULL;
9022 static const struct got_error *
9023 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
9025 *ret = 0;
9027 for (;n > 0; --n, ++km) {
9028 char *t0, *t, *k;
9029 size_t len = 1;
9031 if (km->keys == NULL)
9032 continue;
9034 t = t0 = strdup(km->keys);
9035 if (t0 == NULL)
9036 return got_error_from_errno("strdup");
9038 len += strlen(t);
9039 while ((k = strsep(&t, " ")) != NULL)
9040 len += strlen(k) > 1 ? 2 : 0;
9041 free(t0);
9042 *ret = MAX(*ret, len);
9045 return NULL;
9049 * Write keymap section headers, keys, and key info in km to f.
9050 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9051 * wrap control and symbolic keys in guillemets, else use <>.
9053 static const struct got_error *
9054 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9056 int n, len = width;
9058 if (km->keys) {
9059 static const char *u8_glyph[] = {
9060 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9061 "\xe2\x80\xba" /* U+203A (utf8 >) */
9063 char *t0, *t, *k;
9064 int cs, s, first = 1;
9066 cs = got_locale_is_utf8();
9068 t = t0 = strdup(km->keys);
9069 if (t0 == NULL)
9070 return got_error_from_errno("strdup");
9072 len = strlen(km->keys);
9073 while ((k = strsep(&t, " ")) != NULL) {
9074 s = strlen(k) > 1; /* control or symbolic key */
9075 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9076 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9077 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9078 if (n < 0) {
9079 free(t0);
9080 return got_error_from_errno("fprintf");
9082 first = 0;
9083 len += s ? 2 : 0;
9084 *off += n;
9086 free(t0);
9088 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9089 if (n < 0)
9090 return got_error_from_errno("fprintf");
9091 *off += n;
9093 return NULL;
9096 static const struct got_error *
9097 format_help(struct tog_help_view_state *s)
9099 const struct got_error *err = NULL;
9100 off_t off = 0;
9101 int i, max, n, show = s->all;
9102 static const struct tog_key_map km[] = {
9103 #define KEYMAP_(info, type) { NULL, (info), type }
9104 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9105 GENERATE_HELP
9106 #undef KEYMAP_
9107 #undef KEY_
9110 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9111 if (err)
9112 return err;
9114 n = nitems(km);
9115 err = max_key_str(&max, km, n);
9116 if (err)
9117 return err;
9119 for (i = 0; i < n; ++i) {
9120 if (km[i].keys == NULL) {
9121 show = s->all;
9122 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9123 km[i].type == s->type || s->all)
9124 show = 1;
9126 if (show) {
9127 err = format_help_line(&off, s->f, &km[i], max);
9128 if (err)
9129 return err;
9130 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9131 if (err)
9132 return err;
9135 fputc('\n', s->f);
9136 ++off;
9137 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9138 return err;
9141 static const struct got_error *
9142 create_help(struct tog_help_view_state *s)
9144 FILE *f;
9145 const struct got_error *err;
9147 free(s->line_offsets);
9148 s->line_offsets = NULL;
9149 s->nlines = 0;
9151 f = got_opentemp();
9152 if (f == NULL)
9153 return got_error_from_errno("got_opentemp");
9154 s->f = f;
9156 err = format_help(s);
9157 if (err)
9158 return err;
9160 if (s->f && fflush(s->f) != 0)
9161 return got_error_from_errno("fflush");
9163 return NULL;
9166 static const struct got_error *
9167 search_start_help_view(struct tog_view *view)
9169 view->state.help.matched_line = 0;
9170 return NULL;
9173 static void
9174 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9175 size_t *nlines, int **first, int **last, int **match, int **selected)
9177 struct tog_help_view_state *s = &view->state.help;
9179 *f = s->f;
9180 *nlines = s->nlines;
9181 *line_offsets = s->line_offsets;
9182 *match = &s->matched_line;
9183 *first = &s->first_displayed_line;
9184 *last = &s->last_displayed_line;
9185 *selected = &s->selected_line;
9188 static const struct got_error *
9189 show_help_view(struct tog_view *view)
9191 struct tog_help_view_state *s = &view->state.help;
9192 const struct got_error *err;
9193 regmatch_t *regmatch = &view->regmatch;
9194 wchar_t *wline;
9195 char *line;
9196 ssize_t linelen;
9197 size_t linesz = 0;
9198 int width, nprinted = 0, rc = 0;
9199 int eos = view->nlines;
9201 if (view_is_hsplit_top(view))
9202 --eos; /* account for border */
9204 s->lineno = 0;
9205 rewind(s->f);
9206 werase(view->window);
9208 if (view->gline > s->nlines - 1)
9209 view->gline = s->nlines - 1;
9211 err = win_draw_center(view->window, 0, 0, view->ncols,
9212 view_needs_focus_indication(view),
9213 "tog help (press q to return to tog)");
9214 if (err)
9215 return err;
9216 if (eos <= 1)
9217 return NULL;
9218 waddstr(view->window, "\n\n");
9219 eos -= 2;
9221 s->eof = 0;
9222 view->maxx = 0;
9223 line = NULL;
9224 while (eos > 0 && nprinted < eos) {
9225 attr_t attr = 0;
9227 linelen = getline(&line, &linesz, s->f);
9228 if (linelen == -1) {
9229 if (!feof(s->f)) {
9230 free(line);
9231 return got_ferror(s->f, GOT_ERR_IO);
9233 s->eof = 1;
9234 break;
9236 if (++s->lineno < s->first_displayed_line)
9237 continue;
9238 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9239 continue;
9240 if (s->lineno == view->hiline)
9241 attr = A_STANDOUT;
9243 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9244 view->x ? 1 : 0);
9245 if (err) {
9246 free(line);
9247 return err;
9249 view->maxx = MAX(view->maxx, width);
9250 free(wline);
9251 wline = NULL;
9253 if (attr)
9254 wattron(view->window, attr);
9255 if (s->first_displayed_line + nprinted == s->matched_line &&
9256 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9257 err = add_matched_line(&width, line, view->ncols - 1, 0,
9258 view->window, view->x, regmatch);
9259 if (err) {
9260 free(line);
9261 return err;
9263 } else {
9264 int skip;
9266 err = format_line(&wline, &width, &skip, line,
9267 view->x, view->ncols, 0, view->x ? 1 : 0);
9268 if (err) {
9269 free(line);
9270 return err;
9272 waddwstr(view->window, &wline[skip]);
9273 free(wline);
9274 wline = NULL;
9276 if (s->lineno == view->hiline) {
9277 while (width++ < view->ncols)
9278 waddch(view->window, ' ');
9279 } else {
9280 if (width < view->ncols)
9281 waddch(view->window, '\n');
9283 if (attr)
9284 wattroff(view->window, attr);
9285 if (++nprinted == 1)
9286 s->first_displayed_line = s->lineno;
9288 free(line);
9289 if (nprinted > 0)
9290 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9291 else
9292 s->last_displayed_line = s->first_displayed_line;
9294 view_border(view);
9296 if (s->eof) {
9297 rc = waddnstr(view->window,
9298 "See the tog(1) manual page for full documentation",
9299 view->ncols - 1);
9300 if (rc == ERR)
9301 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9302 } else {
9303 wmove(view->window, view->nlines - 1, 0);
9304 wclrtoeol(view->window);
9305 wstandout(view->window);
9306 rc = waddnstr(view->window, "scroll down for more...",
9307 view->ncols - 1);
9308 if (rc == ERR)
9309 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9310 if (getcurx(view->window) < view->ncols - 6) {
9311 rc = wprintw(view->window, "[%.0f%%]",
9312 100.00 * s->last_displayed_line / s->nlines);
9313 if (rc == ERR)
9314 return got_error_msg(GOT_ERR_IO, "wprintw");
9316 wstandend(view->window);
9319 return NULL;
9322 static const struct got_error *
9323 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9325 struct tog_help_view_state *s = &view->state.help;
9326 const struct got_error *err = NULL;
9327 char *line = NULL;
9328 ssize_t linelen;
9329 size_t linesz = 0;
9330 int eos, nscroll;
9332 eos = nscroll = view->nlines;
9333 if (view_is_hsplit_top(view))
9334 --eos; /* border */
9336 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9338 switch (ch) {
9339 case '0':
9340 case '$':
9341 case KEY_RIGHT:
9342 case 'l':
9343 case KEY_LEFT:
9344 case 'h':
9345 horizontal_scroll_input(view, ch);
9346 break;
9347 case 'g':
9348 case KEY_HOME:
9349 s->first_displayed_line = 1;
9350 view->count = 0;
9351 break;
9352 case 'G':
9353 case KEY_END:
9354 view->count = 0;
9355 if (s->eof)
9356 break;
9357 s->first_displayed_line = (s->nlines - eos) + 3;
9358 s->eof = 1;
9359 break;
9360 case 'k':
9361 case KEY_UP:
9362 if (s->first_displayed_line > 1)
9363 --s->first_displayed_line;
9364 else
9365 view->count = 0;
9366 break;
9367 case CTRL('u'):
9368 case 'u':
9369 nscroll /= 2;
9370 /* FALL THROUGH */
9371 case KEY_PPAGE:
9372 case CTRL('b'):
9373 case 'b':
9374 if (s->first_displayed_line == 1) {
9375 view->count = 0;
9376 break;
9378 while (--nscroll > 0 && s->first_displayed_line > 1)
9379 s->first_displayed_line--;
9380 break;
9381 case 'j':
9382 case KEY_DOWN:
9383 case CTRL('n'):
9384 if (!s->eof)
9385 ++s->first_displayed_line;
9386 else
9387 view->count = 0;
9388 break;
9389 case CTRL('d'):
9390 case 'd':
9391 nscroll /= 2;
9392 /* FALL THROUGH */
9393 case KEY_NPAGE:
9394 case CTRL('f'):
9395 case 'f':
9396 case ' ':
9397 if (s->eof) {
9398 view->count = 0;
9399 break;
9401 while (!s->eof && --nscroll > 0) {
9402 linelen = getline(&line, &linesz, s->f);
9403 s->first_displayed_line++;
9404 if (linelen == -1) {
9405 if (feof(s->f))
9406 s->eof = 1;
9407 else
9408 err = got_ferror(s->f, GOT_ERR_IO);
9409 break;
9412 free(line);
9413 break;
9414 default:
9415 view->count = 0;
9416 break;
9419 return err;
9422 static const struct got_error *
9423 close_help_view(struct tog_view *view)
9425 struct tog_help_view_state *s = &view->state.help;
9427 free(s->line_offsets);
9428 s->line_offsets = NULL;
9429 if (fclose(s->f) == EOF)
9430 return got_error_from_errno("fclose");
9432 return NULL;
9435 static const struct got_error *
9436 reset_help_view(struct tog_view *view)
9438 struct tog_help_view_state *s = &view->state.help;
9441 if (s->f && fclose(s->f) == EOF)
9442 return got_error_from_errno("fclose");
9444 wclear(view->window);
9445 view->count = 0;
9446 view->x = 0;
9447 s->all = !s->all;
9448 s->first_displayed_line = 1;
9449 s->last_displayed_line = view->nlines;
9450 s->matched_line = 0;
9452 return create_help(s);
9455 static const struct got_error *
9456 open_help_view(struct tog_view *view, struct tog_view *parent)
9458 const struct got_error *err = NULL;
9459 struct tog_help_view_state *s = &view->state.help;
9461 s->type = (enum tog_keymap_type)parent->type;
9462 s->first_displayed_line = 1;
9463 s->last_displayed_line = view->nlines;
9464 s->selected_line = 1;
9466 view->show = show_help_view;
9467 view->input = input_help_view;
9468 view->reset = reset_help_view;
9469 view->close = close_help_view;
9470 view->search_start = search_start_help_view;
9471 view->search_setup = search_setup_help_view;
9472 view->search_next = search_next_view_match;
9474 err = create_help(s);
9475 return err;
9478 static const struct got_error *
9479 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9480 enum tog_view_type request, int y, int x)
9482 const struct got_error *err = NULL;
9484 *new_view = NULL;
9486 switch (request) {
9487 case TOG_VIEW_DIFF:
9488 if (view->type == TOG_VIEW_LOG) {
9489 struct tog_log_view_state *s = &view->state.log;
9491 err = open_diff_view_for_commit(new_view, y, x,
9492 s->selected_entry->commit, s->selected_entry->id,
9493 view, s->repo);
9494 } else
9495 return got_error_msg(GOT_ERR_NOT_IMPL,
9496 "parent/child view pair not supported");
9497 break;
9498 case TOG_VIEW_BLAME:
9499 if (view->type == TOG_VIEW_TREE) {
9500 struct tog_tree_view_state *s = &view->state.tree;
9502 err = blame_tree_entry(new_view, y, x,
9503 s->selected_entry, &s->parents, s->commit_id,
9504 s->repo);
9505 } else
9506 return got_error_msg(GOT_ERR_NOT_IMPL,
9507 "parent/child view pair not supported");
9508 break;
9509 case TOG_VIEW_LOG:
9510 if (view->type == TOG_VIEW_BLAME)
9511 err = log_annotated_line(new_view, y, x,
9512 view->state.blame.repo, view->state.blame.id_to_log);
9513 else if (view->type == TOG_VIEW_TREE)
9514 err = log_selected_tree_entry(new_view, y, x,
9515 &view->state.tree);
9516 else if (view->type == TOG_VIEW_REF)
9517 err = log_ref_entry(new_view, y, x,
9518 view->state.ref.selected_entry,
9519 view->state.ref.repo);
9520 else
9521 return got_error_msg(GOT_ERR_NOT_IMPL,
9522 "parent/child view pair not supported");
9523 break;
9524 case TOG_VIEW_TREE:
9525 if (view->type == TOG_VIEW_LOG)
9526 err = browse_commit_tree(new_view, y, x,
9527 view->state.log.selected_entry,
9528 view->state.log.in_repo_path,
9529 view->state.log.head_ref_name,
9530 view->state.log.repo);
9531 else if (view->type == TOG_VIEW_REF)
9532 err = browse_ref_tree(new_view, y, x,
9533 view->state.ref.selected_entry,
9534 view->state.ref.repo);
9535 else
9536 return got_error_msg(GOT_ERR_NOT_IMPL,
9537 "parent/child view pair not supported");
9538 break;
9539 case TOG_VIEW_REF:
9540 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9541 if (*new_view == NULL)
9542 return got_error_from_errno("view_open");
9543 if (view->type == TOG_VIEW_LOG)
9544 err = open_ref_view(*new_view, view->state.log.repo);
9545 else if (view->type == TOG_VIEW_TREE)
9546 err = open_ref_view(*new_view, view->state.tree.repo);
9547 else
9548 err = got_error_msg(GOT_ERR_NOT_IMPL,
9549 "parent/child view pair not supported");
9550 if (err)
9551 view_close(*new_view);
9552 break;
9553 case TOG_VIEW_HELP:
9554 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9555 if (*new_view == NULL)
9556 return got_error_from_errno("view_open");
9557 err = open_help_view(*new_view, view);
9558 if (err)
9559 view_close(*new_view);
9560 break;
9561 default:
9562 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9565 return err;
9569 * If view was scrolled down to move the selected line into view when opening a
9570 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9572 static void
9573 offset_selection_up(struct tog_view *view)
9575 switch (view->type) {
9576 case TOG_VIEW_BLAME: {
9577 struct tog_blame_view_state *s = &view->state.blame;
9578 if (s->first_displayed_line == 1) {
9579 s->selected_line = MAX(s->selected_line - view->offset,
9580 1);
9581 break;
9583 if (s->first_displayed_line > view->offset)
9584 s->first_displayed_line -= view->offset;
9585 else
9586 s->first_displayed_line = 1;
9587 s->selected_line += view->offset;
9588 break;
9590 case TOG_VIEW_LOG:
9591 log_scroll_up(&view->state.log, view->offset);
9592 view->state.log.selected += view->offset;
9593 break;
9594 case TOG_VIEW_REF:
9595 ref_scroll_up(&view->state.ref, view->offset);
9596 view->state.ref.selected += view->offset;
9597 break;
9598 case TOG_VIEW_TREE:
9599 tree_scroll_up(&view->state.tree, view->offset);
9600 view->state.tree.selected += view->offset;
9601 break;
9602 default:
9603 break;
9606 view->offset = 0;
9610 * If the selected line is in the section of screen covered by the bottom split,
9611 * scroll down offset lines to move it into view and index its new position.
9613 static const struct got_error *
9614 offset_selection_down(struct tog_view *view)
9616 const struct got_error *err = NULL;
9617 const struct got_error *(*scrolld)(struct tog_view *, int);
9618 int *selected = NULL;
9619 int header, offset;
9621 switch (view->type) {
9622 case TOG_VIEW_BLAME: {
9623 struct tog_blame_view_state *s = &view->state.blame;
9624 header = 3;
9625 scrolld = NULL;
9626 if (s->selected_line > view->nlines - header) {
9627 offset = abs(view->nlines - s->selected_line - header);
9628 s->first_displayed_line += offset;
9629 s->selected_line -= offset;
9630 view->offset = offset;
9632 break;
9634 case TOG_VIEW_LOG: {
9635 struct tog_log_view_state *s = &view->state.log;
9636 scrolld = &log_scroll_down;
9637 header = view_is_parent_view(view) ? 3 : 2;
9638 selected = &s->selected;
9639 break;
9641 case TOG_VIEW_REF: {
9642 struct tog_ref_view_state *s = &view->state.ref;
9643 scrolld = &ref_scroll_down;
9644 header = 3;
9645 selected = &s->selected;
9646 break;
9648 case TOG_VIEW_TREE: {
9649 struct tog_tree_view_state *s = &view->state.tree;
9650 scrolld = &tree_scroll_down;
9651 header = 5;
9652 selected = &s->selected;
9653 break;
9655 default:
9656 selected = NULL;
9657 scrolld = NULL;
9658 header = 0;
9659 break;
9662 if (selected && *selected > view->nlines - header) {
9663 offset = abs(view->nlines - *selected - header);
9664 view->offset = offset;
9665 if (scrolld && offset) {
9666 err = scrolld(view, offset);
9667 *selected -= offset;
9671 return err;
9674 static void
9675 list_commands(FILE *fp)
9677 size_t i;
9679 fprintf(fp, "commands:");
9680 for (i = 0; i < nitems(tog_commands); i++) {
9681 const struct tog_cmd *cmd = &tog_commands[i];
9682 fprintf(fp, " %s", cmd->name);
9684 fputc('\n', fp);
9687 __dead static void
9688 usage(int hflag, int status)
9690 FILE *fp = (status == 0) ? stdout : stderr;
9692 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9693 getprogname());
9694 if (hflag) {
9695 fprintf(fp, "lazy usage: %s path\n", getprogname());
9696 list_commands(fp);
9698 exit(status);
9701 static char **
9702 make_argv(int argc, ...)
9704 va_list ap;
9705 char **argv;
9706 int i;
9708 va_start(ap, argc);
9710 argv = calloc(argc, sizeof(char *));
9711 if (argv == NULL)
9712 err(1, "calloc");
9713 for (i = 0; i < argc; i++) {
9714 argv[i] = strdup(va_arg(ap, char *));
9715 if (argv[i] == NULL)
9716 err(1, "strdup");
9719 va_end(ap);
9720 return argv;
9724 * Try to convert 'tog path' into a 'tog log path' command.
9725 * The user could simply have mistyped the command rather than knowingly
9726 * provided a path. So check whether argv[0] can in fact be resolved
9727 * to a path in the HEAD commit and print a special error if not.
9728 * This hack is for mpi@ <3
9730 static const struct got_error *
9731 tog_log_with_path(int argc, char *argv[])
9733 const struct got_error *error = NULL, *close_err;
9734 const struct tog_cmd *cmd = NULL;
9735 struct got_repository *repo = NULL;
9736 struct got_worktree *worktree = NULL;
9737 struct got_object_id *commit_id = NULL, *id = NULL;
9738 struct got_commit_object *commit = NULL;
9739 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9740 char *commit_id_str = NULL, **cmd_argv = NULL;
9741 int *pack_fds = NULL;
9743 cwd = getcwd(NULL, 0);
9744 if (cwd == NULL)
9745 return got_error_from_errno("getcwd");
9747 error = got_repo_pack_fds_open(&pack_fds);
9748 if (error != NULL)
9749 goto done;
9751 error = got_worktree_open(&worktree, cwd);
9752 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9753 goto done;
9755 if (worktree)
9756 repo_path = strdup(got_worktree_get_repo_path(worktree));
9757 else
9758 repo_path = strdup(cwd);
9759 if (repo_path == NULL) {
9760 error = got_error_from_errno("strdup");
9761 goto done;
9764 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9765 if (error != NULL)
9766 goto done;
9768 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9769 repo, worktree);
9770 if (error)
9771 goto done;
9773 error = tog_load_refs(repo, 0);
9774 if (error)
9775 goto done;
9776 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9777 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9778 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9779 if (error)
9780 goto done;
9782 if (worktree) {
9783 got_worktree_close(worktree);
9784 worktree = NULL;
9787 error = got_object_open_as_commit(&commit, repo, commit_id);
9788 if (error)
9789 goto done;
9791 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9792 if (error) {
9793 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9794 goto done;
9795 fprintf(stderr, "%s: '%s' is no known command or path\n",
9796 getprogname(), argv[0]);
9797 usage(1, 1);
9798 /* not reached */
9801 error = got_object_id_str(&commit_id_str, commit_id);
9802 if (error)
9803 goto done;
9805 cmd = &tog_commands[0]; /* log */
9806 argc = 4;
9807 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9808 error = cmd->cmd_main(argc, cmd_argv);
9809 done:
9810 if (repo) {
9811 close_err = got_repo_close(repo);
9812 if (error == NULL)
9813 error = close_err;
9815 if (commit)
9816 got_object_commit_close(commit);
9817 if (worktree)
9818 got_worktree_close(worktree);
9819 if (pack_fds) {
9820 const struct got_error *pack_err =
9821 got_repo_pack_fds_close(pack_fds);
9822 if (error == NULL)
9823 error = pack_err;
9825 free(id);
9826 free(commit_id_str);
9827 free(commit_id);
9828 free(cwd);
9829 free(repo_path);
9830 free(in_repo_path);
9831 if (cmd_argv) {
9832 int i;
9833 for (i = 0; i < argc; i++)
9834 free(cmd_argv[i]);
9835 free(cmd_argv);
9837 tog_free_refs();
9838 return error;
9841 int
9842 main(int argc, char *argv[])
9844 const struct got_error *io_err, *error = NULL;
9845 const struct tog_cmd *cmd = NULL;
9846 int ch, hflag = 0, Vflag = 0;
9847 char **cmd_argv = NULL;
9848 static const struct option longopts[] = {
9849 { "version", no_argument, NULL, 'V' },
9850 { NULL, 0, NULL, 0}
9852 char *diff_algo_str = NULL;
9853 const char *test_script_path;
9855 setlocale(LC_CTYPE, "");
9858 * Test mode init must happen before pledge() because "tty" will
9859 * not allow TTY-related ioctls to occur via regular files.
9861 test_script_path = getenv("TOG_TEST_SCRIPT");
9862 if (test_script_path != NULL) {
9863 error = init_mock_term(test_script_path);
9864 if (error) {
9865 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9866 return 1;
9868 } else if (!isatty(STDIN_FILENO))
9869 errx(1, "standard input is not a tty");
9871 #if !defined(PROFILE)
9872 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9873 NULL) == -1)
9874 err(1, "pledge");
9875 #endif
9877 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9878 switch (ch) {
9879 case 'h':
9880 hflag = 1;
9881 break;
9882 case 'V':
9883 Vflag = 1;
9884 break;
9885 default:
9886 usage(hflag, 1);
9887 /* NOTREACHED */
9891 argc -= optind;
9892 argv += optind;
9893 optind = 1;
9894 optreset = 1;
9896 if (Vflag) {
9897 got_version_print_str();
9898 return 0;
9901 if (argc == 0) {
9902 if (hflag)
9903 usage(hflag, 0);
9904 /* Build an argument vector which runs a default command. */
9905 cmd = &tog_commands[0];
9906 argc = 1;
9907 cmd_argv = make_argv(argc, cmd->name);
9908 } else {
9909 size_t i;
9911 /* Did the user specify a command? */
9912 for (i = 0; i < nitems(tog_commands); i++) {
9913 if (strncmp(tog_commands[i].name, argv[0],
9914 strlen(argv[0])) == 0) {
9915 cmd = &tog_commands[i];
9916 break;
9921 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9922 if (diff_algo_str) {
9923 if (strcasecmp(diff_algo_str, "patience") == 0)
9924 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9925 if (strcasecmp(diff_algo_str, "myers") == 0)
9926 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9929 if (cmd == NULL) {
9930 if (argc != 1)
9931 usage(0, 1);
9932 /* No command specified; try log with a path */
9933 error = tog_log_with_path(argc, argv);
9934 } else {
9935 if (hflag)
9936 cmd->cmd_usage();
9937 else
9938 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9941 if (using_mock_io) {
9942 io_err = tog_io_close();
9943 if (error == NULL)
9944 error = io_err;
9946 endwin();
9947 if (cmd_argv) {
9948 int i;
9949 for (i = 0; i < argc; i++)
9950 free(cmd_argv[i]);
9951 free(cmd_argv);
9954 if (error && error->code != GOT_ERR_CANCELLED &&
9955 error->code != GOT_ERR_EOF &&
9956 error->code != GOT_ERR_PRIVSEP_EXIT &&
9957 error->code != GOT_ERR_PRIVSEP_PIPE &&
9958 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9959 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9960 return 0;