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 *wrefstr = NULL, *wlogmsg = NULL, *wauthor = NULL;
2410 int author_width, refstr_width, logmsg_width;
2411 char *newline, *line = NULL;
2412 int col, limit, scrollx, logmsg_x;
2413 const int avail = view->ncols;
2414 struct tm tm;
2415 time_t committer_time;
2416 struct tog_color *tc;
2417 struct got_reflist_head *refs;
2419 committer_time = got_object_commit_get_committer_time(commit);
2420 if (gmtime_r(&committer_time, &tm) == NULL)
2421 return got_error_from_errno("gmtime_r");
2422 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2423 return got_error(GOT_ERR_NO_SPACE);
2425 if (avail <= date_display_cols)
2426 limit = MIN(sizeof(datebuf) - 1, avail);
2427 else
2428 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2429 tc = get_color(&s->colors, TOG_COLOR_DATE);
2430 if (tc)
2431 wattr_on(view->window,
2432 COLOR_PAIR(tc->colorpair), NULL);
2433 waddnstr(view->window, datebuf, limit);
2434 if (tc)
2435 wattr_off(view->window,
2436 COLOR_PAIR(tc->colorpair), NULL);
2437 col = limit;
2438 if (col > avail)
2439 goto done;
2441 if (avail >= 120) {
2442 char *id_str;
2443 err = got_object_id_str(&id_str, id);
2444 if (err)
2445 goto done;
2446 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2447 if (tc)
2448 wattr_on(view->window,
2449 COLOR_PAIR(tc->colorpair), NULL);
2450 wprintw(view->window, "%.8s ", id_str);
2451 if (tc)
2452 wattr_off(view->window,
2453 COLOR_PAIR(tc->colorpair), NULL);
2454 free(id_str);
2455 col += 9;
2456 if (col > avail)
2457 goto done;
2460 if (s->use_committer)
2461 author = strdup(got_object_commit_get_committer(commit));
2462 else
2463 author = strdup(got_object_commit_get_author(commit));
2464 if (author == NULL) {
2465 err = got_error_from_errno("strdup");
2466 goto done;
2468 err = format_author(&wauthor, &author_width, author, avail - col, col);
2469 if (err)
2470 goto done;
2471 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2472 if (tc)
2473 wattr_on(view->window,
2474 COLOR_PAIR(tc->colorpair), NULL);
2475 waddwstr(view->window, wauthor);
2476 col += author_width;
2477 while (col < avail && author_width < author_display_cols + 2) {
2478 waddch(view->window, ' ');
2479 col++;
2480 author_width++;
2482 if (tc)
2483 wattr_off(view->window,
2484 COLOR_PAIR(tc->colorpair), NULL);
2485 if (col > avail)
2486 goto done;
2488 err = got_object_commit_get_logmsg(&logmsg0, commit);
2489 if (err)
2490 goto done;
2491 logmsg = logmsg0;
2492 while (*logmsg == '\n')
2493 logmsg++;
2494 newline = strchr(logmsg, '\n');
2495 if (newline)
2496 *newline = '\0';
2498 limit = avail - col;
2499 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2500 limit--; /* for the border */
2502 /* Prepend reference labels to log message if possible .*/
2503 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, id);
2504 err = build_refs_str(&refs_str, refs, id, s->repo);
2505 if (err)
2506 goto done;
2507 if (refs_str) {
2508 char *rs;
2510 if (asprintf(&rs, "[%s]", refs_str) == -1) {
2511 err = got_error_from_errno("asprintf");
2512 goto done;
2514 err = format_line(&wrefstr, &refstr_width,
2515 &scrollx, rs, view->x, limit, col, 1);
2516 free(rs);
2517 if (err)
2518 goto done;
2519 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2520 if (tc)
2521 wattr_on(view->window,
2522 COLOR_PAIR(tc->colorpair), NULL);
2523 waddwstr(view->window, &wrefstr[scrollx]);
2524 if (tc)
2525 wattr_off(view->window,
2526 COLOR_PAIR(tc->colorpair), NULL);
2527 col += MAX(refstr_width, 0);
2528 if (col > avail)
2529 goto done;
2531 if (col < avail) {
2532 waddch(view->window, ' ');
2533 col++;
2536 if (refstr_width > 0)
2537 logmsg_x = 0;
2538 else {
2539 int unscrolled_refstr_width;
2540 size_t len = wcslen(wrefstr);
2543 * No need to check for -1 return value here since
2544 * unprintables have been replaced by span_wline().
2546 unscrolled_refstr_width = wcswidth(wrefstr, len);
2547 unscrolled_refstr_width += 1; /* trailing space */
2548 logmsg_x = view->x - unscrolled_refstr_width;
2551 limit = avail - col;
2552 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2553 limit--; /* for the border */
2554 } else
2555 logmsg_x = view->x;
2557 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, logmsg_x,
2558 limit, col, 1);
2559 if (err)
2560 goto done;
2561 waddwstr(view->window, &wlogmsg[scrollx]);
2562 col += MAX(logmsg_width, 0);
2563 while (col < avail) {
2564 waddch(view->window, ' ');
2565 col++;
2567 done:
2568 free(logmsg0);
2569 free(wlogmsg);
2570 free(wrefstr);
2571 free(refs_str);
2572 free(author);
2573 free(wauthor);
2574 free(line);
2575 return err;
2578 static struct commit_queue_entry *
2579 alloc_commit_queue_entry(struct got_commit_object *commit,
2580 struct got_object_id *id)
2582 struct commit_queue_entry *entry;
2583 struct got_object_id *dup;
2585 entry = calloc(1, sizeof(*entry));
2586 if (entry == NULL)
2587 return NULL;
2589 dup = got_object_id_dup(id);
2590 if (dup == NULL) {
2591 free(entry);
2592 return NULL;
2595 entry->id = dup;
2596 entry->commit = commit;
2597 return entry;
2600 static void
2601 pop_commit(struct commit_queue *commits)
2603 struct commit_queue_entry *entry;
2605 entry = TAILQ_FIRST(&commits->head);
2606 TAILQ_REMOVE(&commits->head, entry, entry);
2607 got_object_commit_close(entry->commit);
2608 commits->ncommits--;
2609 free(entry->id);
2610 free(entry);
2613 static void
2614 free_commits(struct commit_queue *commits)
2616 while (!TAILQ_EMPTY(&commits->head))
2617 pop_commit(commits);
2620 static const struct got_error *
2621 match_commit(int *have_match, struct got_object_id *id,
2622 struct got_commit_object *commit, regex_t *regex)
2624 const struct got_error *err = NULL;
2625 regmatch_t regmatch;
2626 char *id_str = NULL, *logmsg = NULL;
2628 *have_match = 0;
2630 err = got_object_id_str(&id_str, id);
2631 if (err)
2632 return err;
2634 err = got_object_commit_get_logmsg(&logmsg, commit);
2635 if (err)
2636 goto done;
2638 if (regexec(regex, got_object_commit_get_author(commit), 1,
2639 &regmatch, 0) == 0 ||
2640 regexec(regex, got_object_commit_get_committer(commit), 1,
2641 &regmatch, 0) == 0 ||
2642 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2643 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2644 *have_match = 1;
2645 done:
2646 free(id_str);
2647 free(logmsg);
2648 return err;
2651 static const struct got_error *
2652 queue_commits(struct tog_log_thread_args *a)
2654 const struct got_error *err = NULL;
2657 * We keep all commits open throughout the lifetime of the log
2658 * view in order to avoid having to re-fetch commits from disk
2659 * while updating the display.
2661 do {
2662 struct got_object_id id;
2663 struct got_commit_object *commit;
2664 struct commit_queue_entry *entry;
2665 int limit_match = 0;
2666 int errcode;
2668 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2669 NULL, NULL);
2670 if (err)
2671 break;
2673 err = got_object_open_as_commit(&commit, a->repo, &id);
2674 if (err)
2675 break;
2676 entry = alloc_commit_queue_entry(commit, &id);
2677 if (entry == NULL) {
2678 err = got_error_from_errno("alloc_commit_queue_entry");
2679 break;
2682 errcode = pthread_mutex_lock(&tog_mutex);
2683 if (errcode) {
2684 err = got_error_set_errno(errcode,
2685 "pthread_mutex_lock");
2686 break;
2689 entry->idx = a->real_commits->ncommits;
2690 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2691 a->real_commits->ncommits++;
2693 if (*a->limiting) {
2694 err = match_commit(&limit_match, &id, commit,
2695 a->limit_regex);
2696 if (err)
2697 break;
2699 if (limit_match) {
2700 struct commit_queue_entry *matched;
2702 matched = alloc_commit_queue_entry(
2703 entry->commit, entry->id);
2704 if (matched == NULL) {
2705 err = got_error_from_errno(
2706 "alloc_commit_queue_entry");
2707 break;
2709 matched->commit = entry->commit;
2710 got_object_commit_retain(entry->commit);
2712 matched->idx = a->limit_commits->ncommits;
2713 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2714 matched, entry);
2715 a->limit_commits->ncommits++;
2719 * This is how we signal log_thread() that we
2720 * have found a match, and that it should be
2721 * counted as a new entry for the view.
2723 a->limit_match = limit_match;
2726 if (*a->searching == TOG_SEARCH_FORWARD &&
2727 !*a->search_next_done) {
2728 int have_match;
2729 err = match_commit(&have_match, &id, commit, a->regex);
2730 if (err)
2731 break;
2733 if (*a->limiting) {
2734 if (limit_match && have_match)
2735 *a->search_next_done =
2736 TOG_SEARCH_HAVE_MORE;
2737 } else if (have_match)
2738 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2741 errcode = pthread_mutex_unlock(&tog_mutex);
2742 if (errcode && err == NULL)
2743 err = got_error_set_errno(errcode,
2744 "pthread_mutex_unlock");
2745 if (err)
2746 break;
2747 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2749 return err;
2752 static void
2753 select_commit(struct tog_log_view_state *s)
2755 struct commit_queue_entry *entry;
2756 int ncommits = 0;
2758 entry = s->first_displayed_entry;
2759 while (entry) {
2760 if (ncommits == s->selected) {
2761 s->selected_entry = entry;
2762 break;
2764 entry = TAILQ_NEXT(entry, entry);
2765 ncommits++;
2769 static const struct got_error *
2770 draw_commits(struct tog_view *view)
2772 const struct got_error *err = NULL;
2773 struct tog_log_view_state *s = &view->state.log;
2774 struct commit_queue_entry *entry = s->selected_entry;
2775 int limit = view->nlines;
2776 int width;
2777 int ncommits, author_cols = 4, refstr_cols;
2778 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2779 char *refs_str = NULL;
2780 wchar_t *wline;
2781 struct tog_color *tc;
2782 static const size_t date_display_cols = 12;
2783 struct got_reflist_head *refs;
2785 if (view_is_hsplit_top(view))
2786 --limit; /* account for border */
2788 if (s->selected_entry &&
2789 !(view->searching && view->search_next_done == 0)) {
2790 err = got_object_id_str(&id_str, s->selected_entry->id);
2791 if (err)
2792 return err;
2793 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2794 s->selected_entry->id);
2795 err = build_refs_str(&refs_str, refs, s->selected_entry->id,
2796 s->repo);
2797 if (err)
2798 goto done;
2801 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2802 halfdelay(10); /* disable fast refresh */
2804 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2805 if (asprintf(&ncommits_str, " [%d/%d] %s",
2806 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2807 (view->searching && !view->search_next_done) ?
2808 "searching..." : "loading...") == -1) {
2809 err = got_error_from_errno("asprintf");
2810 goto done;
2812 } else {
2813 const char *search_str = NULL;
2814 const char *limit_str = NULL;
2816 if (view->searching) {
2817 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2818 search_str = "no more matches";
2819 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2820 search_str = "no matches found";
2821 else if (!view->search_next_done)
2822 search_str = "searching...";
2825 if (s->limit_view && s->commits->ncommits == 0)
2826 limit_str = "no matches found";
2828 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2829 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2830 search_str ? search_str : (refs_str ? refs_str : ""),
2831 limit_str ? limit_str : "") == -1) {
2832 err = got_error_from_errno("asprintf");
2833 goto done;
2837 free(refs_str);
2838 refs_str = NULL;
2840 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2841 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2842 "........................................",
2843 s->in_repo_path, ncommits_str) == -1) {
2844 err = got_error_from_errno("asprintf");
2845 header = NULL;
2846 goto done;
2848 } else if (asprintf(&header, "commit %s%s",
2849 id_str ? id_str : "........................................",
2850 ncommits_str) == -1) {
2851 err = got_error_from_errno("asprintf");
2852 header = NULL;
2853 goto done;
2855 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2856 if (err)
2857 goto done;
2859 werase(view->window);
2861 if (view_needs_focus_indication(view))
2862 wstandout(view->window);
2863 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2864 if (tc)
2865 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2866 waddwstr(view->window, wline);
2867 while (width < view->ncols) {
2868 waddch(view->window, ' ');
2869 width++;
2871 if (tc)
2872 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2873 if (view_needs_focus_indication(view))
2874 wstandend(view->window);
2875 free(wline);
2876 if (limit <= 1)
2877 goto done;
2879 /* Grow author column size if necessary, and set view->maxx. */
2880 entry = s->first_displayed_entry;
2881 ncommits = 0;
2882 view->maxx = 0;
2883 while (entry) {
2884 struct got_commit_object *c = entry->commit;
2885 char *author, *eol, *msg, *msg0;
2886 wchar_t *wauthor, *wmsg;
2887 int width;
2888 if (ncommits >= limit - 1)
2889 break;
2890 if (s->use_committer)
2891 author = strdup(got_object_commit_get_committer(c));
2892 else
2893 author = strdup(got_object_commit_get_author(c));
2894 if (author == NULL) {
2895 err = got_error_from_errno("strdup");
2896 goto done;
2898 err = format_author(&wauthor, &width, author, COLS,
2899 date_display_cols);
2900 if (author_cols < width)
2901 author_cols = width;
2902 free(wauthor);
2903 free(author);
2904 if (err)
2905 goto done;
2906 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2907 entry->id);
2908 err = build_refs_str(&refs_str, refs, entry->id, s->repo);
2909 if (err)
2910 goto done;
2911 if (refs_str) {
2912 wchar_t *ws;
2913 err = format_line(&ws, &width, NULL, refs_str,
2914 0, INT_MAX, date_display_cols + author_cols, 0);
2915 free(ws);
2916 free(refs_str);
2917 refs_str = NULL;
2918 if (err)
2919 goto done;
2920 refstr_cols = width + 3; /* account for [ ] + space */
2921 } else
2922 refstr_cols = 0;
2923 err = got_object_commit_get_logmsg(&msg0, c);
2924 if (err)
2925 goto done;
2926 msg = msg0;
2927 while (*msg == '\n')
2928 ++msg;
2929 if ((eol = strchr(msg, '\n')))
2930 *eol = '\0';
2931 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2932 date_display_cols + author_cols + refstr_cols, 0);
2933 if (err)
2934 goto done;
2935 view->maxx = MAX(view->maxx, width + refstr_cols);
2936 free(msg0);
2937 free(wmsg);
2938 ncommits++;
2939 entry = TAILQ_NEXT(entry, entry);
2942 entry = s->first_displayed_entry;
2943 s->last_displayed_entry = s->first_displayed_entry;
2944 ncommits = 0;
2945 while (entry) {
2946 if (ncommits >= limit - 1)
2947 break;
2948 if (ncommits == s->selected)
2949 wstandout(view->window);
2950 err = draw_commit(view, entry->commit, entry->id,
2951 date_display_cols, author_cols);
2952 if (ncommits == s->selected)
2953 wstandend(view->window);
2954 if (err)
2955 goto done;
2956 ncommits++;
2957 s->last_displayed_entry = entry;
2958 entry = TAILQ_NEXT(entry, entry);
2961 view_border(view);
2962 done:
2963 free(id_str);
2964 free(refs_str);
2965 free(ncommits_str);
2966 free(header);
2967 return err;
2970 static void
2971 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2973 struct commit_queue_entry *entry;
2974 int nscrolled = 0;
2976 entry = TAILQ_FIRST(&s->commits->head);
2977 if (s->first_displayed_entry == entry)
2978 return;
2980 entry = s->first_displayed_entry;
2981 while (entry && nscrolled < maxscroll) {
2982 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2983 if (entry) {
2984 s->first_displayed_entry = entry;
2985 nscrolled++;
2990 static const struct got_error *
2991 trigger_log_thread(struct tog_view *view, int wait)
2993 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2994 int errcode;
2996 if (!using_mock_io)
2997 halfdelay(1); /* fast refresh while loading commits */
2999 while (!ta->log_complete && !tog_thread_error &&
3000 (ta->commits_needed > 0 || ta->load_all)) {
3001 /* Wake the log thread. */
3002 errcode = pthread_cond_signal(&ta->need_commits);
3003 if (errcode)
3004 return got_error_set_errno(errcode,
3005 "pthread_cond_signal");
3008 * The mutex will be released while the view loop waits
3009 * in wgetch(), at which time the log thread will run.
3011 if (!wait)
3012 break;
3014 /* Display progress update in log view. */
3015 show_log_view(view);
3016 update_panels();
3017 doupdate();
3019 /* Wait right here while next commit is being loaded. */
3020 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
3021 if (errcode)
3022 return got_error_set_errno(errcode,
3023 "pthread_cond_wait");
3025 /* Display progress update in log view. */
3026 show_log_view(view);
3027 update_panels();
3028 doupdate();
3031 return NULL;
3034 static const struct got_error *
3035 request_log_commits(struct tog_view *view)
3037 struct tog_log_view_state *state = &view->state.log;
3038 const struct got_error *err = NULL;
3040 if (state->thread_args.log_complete)
3041 return NULL;
3043 state->thread_args.commits_needed += view->nscrolled;
3044 err = trigger_log_thread(view, 1);
3045 view->nscrolled = 0;
3047 return err;
3050 static const struct got_error *
3051 log_scroll_down(struct tog_view *view, int maxscroll)
3053 struct tog_log_view_state *s = &view->state.log;
3054 const struct got_error *err = NULL;
3055 struct commit_queue_entry *pentry;
3056 int nscrolled = 0, ncommits_needed;
3058 if (s->last_displayed_entry == NULL)
3059 return NULL;
3061 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
3062 if (s->commits->ncommits < ncommits_needed &&
3063 !s->thread_args.log_complete) {
3065 * Ask the log thread for required amount of commits.
3067 s->thread_args.commits_needed +=
3068 ncommits_needed - s->commits->ncommits;
3069 err = trigger_log_thread(view, 1);
3070 if (err)
3071 return err;
3074 do {
3075 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
3076 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
3077 break;
3079 s->last_displayed_entry = pentry ?
3080 pentry : s->last_displayed_entry;
3082 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3083 if (pentry == NULL)
3084 break;
3085 s->first_displayed_entry = pentry;
3086 } while (++nscrolled < maxscroll);
3088 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3089 view->nscrolled += nscrolled;
3090 else
3091 view->nscrolled = 0;
3093 return err;
3096 static const struct got_error *
3097 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3098 struct got_commit_object *commit, struct got_object_id *commit_id,
3099 struct tog_view *log_view, struct got_repository *repo)
3101 const struct got_error *err;
3102 struct got_object_qid *parent_id;
3103 struct tog_view *diff_view;
3105 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3106 if (diff_view == NULL)
3107 return got_error_from_errno("view_open");
3109 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3110 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3111 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3112 if (err == NULL)
3113 *new_view = diff_view;
3114 return err;
3117 static const struct got_error *
3118 tree_view_visit_subtree(struct tog_tree_view_state *s,
3119 struct got_tree_object *subtree)
3121 struct tog_parent_tree *parent;
3123 parent = calloc(1, sizeof(*parent));
3124 if (parent == NULL)
3125 return got_error_from_errno("calloc");
3127 parent->tree = s->tree;
3128 parent->first_displayed_entry = s->first_displayed_entry;
3129 parent->selected_entry = s->selected_entry;
3130 parent->selected = s->selected;
3131 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3132 s->tree = subtree;
3133 s->selected = 0;
3134 s->first_displayed_entry = NULL;
3135 return NULL;
3138 static const struct got_error *
3139 tree_view_walk_path(struct tog_tree_view_state *s,
3140 struct got_commit_object *commit, const char *path)
3142 const struct got_error *err = NULL;
3143 struct got_tree_object *tree = NULL;
3144 const char *p;
3145 char *slash, *subpath = NULL;
3147 /* Walk the path and open corresponding tree objects. */
3148 p = path;
3149 while (*p) {
3150 struct got_tree_entry *te;
3151 struct got_object_id *tree_id;
3152 char *te_name;
3154 while (p[0] == '/')
3155 p++;
3157 /* Ensure the correct subtree entry is selected. */
3158 slash = strchr(p, '/');
3159 if (slash == NULL)
3160 te_name = strdup(p);
3161 else
3162 te_name = strndup(p, slash - p);
3163 if (te_name == NULL) {
3164 err = got_error_from_errno("strndup");
3165 break;
3167 te = got_object_tree_find_entry(s->tree, te_name);
3168 if (te == NULL) {
3169 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3170 free(te_name);
3171 break;
3173 free(te_name);
3174 s->first_displayed_entry = s->selected_entry = te;
3176 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3177 break; /* jump to this file's entry */
3179 slash = strchr(p, '/');
3180 if (slash)
3181 subpath = strndup(path, slash - path);
3182 else
3183 subpath = strdup(path);
3184 if (subpath == NULL) {
3185 err = got_error_from_errno("strdup");
3186 break;
3189 err = got_object_id_by_path(&tree_id, s->repo, commit,
3190 subpath);
3191 if (err)
3192 break;
3194 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3195 free(tree_id);
3196 if (err)
3197 break;
3199 err = tree_view_visit_subtree(s, tree);
3200 if (err) {
3201 got_object_tree_close(tree);
3202 break;
3204 if (slash == NULL)
3205 break;
3206 free(subpath);
3207 subpath = NULL;
3208 p = slash;
3211 free(subpath);
3212 return err;
3215 static const struct got_error *
3216 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3217 struct commit_queue_entry *entry, const char *path,
3218 const char *head_ref_name, struct got_repository *repo)
3220 const struct got_error *err = NULL;
3221 struct tog_tree_view_state *s;
3222 struct tog_view *tree_view;
3224 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3225 if (tree_view == NULL)
3226 return got_error_from_errno("view_open");
3228 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3229 if (err)
3230 return err;
3231 s = &tree_view->state.tree;
3233 *new_view = tree_view;
3235 if (got_path_is_root_dir(path))
3236 return NULL;
3238 return tree_view_walk_path(s, entry->commit, path);
3241 static const struct got_error *
3242 block_signals_used_by_main_thread(void)
3244 sigset_t sigset;
3245 int errcode;
3247 if (sigemptyset(&sigset) == -1)
3248 return got_error_from_errno("sigemptyset");
3250 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3251 if (sigaddset(&sigset, SIGWINCH) == -1)
3252 return got_error_from_errno("sigaddset");
3253 if (sigaddset(&sigset, SIGCONT) == -1)
3254 return got_error_from_errno("sigaddset");
3255 if (sigaddset(&sigset, SIGINT) == -1)
3256 return got_error_from_errno("sigaddset");
3257 if (sigaddset(&sigset, SIGTERM) == -1)
3258 return got_error_from_errno("sigaddset");
3260 /* ncurses handles SIGTSTP */
3261 if (sigaddset(&sigset, SIGTSTP) == -1)
3262 return got_error_from_errno("sigaddset");
3264 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3265 if (errcode)
3266 return got_error_set_errno(errcode, "pthread_sigmask");
3268 return NULL;
3271 static void *
3272 log_thread(void *arg)
3274 const struct got_error *err = NULL;
3275 int errcode = 0;
3276 struct tog_log_thread_args *a = arg;
3277 int done = 0;
3280 * Sync startup with main thread such that we begin our
3281 * work once view_input() has released the mutex.
3283 errcode = pthread_mutex_lock(&tog_mutex);
3284 if (errcode) {
3285 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3286 return (void *)err;
3289 err = block_signals_used_by_main_thread();
3290 if (err) {
3291 pthread_mutex_unlock(&tog_mutex);
3292 goto done;
3295 while (!done && !err && !tog_fatal_signal_received()) {
3296 errcode = pthread_mutex_unlock(&tog_mutex);
3297 if (errcode) {
3298 err = got_error_set_errno(errcode,
3299 "pthread_mutex_unlock");
3300 goto done;
3302 err = queue_commits(a);
3303 if (err) {
3304 if (err->code != GOT_ERR_ITER_COMPLETED)
3305 goto done;
3306 err = NULL;
3307 done = 1;
3308 } else if (a->commits_needed > 0 && !a->load_all) {
3309 if (*a->limiting) {
3310 if (a->limit_match)
3311 a->commits_needed--;
3312 } else
3313 a->commits_needed--;
3316 errcode = pthread_mutex_lock(&tog_mutex);
3317 if (errcode) {
3318 err = got_error_set_errno(errcode,
3319 "pthread_mutex_lock");
3320 goto done;
3321 } else if (*a->quit)
3322 done = 1;
3323 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3324 *a->first_displayed_entry =
3325 TAILQ_FIRST(&a->limit_commits->head);
3326 *a->selected_entry = *a->first_displayed_entry;
3327 } else if (*a->first_displayed_entry == NULL) {
3328 *a->first_displayed_entry =
3329 TAILQ_FIRST(&a->real_commits->head);
3330 *a->selected_entry = *a->first_displayed_entry;
3333 errcode = pthread_cond_signal(&a->commit_loaded);
3334 if (errcode) {
3335 err = got_error_set_errno(errcode,
3336 "pthread_cond_signal");
3337 pthread_mutex_unlock(&tog_mutex);
3338 goto done;
3341 if (done)
3342 a->commits_needed = 0;
3343 else {
3344 if (a->commits_needed == 0 && !a->load_all) {
3345 errcode = pthread_cond_wait(&a->need_commits,
3346 &tog_mutex);
3347 if (errcode) {
3348 err = got_error_set_errno(errcode,
3349 "pthread_cond_wait");
3350 pthread_mutex_unlock(&tog_mutex);
3351 goto done;
3353 if (*a->quit)
3354 done = 1;
3358 a->log_complete = 1;
3359 errcode = pthread_mutex_unlock(&tog_mutex);
3360 if (errcode)
3361 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3362 done:
3363 if (err) {
3364 tog_thread_error = 1;
3365 pthread_cond_signal(&a->commit_loaded);
3367 return (void *)err;
3370 static const struct got_error *
3371 stop_log_thread(struct tog_log_view_state *s)
3373 const struct got_error *err = NULL, *thread_err = NULL;
3374 int errcode;
3376 if (s->thread) {
3377 s->quit = 1;
3378 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3379 if (errcode)
3380 return got_error_set_errno(errcode,
3381 "pthread_cond_signal");
3382 errcode = pthread_mutex_unlock(&tog_mutex);
3383 if (errcode)
3384 return got_error_set_errno(errcode,
3385 "pthread_mutex_unlock");
3386 errcode = pthread_join(s->thread, (void **)&thread_err);
3387 if (errcode)
3388 return got_error_set_errno(errcode, "pthread_join");
3389 errcode = pthread_mutex_lock(&tog_mutex);
3390 if (errcode)
3391 return got_error_set_errno(errcode,
3392 "pthread_mutex_lock");
3393 s->thread = NULL;
3396 if (s->thread_args.repo) {
3397 err = got_repo_close(s->thread_args.repo);
3398 s->thread_args.repo = NULL;
3401 if (s->thread_args.pack_fds) {
3402 const struct got_error *pack_err =
3403 got_repo_pack_fds_close(s->thread_args.pack_fds);
3404 if (err == NULL)
3405 err = pack_err;
3406 s->thread_args.pack_fds = NULL;
3409 if (s->thread_args.graph) {
3410 got_commit_graph_close(s->thread_args.graph);
3411 s->thread_args.graph = NULL;
3414 return err ? err : thread_err;
3417 static const struct got_error *
3418 close_log_view(struct tog_view *view)
3420 const struct got_error *err = NULL;
3421 struct tog_log_view_state *s = &view->state.log;
3422 int errcode;
3424 err = stop_log_thread(s);
3426 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3427 if (errcode && err == NULL)
3428 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3430 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3431 if (errcode && err == NULL)
3432 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3434 free_commits(&s->limit_commits);
3435 free_commits(&s->real_commits);
3436 free(s->in_repo_path);
3437 s->in_repo_path = NULL;
3438 free(s->start_id);
3439 s->start_id = NULL;
3440 free(s->head_ref_name);
3441 s->head_ref_name = NULL;
3442 return err;
3446 * We use two queues to implement the limit feature: first consists of
3447 * commits matching the current limit_regex; second is the real queue
3448 * of all known commits (real_commits). When the user starts limiting,
3449 * we swap queues such that all movement and displaying functionality
3450 * works with very slight change.
3452 static const struct got_error *
3453 limit_log_view(struct tog_view *view)
3455 struct tog_log_view_state *s = &view->state.log;
3456 struct commit_queue_entry *entry;
3457 struct tog_view *v = view;
3458 const struct got_error *err = NULL;
3459 char pattern[1024];
3460 int ret;
3462 if (view_is_hsplit_top(view))
3463 v = view->child;
3464 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3465 v = view->parent;
3467 /* Get the pattern */
3468 wmove(v->window, v->nlines - 1, 0);
3469 wclrtoeol(v->window);
3470 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3471 nodelay(v->window, FALSE);
3472 nocbreak();
3473 echo();
3474 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3475 cbreak();
3476 noecho();
3477 nodelay(v->window, TRUE);
3478 if (ret == ERR)
3479 return NULL;
3481 if (*pattern == '\0') {
3483 * Safety measure for the situation where the user
3484 * resets limit without previously limiting anything.
3486 if (!s->limit_view)
3487 return NULL;
3490 * User could have pressed Ctrl+L, which refreshed the
3491 * commit queues, it means we can't save previously
3492 * (before limit took place) displayed entries,
3493 * because they would point to already free'ed memory,
3494 * so we are forced to always select first entry of
3495 * the queue.
3497 s->commits = &s->real_commits;
3498 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3499 s->selected_entry = s->first_displayed_entry;
3500 s->selected = 0;
3501 s->limit_view = 0;
3503 return NULL;
3506 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3507 return NULL;
3509 s->limit_view = 1;
3511 /* Clear the screen while loading limit view */
3512 s->first_displayed_entry = NULL;
3513 s->last_displayed_entry = NULL;
3514 s->selected_entry = NULL;
3515 s->commits = &s->limit_commits;
3517 /* Prepare limit queue for new search */
3518 free_commits(&s->limit_commits);
3519 s->limit_commits.ncommits = 0;
3521 /* First process commits, which are in queue already */
3522 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3523 int have_match = 0;
3525 err = match_commit(&have_match, entry->id,
3526 entry->commit, &s->limit_regex);
3527 if (err)
3528 return err;
3530 if (have_match) {
3531 struct commit_queue_entry *matched;
3533 matched = alloc_commit_queue_entry(entry->commit,
3534 entry->id);
3535 if (matched == NULL) {
3536 err = got_error_from_errno(
3537 "alloc_commit_queue_entry");
3538 break;
3540 matched->commit = entry->commit;
3541 got_object_commit_retain(entry->commit);
3543 matched->idx = s->limit_commits.ncommits;
3544 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3545 matched, entry);
3546 s->limit_commits.ncommits++;
3550 /* Second process all the commits, until we fill the screen */
3551 if (s->limit_commits.ncommits < view->nlines - 1 &&
3552 !s->thread_args.log_complete) {
3553 s->thread_args.commits_needed +=
3554 view->nlines - s->limit_commits.ncommits - 1;
3555 err = trigger_log_thread(view, 1);
3556 if (err)
3557 return err;
3560 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3561 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3562 s->selected = 0;
3564 return NULL;
3567 static const struct got_error *
3568 search_start_log_view(struct tog_view *view)
3570 struct tog_log_view_state *s = &view->state.log;
3572 s->matched_entry = NULL;
3573 s->search_entry = NULL;
3574 return NULL;
3577 static const struct got_error *
3578 search_next_log_view(struct tog_view *view)
3580 const struct got_error *err = NULL;
3581 struct tog_log_view_state *s = &view->state.log;
3582 struct commit_queue_entry *entry;
3584 /* Display progress update in log view. */
3585 show_log_view(view);
3586 update_panels();
3587 doupdate();
3589 if (s->search_entry) {
3590 int errcode, ch;
3591 errcode = pthread_mutex_unlock(&tog_mutex);
3592 if (errcode)
3593 return got_error_set_errno(errcode,
3594 "pthread_mutex_unlock");
3595 ch = wgetch(view->window);
3596 errcode = pthread_mutex_lock(&tog_mutex);
3597 if (errcode)
3598 return got_error_set_errno(errcode,
3599 "pthread_mutex_lock");
3600 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3601 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3602 return NULL;
3604 if (view->searching == TOG_SEARCH_FORWARD)
3605 entry = TAILQ_NEXT(s->search_entry, entry);
3606 else
3607 entry = TAILQ_PREV(s->search_entry,
3608 commit_queue_head, entry);
3609 } else if (s->matched_entry) {
3611 * If the user has moved the cursor after we hit a match,
3612 * the position from where we should continue searching
3613 * might have changed.
3615 if (view->searching == TOG_SEARCH_FORWARD)
3616 entry = TAILQ_NEXT(s->selected_entry, entry);
3617 else
3618 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3619 entry);
3620 } else {
3621 entry = s->selected_entry;
3624 while (1) {
3625 int have_match = 0;
3627 if (entry == NULL) {
3628 if (s->thread_args.log_complete ||
3629 view->searching == TOG_SEARCH_BACKWARD) {
3630 view->search_next_done =
3631 (s->matched_entry == NULL ?
3632 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3633 s->search_entry = NULL;
3634 return NULL;
3637 * Poke the log thread for more commits and return,
3638 * allowing the main loop to make progress. Search
3639 * will resume at s->search_entry once we come back.
3641 s->thread_args.commits_needed++;
3642 return trigger_log_thread(view, 0);
3645 err = match_commit(&have_match, entry->id, entry->commit,
3646 &view->regex);
3647 if (err)
3648 break;
3649 if (have_match) {
3650 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3651 s->matched_entry = entry;
3652 break;
3655 s->search_entry = entry;
3656 if (view->searching == TOG_SEARCH_FORWARD)
3657 entry = TAILQ_NEXT(entry, entry);
3658 else
3659 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3662 if (s->matched_entry) {
3663 int cur = s->selected_entry->idx;
3664 while (cur < s->matched_entry->idx) {
3665 err = input_log_view(NULL, view, KEY_DOWN);
3666 if (err)
3667 return err;
3668 cur++;
3670 while (cur > s->matched_entry->idx) {
3671 err = input_log_view(NULL, view, KEY_UP);
3672 if (err)
3673 return err;
3674 cur--;
3678 s->search_entry = NULL;
3680 return NULL;
3683 static const struct got_error *
3684 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3685 struct got_repository *repo, const char *head_ref_name,
3686 const char *in_repo_path, int log_branches)
3688 const struct got_error *err = NULL;
3689 struct tog_log_view_state *s = &view->state.log;
3690 struct got_repository *thread_repo = NULL;
3691 struct got_commit_graph *thread_graph = NULL;
3692 int errcode;
3694 if (in_repo_path != s->in_repo_path) {
3695 free(s->in_repo_path);
3696 s->in_repo_path = strdup(in_repo_path);
3697 if (s->in_repo_path == NULL) {
3698 err = got_error_from_errno("strdup");
3699 goto done;
3703 /* The commit queue only contains commits being displayed. */
3704 TAILQ_INIT(&s->real_commits.head);
3705 s->real_commits.ncommits = 0;
3706 s->commits = &s->real_commits;
3708 TAILQ_INIT(&s->limit_commits.head);
3709 s->limit_view = 0;
3710 s->limit_commits.ncommits = 0;
3712 s->repo = repo;
3713 if (head_ref_name) {
3714 s->head_ref_name = strdup(head_ref_name);
3715 if (s->head_ref_name == NULL) {
3716 err = got_error_from_errno("strdup");
3717 goto done;
3720 s->start_id = got_object_id_dup(start_id);
3721 if (s->start_id == NULL) {
3722 err = got_error_from_errno("got_object_id_dup");
3723 goto done;
3725 s->log_branches = log_branches;
3726 s->use_committer = 1;
3728 STAILQ_INIT(&s->colors);
3729 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3730 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3731 get_color_value("TOG_COLOR_COMMIT"));
3732 if (err)
3733 goto done;
3734 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3735 get_color_value("TOG_COLOR_AUTHOR"));
3736 if (err) {
3737 free_colors(&s->colors);
3738 goto done;
3740 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3741 get_color_value("TOG_COLOR_DATE"));
3742 if (err) {
3743 free_colors(&s->colors);
3744 goto done;
3748 view->show = show_log_view;
3749 view->input = input_log_view;
3750 view->resize = resize_log_view;
3751 view->close = close_log_view;
3752 view->search_start = search_start_log_view;
3753 view->search_next = search_next_log_view;
3755 if (s->thread_args.pack_fds == NULL) {
3756 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3757 if (err)
3758 goto done;
3760 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3761 s->thread_args.pack_fds);
3762 if (err)
3763 goto done;
3764 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3765 !s->log_branches);
3766 if (err)
3767 goto done;
3768 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3769 s->repo, NULL, NULL);
3770 if (err)
3771 goto done;
3773 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3774 if (errcode) {
3775 err = got_error_set_errno(errcode, "pthread_cond_init");
3776 goto done;
3778 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3779 if (errcode) {
3780 err = got_error_set_errno(errcode, "pthread_cond_init");
3781 goto done;
3784 s->thread_args.commits_needed = view->nlines;
3785 s->thread_args.graph = thread_graph;
3786 s->thread_args.real_commits = &s->real_commits;
3787 s->thread_args.limit_commits = &s->limit_commits;
3788 s->thread_args.in_repo_path = s->in_repo_path;
3789 s->thread_args.start_id = s->start_id;
3790 s->thread_args.repo = thread_repo;
3791 s->thread_args.log_complete = 0;
3792 s->thread_args.quit = &s->quit;
3793 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3794 s->thread_args.selected_entry = &s->selected_entry;
3795 s->thread_args.searching = &view->searching;
3796 s->thread_args.search_next_done = &view->search_next_done;
3797 s->thread_args.regex = &view->regex;
3798 s->thread_args.limiting = &s->limit_view;
3799 s->thread_args.limit_regex = &s->limit_regex;
3800 s->thread_args.limit_commits = &s->limit_commits;
3801 done:
3802 if (err) {
3803 if (view->close == NULL)
3804 close_log_view(view);
3805 view_close(view);
3807 return err;
3810 static const struct got_error *
3811 show_log_view(struct tog_view *view)
3813 const struct got_error *err;
3814 struct tog_log_view_state *s = &view->state.log;
3816 if (s->thread == NULL) {
3817 int errcode = pthread_create(&s->thread, NULL, log_thread,
3818 &s->thread_args);
3819 if (errcode)
3820 return got_error_set_errno(errcode, "pthread_create");
3821 if (s->thread_args.commits_needed > 0) {
3822 err = trigger_log_thread(view, 1);
3823 if (err)
3824 return err;
3828 return draw_commits(view);
3831 static void
3832 log_move_cursor_up(struct tog_view *view, int page, int home)
3834 struct tog_log_view_state *s = &view->state.log;
3836 if (s->first_displayed_entry == NULL)
3837 return;
3838 if (s->selected_entry->idx == 0)
3839 view->count = 0;
3841 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3842 || home)
3843 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3845 if (!page && !home && s->selected > 0)
3846 --s->selected;
3847 else
3848 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3850 select_commit(s);
3851 return;
3854 static const struct got_error *
3855 log_move_cursor_down(struct tog_view *view, int page)
3857 struct tog_log_view_state *s = &view->state.log;
3858 const struct got_error *err = NULL;
3859 int eos = view->nlines - 2;
3861 if (s->first_displayed_entry == NULL)
3862 return NULL;
3864 if (s->thread_args.log_complete &&
3865 s->selected_entry->idx >= s->commits->ncommits - 1)
3866 return NULL;
3868 if (view_is_hsplit_top(view))
3869 --eos; /* border consumes the last line */
3871 if (!page) {
3872 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3873 ++s->selected;
3874 else
3875 err = log_scroll_down(view, 1);
3876 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3877 struct commit_queue_entry *entry;
3878 int n;
3880 s->selected = 0;
3881 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3882 s->last_displayed_entry = entry;
3883 for (n = 0; n <= eos; n++) {
3884 if (entry == NULL)
3885 break;
3886 s->first_displayed_entry = entry;
3887 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3889 if (n > 0)
3890 s->selected = n - 1;
3891 } else {
3892 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3893 s->thread_args.log_complete)
3894 s->selected += MIN(page,
3895 s->commits->ncommits - s->selected_entry->idx - 1);
3896 else
3897 err = log_scroll_down(view, page);
3899 if (err)
3900 return err;
3903 * We might necessarily overshoot in horizontal
3904 * splits; if so, select the last displayed commit.
3906 if (s->first_displayed_entry && s->last_displayed_entry) {
3907 s->selected = MIN(s->selected,
3908 s->last_displayed_entry->idx -
3909 s->first_displayed_entry->idx);
3912 select_commit(s);
3914 if (s->thread_args.log_complete &&
3915 s->selected_entry->idx == s->commits->ncommits - 1)
3916 view->count = 0;
3918 return NULL;
3921 static void
3922 view_get_split(struct tog_view *view, int *y, int *x)
3924 *x = 0;
3925 *y = 0;
3927 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3928 if (view->child && view->child->resized_y)
3929 *y = view->child->resized_y;
3930 else if (view->resized_y)
3931 *y = view->resized_y;
3932 else
3933 *y = view_split_begin_y(view->lines);
3934 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3935 if (view->child && view->child->resized_x)
3936 *x = view->child->resized_x;
3937 else if (view->resized_x)
3938 *x = view->resized_x;
3939 else
3940 *x = view_split_begin_x(view->begin_x);
3944 /* Split view horizontally at y and offset view->state->selected line. */
3945 static const struct got_error *
3946 view_init_hsplit(struct tog_view *view, int y)
3948 const struct got_error *err = NULL;
3950 view->nlines = y;
3951 view->ncols = COLS;
3952 err = view_resize(view);
3953 if (err)
3954 return err;
3956 err = offset_selection_down(view);
3958 return err;
3961 static const struct got_error *
3962 log_goto_line(struct tog_view *view, int nlines)
3964 const struct got_error *err = NULL;
3965 struct tog_log_view_state *s = &view->state.log;
3966 int g, idx = s->selected_entry->idx;
3968 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3969 return NULL;
3971 g = view->gline;
3972 view->gline = 0;
3974 if (g >= s->first_displayed_entry->idx + 1 &&
3975 g <= s->last_displayed_entry->idx + 1 &&
3976 g - s->first_displayed_entry->idx - 1 < nlines) {
3977 s->selected = g - s->first_displayed_entry->idx - 1;
3978 select_commit(s);
3979 return NULL;
3982 if (idx + 1 < g) {
3983 err = log_move_cursor_down(view, g - idx - 1);
3984 if (!err && g > s->selected_entry->idx + 1)
3985 err = log_move_cursor_down(view,
3986 g - s->first_displayed_entry->idx - 1);
3987 if (err)
3988 return err;
3989 } else if (idx + 1 > g)
3990 log_move_cursor_up(view, idx - g + 1, 0);
3992 if (g < nlines && s->first_displayed_entry->idx == 0)
3993 s->selected = g - 1;
3995 select_commit(s);
3996 return NULL;
4000 static void
4001 horizontal_scroll_input(struct tog_view *view, int ch)
4004 switch (ch) {
4005 case KEY_LEFT:
4006 case 'h':
4007 view->x -= MIN(view->x, 2);
4008 if (view->x <= 0)
4009 view->count = 0;
4010 break;
4011 case KEY_RIGHT:
4012 case 'l':
4013 if (view->x + view->ncols / 2 < view->maxx)
4014 view->x += 2;
4015 else
4016 view->count = 0;
4017 break;
4018 case '0':
4019 view->x = 0;
4020 break;
4021 case '$':
4022 view->x = MAX(view->maxx - view->ncols / 2, 0);
4023 view->count = 0;
4024 break;
4025 default:
4026 break;
4030 static const struct got_error *
4031 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
4033 const struct got_error *err = NULL;
4034 struct tog_log_view_state *s = &view->state.log;
4035 int eos, nscroll;
4037 if (s->thread_args.load_all) {
4038 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
4039 s->thread_args.load_all = 0;
4040 else if (s->thread_args.log_complete) {
4041 err = log_move_cursor_down(view, s->commits->ncommits);
4042 s->thread_args.load_all = 0;
4044 if (err)
4045 return err;
4048 eos = nscroll = view->nlines - 1;
4049 if (view_is_hsplit_top(view))
4050 --eos; /* border */
4052 if (view->gline)
4053 return log_goto_line(view, eos);
4055 switch (ch) {
4056 case '&':
4057 err = limit_log_view(view);
4058 break;
4059 case 'q':
4060 s->quit = 1;
4061 break;
4062 case '0':
4063 case '$':
4064 case KEY_RIGHT:
4065 case 'l':
4066 case KEY_LEFT:
4067 case 'h':
4068 horizontal_scroll_input(view, ch);
4069 break;
4070 case 'k':
4071 case KEY_UP:
4072 case '<':
4073 case ',':
4074 case CTRL('p'):
4075 log_move_cursor_up(view, 0, 0);
4076 break;
4077 case 'g':
4078 case '=':
4079 case KEY_HOME:
4080 log_move_cursor_up(view, 0, 1);
4081 view->count = 0;
4082 break;
4083 case CTRL('u'):
4084 case 'u':
4085 nscroll /= 2;
4086 /* FALL THROUGH */
4087 case KEY_PPAGE:
4088 case CTRL('b'):
4089 case 'b':
4090 log_move_cursor_up(view, nscroll, 0);
4091 break;
4092 case 'j':
4093 case KEY_DOWN:
4094 case '>':
4095 case '.':
4096 case CTRL('n'):
4097 err = log_move_cursor_down(view, 0);
4098 break;
4099 case '@':
4100 s->use_committer = !s->use_committer;
4101 view->action = s->use_committer ?
4102 "show committer" : "show commit author";
4103 break;
4104 case 'G':
4105 case '*':
4106 case KEY_END: {
4107 /* We don't know yet how many commits, so we're forced to
4108 * traverse them all. */
4109 view->count = 0;
4110 s->thread_args.load_all = 1;
4111 if (!s->thread_args.log_complete)
4112 return trigger_log_thread(view, 0);
4113 err = log_move_cursor_down(view, s->commits->ncommits);
4114 s->thread_args.load_all = 0;
4115 break;
4117 case CTRL('d'):
4118 case 'd':
4119 nscroll /= 2;
4120 /* FALL THROUGH */
4121 case KEY_NPAGE:
4122 case CTRL('f'):
4123 case 'f':
4124 case ' ':
4125 err = log_move_cursor_down(view, nscroll);
4126 break;
4127 case KEY_RESIZE:
4128 if (s->selected > view->nlines - 2)
4129 s->selected = view->nlines - 2;
4130 if (s->selected > s->commits->ncommits - 1)
4131 s->selected = s->commits->ncommits - 1;
4132 select_commit(s);
4133 if (s->commits->ncommits < view->nlines - 1 &&
4134 !s->thread_args.log_complete) {
4135 s->thread_args.commits_needed += (view->nlines - 1) -
4136 s->commits->ncommits;
4137 err = trigger_log_thread(view, 1);
4139 break;
4140 case KEY_ENTER:
4141 case '\r':
4142 view->count = 0;
4143 if (s->selected_entry == NULL)
4144 break;
4145 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4146 break;
4147 case 'T':
4148 view->count = 0;
4149 if (s->selected_entry == NULL)
4150 break;
4151 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4152 break;
4153 case KEY_BACKSPACE:
4154 case CTRL('l'):
4155 case 'B':
4156 view->count = 0;
4157 if (ch == KEY_BACKSPACE &&
4158 got_path_is_root_dir(s->in_repo_path))
4159 break;
4160 err = stop_log_thread(s);
4161 if (err)
4162 return err;
4163 if (ch == KEY_BACKSPACE) {
4164 char *parent_path;
4165 err = got_path_dirname(&parent_path, s->in_repo_path);
4166 if (err)
4167 return err;
4168 free(s->in_repo_path);
4169 s->in_repo_path = parent_path;
4170 s->thread_args.in_repo_path = s->in_repo_path;
4171 } else if (ch == CTRL('l')) {
4172 struct got_object_id *start_id;
4173 err = got_repo_match_object_id(&start_id, NULL,
4174 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4175 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4176 if (err) {
4177 if (s->head_ref_name == NULL ||
4178 err->code != GOT_ERR_NOT_REF)
4179 return err;
4180 /* Try to cope with deleted references. */
4181 free(s->head_ref_name);
4182 s->head_ref_name = NULL;
4183 err = got_repo_match_object_id(&start_id,
4184 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4185 &tog_refs, s->repo);
4186 if (err)
4187 return err;
4189 free(s->start_id);
4190 s->start_id = start_id;
4191 s->thread_args.start_id = s->start_id;
4192 } else /* 'B' */
4193 s->log_branches = !s->log_branches;
4195 if (s->thread_args.pack_fds == NULL) {
4196 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4197 if (err)
4198 return err;
4200 err = got_repo_open(&s->thread_args.repo,
4201 got_repo_get_path(s->repo), NULL,
4202 s->thread_args.pack_fds);
4203 if (err)
4204 return err;
4205 tog_free_refs();
4206 err = tog_load_refs(s->repo, 0);
4207 if (err)
4208 return err;
4209 err = got_commit_graph_open(&s->thread_args.graph,
4210 s->in_repo_path, !s->log_branches);
4211 if (err)
4212 return err;
4213 err = got_commit_graph_iter_start(s->thread_args.graph,
4214 s->start_id, s->repo, NULL, NULL);
4215 if (err)
4216 return err;
4217 free_commits(&s->real_commits);
4218 free_commits(&s->limit_commits);
4219 s->first_displayed_entry = NULL;
4220 s->last_displayed_entry = NULL;
4221 s->selected_entry = NULL;
4222 s->selected = 0;
4223 s->thread_args.log_complete = 0;
4224 s->quit = 0;
4225 s->thread_args.commits_needed = view->lines;
4226 s->matched_entry = NULL;
4227 s->search_entry = NULL;
4228 view->offset = 0;
4229 break;
4230 case 'R':
4231 view->count = 0;
4232 err = view_request_new(new_view, view, TOG_VIEW_REF);
4233 break;
4234 default:
4235 view->count = 0;
4236 break;
4239 return err;
4242 static const struct got_error *
4243 apply_unveil(const char *repo_path, const char *worktree_path)
4245 const struct got_error *error;
4247 #ifdef PROFILE
4248 if (unveil("gmon.out", "rwc") != 0)
4249 return got_error_from_errno2("unveil", "gmon.out");
4250 #endif
4251 if (repo_path && unveil(repo_path, "r") != 0)
4252 return got_error_from_errno2("unveil", repo_path);
4254 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4255 return got_error_from_errno2("unveil", worktree_path);
4257 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4258 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4260 error = got_privsep_unveil_exec_helpers();
4261 if (error != NULL)
4262 return error;
4264 if (unveil(NULL, NULL) != 0)
4265 return got_error_from_errno("unveil");
4267 return NULL;
4270 static const struct got_error *
4271 init_mock_term(const char *test_script_path)
4273 const struct got_error *err = NULL;
4274 const char *screen_dump_path;
4275 int in;
4277 if (test_script_path == NULL || *test_script_path == '\0')
4278 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4280 tog_io.f = fopen(test_script_path, "re");
4281 if (tog_io.f == NULL) {
4282 err = got_error_from_errno_fmt("fopen: %s",
4283 test_script_path);
4284 goto done;
4287 /* test mode, we don't want any output */
4288 tog_io.cout = fopen("/dev/null", "w+");
4289 if (tog_io.cout == NULL) {
4290 err = got_error_from_errno2("fopen", "/dev/null");
4291 goto done;
4294 in = dup(fileno(tog_io.cout));
4295 if (in == -1) {
4296 err = got_error_from_errno("dup");
4297 goto done;
4299 tog_io.cin = fdopen(in, "r");
4300 if (tog_io.cin == NULL) {
4301 err = got_error_from_errno("fdopen");
4302 close(in);
4303 goto done;
4306 screen_dump_path = getenv("TOG_SCR_DUMP");
4307 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4308 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4309 tog_io.sdump = fopen(screen_dump_path, "wex");
4310 if (tog_io.sdump == NULL) {
4311 err = got_error_from_errno2("fopen", screen_dump_path);
4312 goto done;
4315 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4316 err = got_error_from_errno("fseeko");
4317 goto done;
4320 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4321 err = got_error_msg(GOT_ERR_IO,
4322 "newterm: failed to initialise curses");
4324 using_mock_io = 1;
4326 done:
4327 if (err)
4328 tog_io_close();
4329 return err;
4332 static void
4333 init_curses(void)
4336 * Override default signal handlers before starting ncurses.
4337 * This should prevent ncurses from installing its own
4338 * broken cleanup() signal handler.
4340 signal(SIGWINCH, tog_sigwinch);
4341 signal(SIGPIPE, tog_sigpipe);
4342 signal(SIGCONT, tog_sigcont);
4343 signal(SIGINT, tog_sigint);
4344 signal(SIGTERM, tog_sigterm);
4346 if (using_mock_io) /* In test mode we use a fake terminal */
4347 return;
4349 initscr();
4351 cbreak();
4352 halfdelay(1); /* Fast refresh while initial view is loading. */
4353 noecho();
4354 nonl();
4355 intrflush(stdscr, FALSE);
4356 keypad(stdscr, TRUE);
4357 curs_set(0);
4358 if (getenv("TOG_COLORS") != NULL) {
4359 start_color();
4360 use_default_colors();
4363 return;
4366 static const struct got_error *
4367 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4368 struct got_repository *repo, struct got_worktree *worktree)
4370 const struct got_error *err = NULL;
4372 if (argc == 0) {
4373 *in_repo_path = strdup("/");
4374 if (*in_repo_path == NULL)
4375 return got_error_from_errno("strdup");
4376 return NULL;
4379 if (worktree) {
4380 const char *prefix = got_worktree_get_path_prefix(worktree);
4381 char *p;
4383 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4384 if (err)
4385 return err;
4386 if (asprintf(in_repo_path, "%s%s%s", prefix,
4387 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4388 p) == -1) {
4389 err = got_error_from_errno("asprintf");
4390 *in_repo_path = NULL;
4392 free(p);
4393 } else
4394 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4396 return err;
4399 static const struct got_error *
4400 cmd_log(int argc, char *argv[])
4402 const struct got_error *error;
4403 struct got_repository *repo = NULL;
4404 struct got_worktree *worktree = NULL;
4405 struct got_object_id *start_id = NULL;
4406 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4407 char *start_commit = NULL, *label = NULL;
4408 struct got_reference *ref = NULL;
4409 const char *head_ref_name = NULL;
4410 int ch, log_branches = 0;
4411 struct tog_view *view;
4412 int *pack_fds = NULL;
4414 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4415 switch (ch) {
4416 case 'b':
4417 log_branches = 1;
4418 break;
4419 case 'c':
4420 start_commit = optarg;
4421 break;
4422 case 'r':
4423 repo_path = realpath(optarg, NULL);
4424 if (repo_path == NULL)
4425 return got_error_from_errno2("realpath",
4426 optarg);
4427 break;
4428 default:
4429 usage_log();
4430 /* NOTREACHED */
4434 argc -= optind;
4435 argv += optind;
4437 if (argc > 1)
4438 usage_log();
4440 error = got_repo_pack_fds_open(&pack_fds);
4441 if (error != NULL)
4442 goto done;
4444 if (repo_path == NULL) {
4445 cwd = getcwd(NULL, 0);
4446 if (cwd == NULL)
4447 return got_error_from_errno("getcwd");
4448 error = got_worktree_open(&worktree, cwd);
4449 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4450 goto done;
4451 if (worktree)
4452 repo_path =
4453 strdup(got_worktree_get_repo_path(worktree));
4454 else
4455 repo_path = strdup(cwd);
4456 if (repo_path == NULL) {
4457 error = got_error_from_errno("strdup");
4458 goto done;
4462 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4463 if (error != NULL)
4464 goto done;
4466 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4467 repo, worktree);
4468 if (error)
4469 goto done;
4471 init_curses();
4473 error = apply_unveil(got_repo_get_path(repo),
4474 worktree ? got_worktree_get_root_path(worktree) : NULL);
4475 if (error)
4476 goto done;
4478 /* already loaded by tog_log_with_path()? */
4479 if (TAILQ_EMPTY(&tog_refs)) {
4480 error = tog_load_refs(repo, 0);
4481 if (error)
4482 goto done;
4485 if (start_commit == NULL) {
4486 error = got_repo_match_object_id(&start_id, &label,
4487 worktree ? got_worktree_get_head_ref_name(worktree) :
4488 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4489 if (error)
4490 goto done;
4491 head_ref_name = label;
4492 } else {
4493 error = got_ref_open(&ref, repo, start_commit, 0);
4494 if (error == NULL)
4495 head_ref_name = got_ref_get_name(ref);
4496 else if (error->code != GOT_ERR_NOT_REF)
4497 goto done;
4498 error = got_repo_match_object_id(&start_id, NULL,
4499 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4500 if (error)
4501 goto done;
4504 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4505 if (view == NULL) {
4506 error = got_error_from_errno("view_open");
4507 goto done;
4509 error = open_log_view(view, start_id, repo, head_ref_name,
4510 in_repo_path, log_branches);
4511 if (error)
4512 goto done;
4513 if (worktree) {
4514 /* Release work tree lock. */
4515 got_worktree_close(worktree);
4516 worktree = NULL;
4518 error = view_loop(view);
4519 done:
4520 free(in_repo_path);
4521 free(repo_path);
4522 free(cwd);
4523 free(start_id);
4524 free(label);
4525 if (ref)
4526 got_ref_close(ref);
4527 if (repo) {
4528 const struct got_error *close_err = got_repo_close(repo);
4529 if (error == NULL)
4530 error = close_err;
4532 if (worktree)
4533 got_worktree_close(worktree);
4534 if (pack_fds) {
4535 const struct got_error *pack_err =
4536 got_repo_pack_fds_close(pack_fds);
4537 if (error == NULL)
4538 error = pack_err;
4540 tog_free_refs();
4541 return error;
4544 __dead static void
4545 usage_diff(void)
4547 endwin();
4548 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4549 "object1 object2\n", getprogname());
4550 exit(1);
4553 static int
4554 match_line(const char *line, regex_t *regex, size_t nmatch,
4555 regmatch_t *regmatch)
4557 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4560 static struct tog_color *
4561 match_color(struct tog_colors *colors, const char *line)
4563 struct tog_color *tc = NULL;
4565 STAILQ_FOREACH(tc, colors, entry) {
4566 if (match_line(line, &tc->regex, 0, NULL))
4567 return tc;
4570 return NULL;
4573 static const struct got_error *
4574 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4575 WINDOW *window, int skipcol, regmatch_t *regmatch)
4577 const struct got_error *err = NULL;
4578 char *exstr = NULL;
4579 wchar_t *wline = NULL;
4580 int rme, rms, n, width, scrollx;
4581 int width0 = 0, width1 = 0, width2 = 0;
4582 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4584 *wtotal = 0;
4586 rms = regmatch->rm_so;
4587 rme = regmatch->rm_eo;
4589 err = expand_tab(&exstr, line);
4590 if (err)
4591 return err;
4593 /* Split the line into 3 segments, according to match offsets. */
4594 seg0 = strndup(exstr, rms);
4595 if (seg0 == NULL) {
4596 err = got_error_from_errno("strndup");
4597 goto done;
4599 seg1 = strndup(exstr + rms, rme - rms);
4600 if (seg1 == NULL) {
4601 err = got_error_from_errno("strndup");
4602 goto done;
4604 seg2 = strdup(exstr + rme);
4605 if (seg2 == NULL) {
4606 err = got_error_from_errno("strndup");
4607 goto done;
4610 /* draw up to matched token if we haven't scrolled past it */
4611 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4612 col_tab_align, 1);
4613 if (err)
4614 goto done;
4615 n = MAX(width0 - skipcol, 0);
4616 if (n) {
4617 free(wline);
4618 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4619 wlimit, col_tab_align, 1);
4620 if (err)
4621 goto done;
4622 waddwstr(window, &wline[scrollx]);
4623 wlimit -= width;
4624 *wtotal += width;
4627 if (wlimit > 0) {
4628 int i = 0, w = 0;
4629 size_t wlen;
4631 free(wline);
4632 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4633 col_tab_align, 1);
4634 if (err)
4635 goto done;
4636 wlen = wcslen(wline);
4637 while (i < wlen) {
4638 width = wcwidth(wline[i]);
4639 if (width == -1) {
4640 /* should not happen, tabs are expanded */
4641 err = got_error(GOT_ERR_RANGE);
4642 goto done;
4644 if (width0 + w + width > skipcol)
4645 break;
4646 w += width;
4647 i++;
4649 /* draw (visible part of) matched token (if scrolled into it) */
4650 if (width1 - w > 0) {
4651 wattron(window, A_STANDOUT);
4652 waddwstr(window, &wline[i]);
4653 wattroff(window, A_STANDOUT);
4654 wlimit -= (width1 - w);
4655 *wtotal += (width1 - w);
4659 if (wlimit > 0) { /* draw rest of line */
4660 free(wline);
4661 if (skipcol > width0 + width1) {
4662 err = format_line(&wline, &width2, &scrollx, seg2,
4663 skipcol - (width0 + width1), wlimit,
4664 col_tab_align, 1);
4665 if (err)
4666 goto done;
4667 waddwstr(window, &wline[scrollx]);
4668 } else {
4669 err = format_line(&wline, &width2, NULL, seg2, 0,
4670 wlimit, col_tab_align, 1);
4671 if (err)
4672 goto done;
4673 waddwstr(window, wline);
4675 *wtotal += width2;
4677 done:
4678 free(wline);
4679 free(exstr);
4680 free(seg0);
4681 free(seg1);
4682 free(seg2);
4683 return err;
4686 static int
4687 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4689 FILE *f = NULL;
4690 int *eof, *first, *selected;
4692 if (view->type == TOG_VIEW_DIFF) {
4693 struct tog_diff_view_state *s = &view->state.diff;
4695 first = &s->first_displayed_line;
4696 selected = first;
4697 eof = &s->eof;
4698 f = s->f;
4699 } else if (view->type == TOG_VIEW_HELP) {
4700 struct tog_help_view_state *s = &view->state.help;
4702 first = &s->first_displayed_line;
4703 selected = first;
4704 eof = &s->eof;
4705 f = s->f;
4706 } else if (view->type == TOG_VIEW_BLAME) {
4707 struct tog_blame_view_state *s = &view->state.blame;
4709 first = &s->first_displayed_line;
4710 selected = &s->selected_line;
4711 eof = &s->eof;
4712 f = s->blame.f;
4713 } else
4714 return 0;
4716 /* Center gline in the middle of the page like vi(1). */
4717 if (*lineno < view->gline - (view->nlines - 3) / 2)
4718 return 0;
4719 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4720 rewind(f);
4721 *eof = 0;
4722 *first = 1;
4723 *lineno = 0;
4724 *nprinted = 0;
4725 return 0;
4728 *selected = view->gline <= (view->nlines - 3) / 2 ?
4729 view->gline : (view->nlines - 3) / 2 + 1;
4730 view->gline = 0;
4732 return 1;
4735 static const struct got_error *
4736 draw_file(struct tog_view *view, const char *header)
4738 struct tog_diff_view_state *s = &view->state.diff;
4739 regmatch_t *regmatch = &view->regmatch;
4740 const struct got_error *err;
4741 int nprinted = 0;
4742 char *line;
4743 size_t linesize = 0;
4744 ssize_t linelen;
4745 wchar_t *wline;
4746 int width;
4747 int max_lines = view->nlines;
4748 int nlines = s->nlines;
4749 off_t line_offset;
4751 s->lineno = s->first_displayed_line - 1;
4752 line_offset = s->lines[s->first_displayed_line - 1].offset;
4753 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4754 return got_error_from_errno("fseek");
4756 werase(view->window);
4758 if (view->gline > s->nlines - 1)
4759 view->gline = s->nlines - 1;
4761 if (header) {
4762 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4763 1 : view->gline - (view->nlines - 3) / 2 :
4764 s->lineno + s->selected_line;
4766 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4767 return got_error_from_errno("asprintf");
4768 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4769 0, 0);
4770 free(line);
4771 if (err)
4772 return err;
4774 if (view_needs_focus_indication(view))
4775 wstandout(view->window);
4776 waddwstr(view->window, wline);
4777 free(wline);
4778 wline = NULL;
4779 while (width++ < view->ncols)
4780 waddch(view->window, ' ');
4781 if (view_needs_focus_indication(view))
4782 wstandend(view->window);
4784 if (max_lines <= 1)
4785 return NULL;
4786 max_lines--;
4789 s->eof = 0;
4790 view->maxx = 0;
4791 line = NULL;
4792 while (max_lines > 0 && nprinted < max_lines) {
4793 enum got_diff_line_type linetype;
4794 attr_t attr = 0;
4796 linelen = getline(&line, &linesize, s->f);
4797 if (linelen == -1) {
4798 if (feof(s->f)) {
4799 s->eof = 1;
4800 break;
4802 free(line);
4803 return got_ferror(s->f, GOT_ERR_IO);
4806 if (++s->lineno < s->first_displayed_line)
4807 continue;
4808 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4809 continue;
4810 if (s->lineno == view->hiline)
4811 attr = A_STANDOUT;
4813 /* Set view->maxx based on full line length. */
4814 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4815 view->x ? 1 : 0);
4816 if (err) {
4817 free(line);
4818 return err;
4820 view->maxx = MAX(view->maxx, width);
4821 free(wline);
4822 wline = NULL;
4824 linetype = s->lines[s->lineno].type;
4825 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4826 linetype < GOT_DIFF_LINE_CONTEXT)
4827 attr |= COLOR_PAIR(linetype);
4828 if (attr)
4829 wattron(view->window, attr);
4830 if (s->first_displayed_line + nprinted == s->matched_line &&
4831 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4832 err = add_matched_line(&width, line, view->ncols, 0,
4833 view->window, view->x, regmatch);
4834 if (err) {
4835 free(line);
4836 return err;
4838 } else {
4839 int skip;
4840 err = format_line(&wline, &width, &skip, line,
4841 view->x, view->ncols, 0, view->x ? 1 : 0);
4842 if (err) {
4843 free(line);
4844 return err;
4846 waddwstr(view->window, &wline[skip]);
4847 free(wline);
4848 wline = NULL;
4850 if (s->lineno == view->hiline) {
4851 /* highlight full gline length */
4852 while (width++ < view->ncols)
4853 waddch(view->window, ' ');
4854 } else {
4855 if (width <= view->ncols - 1)
4856 waddch(view->window, '\n');
4858 if (attr)
4859 wattroff(view->window, attr);
4860 if (++nprinted == 1)
4861 s->first_displayed_line = s->lineno;
4863 free(line);
4864 if (nprinted >= 1)
4865 s->last_displayed_line = s->first_displayed_line +
4866 (nprinted - 1);
4867 else
4868 s->last_displayed_line = s->first_displayed_line;
4870 view_border(view);
4872 if (s->eof) {
4873 while (nprinted < view->nlines) {
4874 waddch(view->window, '\n');
4875 nprinted++;
4878 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4879 view->ncols, 0, 0);
4880 if (err) {
4881 return err;
4884 wstandout(view->window);
4885 waddwstr(view->window, wline);
4886 free(wline);
4887 wline = NULL;
4888 wstandend(view->window);
4891 return NULL;
4894 static char *
4895 get_datestr(time_t *time, char *datebuf)
4897 struct tm mytm, *tm;
4898 char *p, *s;
4900 tm = gmtime_r(time, &mytm);
4901 if (tm == NULL)
4902 return NULL;
4903 s = asctime_r(tm, datebuf);
4904 if (s == NULL)
4905 return NULL;
4906 p = strchr(s, '\n');
4907 if (p)
4908 *p = '\0';
4909 return s;
4912 static const struct got_error *
4913 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4914 off_t off, uint8_t type)
4916 struct got_diff_line *p;
4918 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4919 if (p == NULL)
4920 return got_error_from_errno("reallocarray");
4921 *lines = p;
4922 (*lines)[*nlines].offset = off;
4923 (*lines)[*nlines].type = type;
4924 (*nlines)++;
4926 return NULL;
4929 static const struct got_error *
4930 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4931 struct got_diff_line *s_lines, size_t s_nlines)
4933 struct got_diff_line *p;
4934 char buf[BUFSIZ];
4935 size_t i, r;
4937 if (fseeko(src, 0L, SEEK_SET) == -1)
4938 return got_error_from_errno("fseeko");
4940 for (;;) {
4941 r = fread(buf, 1, sizeof(buf), src);
4942 if (r == 0) {
4943 if (ferror(src))
4944 return got_error_from_errno("fread");
4945 if (feof(src))
4946 break;
4948 if (fwrite(buf, 1, r, dst) != r)
4949 return got_ferror(dst, GOT_ERR_IO);
4952 if (s_nlines == 0 && *d_nlines == 0)
4953 return NULL;
4956 * If commit info was in dst, increment line offsets
4957 * of the appended diff content, but skip s_lines[0]
4958 * because offset zero is already in *d_lines.
4960 if (*d_nlines > 0) {
4961 for (i = 1; i < s_nlines; ++i)
4962 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4964 if (s_nlines > 0) {
4965 --s_nlines;
4966 ++s_lines;
4970 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4971 if (p == NULL) {
4972 /* d_lines is freed in close_diff_view() */
4973 return got_error_from_errno("reallocarray");
4976 *d_lines = p;
4978 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4979 *d_nlines += s_nlines;
4981 return NULL;
4984 static const struct got_error *
4985 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4986 struct got_object_id *commit_id, struct got_reflist_head *refs,
4987 struct got_repository *repo, int ignore_ws, int force_text_diff,
4988 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4990 const struct got_error *err = NULL;
4991 char datebuf[26], *datestr;
4992 struct got_commit_object *commit;
4993 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4994 time_t committer_time;
4995 const char *author, *committer;
4996 char *refs_str = NULL;
4997 struct got_pathlist_entry *pe;
4998 off_t outoff = 0;
4999 int n;
5001 err = build_refs_str(&refs_str, refs, commit_id, repo);
5002 if (err)
5003 return err;
5005 err = got_object_open_as_commit(&commit, repo, commit_id);
5006 if (err)
5007 return err;
5009 err = got_object_id_str(&id_str, commit_id);
5010 if (err) {
5011 err = got_error_from_errno("got_object_id_str");
5012 goto done;
5015 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
5016 if (err)
5017 goto done;
5019 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
5020 refs_str ? refs_str : "", refs_str ? ")" : "");
5021 if (n < 0) {
5022 err = got_error_from_errno("fprintf");
5023 goto done;
5025 outoff += n;
5026 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
5027 if (err)
5028 goto done;
5030 n = fprintf(outfile, "from: %s\n",
5031 got_object_commit_get_author(commit));
5032 if (n < 0) {
5033 err = got_error_from_errno("fprintf");
5034 goto done;
5036 outoff += n;
5037 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
5038 if (err)
5039 goto done;
5041 author = got_object_commit_get_author(commit);
5042 committer = got_object_commit_get_committer(commit);
5043 if (strcmp(author, committer) != 0) {
5044 n = fprintf(outfile, "via: %s\n", committer);
5045 if (n < 0) {
5046 err = got_error_from_errno("fprintf");
5047 goto done;
5049 outoff += n;
5050 err = add_line_metadata(lines, nlines, outoff,
5051 GOT_DIFF_LINE_AUTHOR);
5052 if (err)
5053 goto done;
5055 committer_time = got_object_commit_get_committer_time(commit);
5056 datestr = get_datestr(&committer_time, datebuf);
5057 if (datestr) {
5058 n = fprintf(outfile, "date: %s UTC\n", datestr);
5059 if (n < 0) {
5060 err = got_error_from_errno("fprintf");
5061 goto done;
5063 outoff += n;
5064 err = add_line_metadata(lines, nlines, outoff,
5065 GOT_DIFF_LINE_DATE);
5066 if (err)
5067 goto done;
5069 if (got_object_commit_get_nparents(commit) > 1) {
5070 const struct got_object_id_queue *parent_ids;
5071 struct got_object_qid *qid;
5072 int pn = 1;
5073 parent_ids = got_object_commit_get_parent_ids(commit);
5074 STAILQ_FOREACH(qid, parent_ids, entry) {
5075 err = got_object_id_str(&id_str, &qid->id);
5076 if (err)
5077 goto done;
5078 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5079 if (n < 0) {
5080 err = got_error_from_errno("fprintf");
5081 goto done;
5083 outoff += n;
5084 err = add_line_metadata(lines, nlines, outoff,
5085 GOT_DIFF_LINE_META);
5086 if (err)
5087 goto done;
5088 free(id_str);
5089 id_str = NULL;
5093 err = got_object_commit_get_logmsg(&logmsg, commit);
5094 if (err)
5095 goto done;
5096 s = logmsg;
5097 while ((line = strsep(&s, "\n")) != NULL) {
5098 n = fprintf(outfile, "%s\n", line);
5099 if (n < 0) {
5100 err = got_error_from_errno("fprintf");
5101 goto done;
5103 outoff += n;
5104 err = add_line_metadata(lines, nlines, outoff,
5105 GOT_DIFF_LINE_LOGMSG);
5106 if (err)
5107 goto done;
5110 TAILQ_FOREACH(pe, dsa->paths, entry) {
5111 struct got_diff_changed_path *cp = pe->data;
5112 int pad = dsa->max_path_len - pe->path_len + 1;
5114 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5115 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5116 dsa->rm_cols + 1, cp->rm);
5117 if (n < 0) {
5118 err = got_error_from_errno("fprintf");
5119 goto done;
5121 outoff += n;
5122 err = add_line_metadata(lines, nlines, outoff,
5123 GOT_DIFF_LINE_CHANGES);
5124 if (err)
5125 goto done;
5128 fputc('\n', outfile);
5129 outoff++;
5130 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5131 if (err)
5132 goto done;
5134 n = fprintf(outfile,
5135 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5136 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5137 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5138 if (n < 0) {
5139 err = got_error_from_errno("fprintf");
5140 goto done;
5142 outoff += n;
5143 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5144 if (err)
5145 goto done;
5147 fputc('\n', outfile);
5148 outoff++;
5149 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5150 done:
5151 free(id_str);
5152 free(logmsg);
5153 free(refs_str);
5154 got_object_commit_close(commit);
5155 if (err) {
5156 free(*lines);
5157 *lines = NULL;
5158 *nlines = 0;
5160 return err;
5163 static const struct got_error *
5164 create_diff(struct tog_diff_view_state *s)
5166 const struct got_error *err = NULL;
5167 FILE *f = NULL, *tmp_diff_file = NULL;
5168 int obj_type;
5169 struct got_diff_line *lines = NULL;
5170 struct got_pathlist_head changed_paths;
5172 TAILQ_INIT(&changed_paths);
5174 free(s->lines);
5175 s->lines = malloc(sizeof(*s->lines));
5176 if (s->lines == NULL)
5177 return got_error_from_errno("malloc");
5178 s->nlines = 0;
5180 f = got_opentemp();
5181 if (f == NULL) {
5182 err = got_error_from_errno("got_opentemp");
5183 goto done;
5185 tmp_diff_file = got_opentemp();
5186 if (tmp_diff_file == NULL) {
5187 err = got_error_from_errno("got_opentemp");
5188 goto done;
5190 if (s->f && fclose(s->f) == EOF) {
5191 err = got_error_from_errno("fclose");
5192 goto done;
5194 s->f = f;
5196 if (s->id1)
5197 err = got_object_get_type(&obj_type, s->repo, s->id1);
5198 else
5199 err = got_object_get_type(&obj_type, s->repo, s->id2);
5200 if (err)
5201 goto done;
5203 switch (obj_type) {
5204 case GOT_OBJ_TYPE_BLOB:
5205 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5206 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5207 s->label1, s->label2, tog_diff_algo, s->diff_context,
5208 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5209 s->f);
5210 break;
5211 case GOT_OBJ_TYPE_TREE:
5212 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5213 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5214 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5215 s->force_text_diff, NULL, s->repo, s->f);
5216 break;
5217 case GOT_OBJ_TYPE_COMMIT: {
5218 const struct got_object_id_queue *parent_ids;
5219 struct got_object_qid *pid;
5220 struct got_commit_object *commit2;
5221 struct got_reflist_head *refs;
5222 size_t nlines = 0;
5223 struct got_diffstat_cb_arg dsa = {
5224 0, 0, 0, 0, 0, 0,
5225 &changed_paths,
5226 s->ignore_whitespace,
5227 s->force_text_diff,
5228 tog_diff_algo
5231 lines = malloc(sizeof(*lines));
5232 if (lines == NULL) {
5233 err = got_error_from_errno("malloc");
5234 goto done;
5237 /* build diff first in tmp file then append to commit info */
5238 err = got_diff_objects_as_commits(&lines, &nlines,
5239 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5240 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5241 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5242 if (err)
5243 break;
5245 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5246 if (err)
5247 goto done;
5248 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5249 /* Show commit info if we're diffing to a parent/root commit. */
5250 if (s->id1 == NULL) {
5251 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5252 refs, s->repo, s->ignore_whitespace,
5253 s->force_text_diff, &dsa, s->f);
5254 if (err)
5255 goto done;
5256 } else {
5257 parent_ids = got_object_commit_get_parent_ids(commit2);
5258 STAILQ_FOREACH(pid, parent_ids, entry) {
5259 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5260 err = write_commit_info(&s->lines,
5261 &s->nlines, s->id2, refs, s->repo,
5262 s->ignore_whitespace,
5263 s->force_text_diff, &dsa, s->f);
5264 if (err)
5265 goto done;
5266 break;
5270 got_object_commit_close(commit2);
5272 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5273 lines, nlines);
5274 break;
5276 default:
5277 err = got_error(GOT_ERR_OBJ_TYPE);
5278 break;
5280 done:
5281 free(lines);
5282 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5283 if (s->f && fflush(s->f) != 0 && err == NULL)
5284 err = got_error_from_errno("fflush");
5285 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5286 err = got_error_from_errno("fclose");
5287 return err;
5290 static void
5291 diff_view_indicate_progress(struct tog_view *view)
5293 mvwaddstr(view->window, 0, 0, "diffing...");
5294 update_panels();
5295 doupdate();
5298 static const struct got_error *
5299 search_start_diff_view(struct tog_view *view)
5301 struct tog_diff_view_state *s = &view->state.diff;
5303 s->matched_line = 0;
5304 return NULL;
5307 static void
5308 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5309 size_t *nlines, int **first, int **last, int **match, int **selected)
5311 struct tog_diff_view_state *s = &view->state.diff;
5313 *f = s->f;
5314 *nlines = s->nlines;
5315 *line_offsets = NULL;
5316 *match = &s->matched_line;
5317 *first = &s->first_displayed_line;
5318 *last = &s->last_displayed_line;
5319 *selected = &s->selected_line;
5322 static const struct got_error *
5323 search_next_view_match(struct tog_view *view)
5325 const struct got_error *err = NULL;
5326 FILE *f;
5327 int lineno;
5328 char *line = NULL;
5329 size_t linesize = 0;
5330 ssize_t linelen;
5331 off_t *line_offsets;
5332 size_t nlines = 0;
5333 int *first, *last, *match, *selected;
5335 if (!view->search_setup)
5336 return got_error_msg(GOT_ERR_NOT_IMPL,
5337 "view search not supported");
5338 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5339 &match, &selected);
5341 if (!view->searching) {
5342 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5343 return NULL;
5346 if (*match) {
5347 if (view->searching == TOG_SEARCH_FORWARD)
5348 lineno = *first + 1;
5349 else
5350 lineno = *first - 1;
5351 } else
5352 lineno = *first - 1 + *selected;
5354 while (1) {
5355 off_t offset;
5357 if (lineno <= 0 || lineno > nlines) {
5358 if (*match == 0) {
5359 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5360 break;
5363 if (view->searching == TOG_SEARCH_FORWARD)
5364 lineno = 1;
5365 else
5366 lineno = nlines;
5369 offset = view->type == TOG_VIEW_DIFF ?
5370 view->state.diff.lines[lineno - 1].offset :
5371 line_offsets[lineno - 1];
5372 if (fseeko(f, offset, SEEK_SET) != 0) {
5373 free(line);
5374 return got_error_from_errno("fseeko");
5376 linelen = getline(&line, &linesize, f);
5377 if (linelen != -1) {
5378 char *exstr;
5379 err = expand_tab(&exstr, line);
5380 if (err)
5381 break;
5382 if (match_line(exstr, &view->regex, 1,
5383 &view->regmatch)) {
5384 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5385 *match = lineno;
5386 free(exstr);
5387 break;
5389 free(exstr);
5391 if (view->searching == TOG_SEARCH_FORWARD)
5392 lineno++;
5393 else
5394 lineno--;
5396 free(line);
5398 if (*match) {
5399 *first = *match;
5400 *selected = 1;
5403 return err;
5406 static const struct got_error *
5407 close_diff_view(struct tog_view *view)
5409 const struct got_error *err = NULL;
5410 struct tog_diff_view_state *s = &view->state.diff;
5412 free(s->id1);
5413 s->id1 = NULL;
5414 free(s->id2);
5415 s->id2 = NULL;
5416 if (s->f && fclose(s->f) == EOF)
5417 err = got_error_from_errno("fclose");
5418 s->f = NULL;
5419 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5420 err = got_error_from_errno("fclose");
5421 s->f1 = NULL;
5422 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5423 err = got_error_from_errno("fclose");
5424 s->f2 = NULL;
5425 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5426 err = got_error_from_errno("close");
5427 s->fd1 = -1;
5428 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5429 err = got_error_from_errno("close");
5430 s->fd2 = -1;
5431 free(s->lines);
5432 s->lines = NULL;
5433 s->nlines = 0;
5434 return err;
5437 static const struct got_error *
5438 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5439 struct got_object_id *id2, const char *label1, const char *label2,
5440 int diff_context, int ignore_whitespace, int force_text_diff,
5441 struct tog_view *parent_view, struct got_repository *repo)
5443 const struct got_error *err;
5444 struct tog_diff_view_state *s = &view->state.diff;
5446 memset(s, 0, sizeof(*s));
5447 s->fd1 = -1;
5448 s->fd2 = -1;
5450 if (id1 != NULL && id2 != NULL) {
5451 int type1, type2;
5453 err = got_object_get_type(&type1, repo, id1);
5454 if (err)
5455 goto done;
5456 err = got_object_get_type(&type2, repo, id2);
5457 if (err)
5458 goto done;
5460 if (type1 != type2) {
5461 err = got_error(GOT_ERR_OBJ_TYPE);
5462 goto done;
5465 s->first_displayed_line = 1;
5466 s->last_displayed_line = view->nlines;
5467 s->selected_line = 1;
5468 s->repo = repo;
5469 s->id1 = id1;
5470 s->id2 = id2;
5471 s->label1 = label1;
5472 s->label2 = label2;
5474 if (id1) {
5475 s->id1 = got_object_id_dup(id1);
5476 if (s->id1 == NULL) {
5477 err = got_error_from_errno("got_object_id_dup");
5478 goto done;
5480 } else
5481 s->id1 = NULL;
5483 s->id2 = got_object_id_dup(id2);
5484 if (s->id2 == NULL) {
5485 err = got_error_from_errno("got_object_id_dup");
5486 goto done;
5489 s->f1 = got_opentemp();
5490 if (s->f1 == NULL) {
5491 err = got_error_from_errno("got_opentemp");
5492 goto done;
5495 s->f2 = got_opentemp();
5496 if (s->f2 == NULL) {
5497 err = got_error_from_errno("got_opentemp");
5498 goto done;
5501 s->fd1 = got_opentempfd();
5502 if (s->fd1 == -1) {
5503 err = got_error_from_errno("got_opentempfd");
5504 goto done;
5507 s->fd2 = got_opentempfd();
5508 if (s->fd2 == -1) {
5509 err = got_error_from_errno("got_opentempfd");
5510 goto done;
5513 s->diff_context = diff_context;
5514 s->ignore_whitespace = ignore_whitespace;
5515 s->force_text_diff = force_text_diff;
5516 s->parent_view = parent_view;
5517 s->repo = repo;
5519 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5520 int rc;
5522 rc = init_pair(GOT_DIFF_LINE_MINUS,
5523 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5524 if (rc != ERR)
5525 rc = init_pair(GOT_DIFF_LINE_PLUS,
5526 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5527 if (rc != ERR)
5528 rc = init_pair(GOT_DIFF_LINE_HUNK,
5529 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5530 if (rc != ERR)
5531 rc = init_pair(GOT_DIFF_LINE_META,
5532 get_color_value("TOG_COLOR_DIFF_META"), -1);
5533 if (rc != ERR)
5534 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5535 get_color_value("TOG_COLOR_DIFF_META"), -1);
5536 if (rc != ERR)
5537 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5538 get_color_value("TOG_COLOR_DIFF_META"), -1);
5539 if (rc != ERR)
5540 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5541 get_color_value("TOG_COLOR_DIFF_META"), -1);
5542 if (rc != ERR)
5543 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5544 get_color_value("TOG_COLOR_AUTHOR"), -1);
5545 if (rc != ERR)
5546 rc = init_pair(GOT_DIFF_LINE_DATE,
5547 get_color_value("TOG_COLOR_DATE"), -1);
5548 if (rc == ERR) {
5549 err = got_error(GOT_ERR_RANGE);
5550 goto done;
5554 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5555 view_is_splitscreen(view))
5556 show_log_view(parent_view); /* draw border */
5557 diff_view_indicate_progress(view);
5559 err = create_diff(s);
5561 view->show = show_diff_view;
5562 view->input = input_diff_view;
5563 view->reset = reset_diff_view;
5564 view->close = close_diff_view;
5565 view->search_start = search_start_diff_view;
5566 view->search_setup = search_setup_diff_view;
5567 view->search_next = search_next_view_match;
5568 done:
5569 if (err) {
5570 if (view->close == NULL)
5571 close_diff_view(view);
5572 view_close(view);
5574 return err;
5577 static const struct got_error *
5578 show_diff_view(struct tog_view *view)
5580 const struct got_error *err;
5581 struct tog_diff_view_state *s = &view->state.diff;
5582 char *id_str1 = NULL, *id_str2, *header;
5583 const char *label1, *label2;
5585 if (s->id1) {
5586 err = got_object_id_str(&id_str1, s->id1);
5587 if (err)
5588 return err;
5589 label1 = s->label1 ? s->label1 : id_str1;
5590 } else
5591 label1 = "/dev/null";
5593 err = got_object_id_str(&id_str2, s->id2);
5594 if (err)
5595 return err;
5596 label2 = s->label2 ? s->label2 : id_str2;
5598 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5599 err = got_error_from_errno("asprintf");
5600 free(id_str1);
5601 free(id_str2);
5602 return err;
5604 free(id_str1);
5605 free(id_str2);
5607 err = draw_file(view, header);
5608 free(header);
5609 return err;
5612 static const struct got_error *
5613 set_selected_commit(struct tog_diff_view_state *s,
5614 struct commit_queue_entry *entry)
5616 const struct got_error *err;
5617 const struct got_object_id_queue *parent_ids;
5618 struct got_commit_object *selected_commit;
5619 struct got_object_qid *pid;
5621 free(s->id2);
5622 s->id2 = got_object_id_dup(entry->id);
5623 if (s->id2 == NULL)
5624 return got_error_from_errno("got_object_id_dup");
5626 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5627 if (err)
5628 return err;
5629 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5630 free(s->id1);
5631 pid = STAILQ_FIRST(parent_ids);
5632 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5633 got_object_commit_close(selected_commit);
5634 return NULL;
5637 static const struct got_error *
5638 reset_diff_view(struct tog_view *view)
5640 struct tog_diff_view_state *s = &view->state.diff;
5642 view->count = 0;
5643 wclear(view->window);
5644 s->first_displayed_line = 1;
5645 s->last_displayed_line = view->nlines;
5646 s->matched_line = 0;
5647 diff_view_indicate_progress(view);
5648 return create_diff(s);
5651 static void
5652 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5654 int start, i;
5656 i = start = s->first_displayed_line - 1;
5658 while (s->lines[i].type != type) {
5659 if (i == 0)
5660 i = s->nlines - 1;
5661 if (--i == start)
5662 return; /* do nothing, requested type not in file */
5665 s->selected_line = 1;
5666 s->first_displayed_line = i;
5669 static void
5670 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5672 int start, i;
5674 i = start = s->first_displayed_line + 1;
5676 while (s->lines[i].type != type) {
5677 if (i == s->nlines - 1)
5678 i = 0;
5679 if (++i == start)
5680 return; /* do nothing, requested type not in file */
5683 s->selected_line = 1;
5684 s->first_displayed_line = i;
5687 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5688 int, int, int);
5689 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5690 int, int);
5692 static const struct got_error *
5693 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5695 const struct got_error *err = NULL;
5696 struct tog_diff_view_state *s = &view->state.diff;
5697 struct tog_log_view_state *ls;
5698 struct commit_queue_entry *old_selected_entry;
5699 char *line = NULL;
5700 size_t linesize = 0;
5701 ssize_t linelen;
5702 int i, nscroll = view->nlines - 1, up = 0;
5704 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5706 switch (ch) {
5707 case '0':
5708 case '$':
5709 case KEY_RIGHT:
5710 case 'l':
5711 case KEY_LEFT:
5712 case 'h':
5713 horizontal_scroll_input(view, ch);
5714 break;
5715 case 'a':
5716 case 'w':
5717 if (ch == 'a') {
5718 s->force_text_diff = !s->force_text_diff;
5719 view->action = s->force_text_diff ?
5720 "force ASCII text enabled" :
5721 "force ASCII text disabled";
5723 else if (ch == 'w') {
5724 s->ignore_whitespace = !s->ignore_whitespace;
5725 view->action = s->ignore_whitespace ?
5726 "ignore whitespace enabled" :
5727 "ignore whitespace disabled";
5729 err = reset_diff_view(view);
5730 break;
5731 case 'g':
5732 case KEY_HOME:
5733 s->first_displayed_line = 1;
5734 view->count = 0;
5735 break;
5736 case 'G':
5737 case KEY_END:
5738 view->count = 0;
5739 if (s->eof)
5740 break;
5742 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5743 s->eof = 1;
5744 break;
5745 case 'k':
5746 case KEY_UP:
5747 case CTRL('p'):
5748 if (s->first_displayed_line > 1)
5749 s->first_displayed_line--;
5750 else
5751 view->count = 0;
5752 break;
5753 case CTRL('u'):
5754 case 'u':
5755 nscroll /= 2;
5756 /* FALL THROUGH */
5757 case KEY_PPAGE:
5758 case CTRL('b'):
5759 case 'b':
5760 if (s->first_displayed_line == 1) {
5761 view->count = 0;
5762 break;
5764 i = 0;
5765 while (i++ < nscroll && s->first_displayed_line > 1)
5766 s->first_displayed_line--;
5767 break;
5768 case 'j':
5769 case KEY_DOWN:
5770 case CTRL('n'):
5771 if (!s->eof)
5772 s->first_displayed_line++;
5773 else
5774 view->count = 0;
5775 break;
5776 case CTRL('d'):
5777 case 'd':
5778 nscroll /= 2;
5779 /* FALL THROUGH */
5780 case KEY_NPAGE:
5781 case CTRL('f'):
5782 case 'f':
5783 case ' ':
5784 if (s->eof) {
5785 view->count = 0;
5786 break;
5788 i = 0;
5789 while (!s->eof && i++ < nscroll) {
5790 linelen = getline(&line, &linesize, s->f);
5791 s->first_displayed_line++;
5792 if (linelen == -1) {
5793 if (feof(s->f)) {
5794 s->eof = 1;
5795 } else
5796 err = got_ferror(s->f, GOT_ERR_IO);
5797 break;
5800 free(line);
5801 break;
5802 case '(':
5803 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5804 break;
5805 case ')':
5806 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5807 break;
5808 case '{':
5809 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5810 break;
5811 case '}':
5812 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5813 break;
5814 case '[':
5815 if (s->diff_context > 0) {
5816 s->diff_context--;
5817 s->matched_line = 0;
5818 diff_view_indicate_progress(view);
5819 err = create_diff(s);
5820 if (s->first_displayed_line + view->nlines - 1 >
5821 s->nlines) {
5822 s->first_displayed_line = 1;
5823 s->last_displayed_line = view->nlines;
5825 } else
5826 view->count = 0;
5827 break;
5828 case ']':
5829 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5830 s->diff_context++;
5831 s->matched_line = 0;
5832 diff_view_indicate_progress(view);
5833 err = create_diff(s);
5834 } else
5835 view->count = 0;
5836 break;
5837 case '<':
5838 case ',':
5839 case 'K':
5840 up = 1;
5841 /* FALL THROUGH */
5842 case '>':
5843 case '.':
5844 case 'J':
5845 if (s->parent_view == NULL) {
5846 view->count = 0;
5847 break;
5849 s->parent_view->count = view->count;
5851 if (s->parent_view->type == TOG_VIEW_LOG) {
5852 ls = &s->parent_view->state.log;
5853 old_selected_entry = ls->selected_entry;
5855 err = input_log_view(NULL, s->parent_view,
5856 up ? KEY_UP : KEY_DOWN);
5857 if (err)
5858 break;
5859 view->count = s->parent_view->count;
5861 if (old_selected_entry == ls->selected_entry)
5862 break;
5864 err = set_selected_commit(s, ls->selected_entry);
5865 if (err)
5866 break;
5867 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5868 struct tog_blame_view_state *bs;
5869 struct got_object_id *id, *prev_id;
5871 bs = &s->parent_view->state.blame;
5872 prev_id = get_annotation_for_line(bs->blame.lines,
5873 bs->blame.nlines, bs->last_diffed_line);
5875 err = input_blame_view(&view, s->parent_view,
5876 up ? KEY_UP : KEY_DOWN);
5877 if (err)
5878 break;
5879 view->count = s->parent_view->count;
5881 if (prev_id == NULL)
5882 break;
5883 id = get_selected_commit_id(bs->blame.lines,
5884 bs->blame.nlines, bs->first_displayed_line,
5885 bs->selected_line);
5886 if (id == NULL)
5887 break;
5889 if (!got_object_id_cmp(prev_id, id))
5890 break;
5892 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5893 if (err)
5894 break;
5896 s->first_displayed_line = 1;
5897 s->last_displayed_line = view->nlines;
5898 s->matched_line = 0;
5899 view->x = 0;
5901 diff_view_indicate_progress(view);
5902 err = create_diff(s);
5903 break;
5904 default:
5905 view->count = 0;
5906 break;
5909 return err;
5912 static const struct got_error *
5913 cmd_diff(int argc, char *argv[])
5915 const struct got_error *error;
5916 struct got_repository *repo = NULL;
5917 struct got_worktree *worktree = NULL;
5918 struct got_object_id *id1 = NULL, *id2 = NULL;
5919 char *repo_path = NULL, *cwd = NULL;
5920 char *id_str1 = NULL, *id_str2 = NULL;
5921 char *label1 = NULL, *label2 = NULL;
5922 int diff_context = 3, ignore_whitespace = 0;
5923 int ch, force_text_diff = 0;
5924 const char *errstr;
5925 struct tog_view *view;
5926 int *pack_fds = NULL;
5928 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5929 switch (ch) {
5930 case 'a':
5931 force_text_diff = 1;
5932 break;
5933 case 'C':
5934 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5935 &errstr);
5936 if (errstr != NULL)
5937 errx(1, "number of context lines is %s: %s",
5938 errstr, errstr);
5939 break;
5940 case 'r':
5941 repo_path = realpath(optarg, NULL);
5942 if (repo_path == NULL)
5943 return got_error_from_errno2("realpath",
5944 optarg);
5945 got_path_strip_trailing_slashes(repo_path);
5946 break;
5947 case 'w':
5948 ignore_whitespace = 1;
5949 break;
5950 default:
5951 usage_diff();
5952 /* NOTREACHED */
5956 argc -= optind;
5957 argv += optind;
5959 if (argc == 0) {
5960 usage_diff(); /* TODO show local worktree changes */
5961 } else if (argc == 2) {
5962 id_str1 = argv[0];
5963 id_str2 = argv[1];
5964 } else
5965 usage_diff();
5967 error = got_repo_pack_fds_open(&pack_fds);
5968 if (error)
5969 goto done;
5971 if (repo_path == NULL) {
5972 cwd = getcwd(NULL, 0);
5973 if (cwd == NULL)
5974 return got_error_from_errno("getcwd");
5975 error = got_worktree_open(&worktree, cwd);
5976 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5977 goto done;
5978 if (worktree)
5979 repo_path =
5980 strdup(got_worktree_get_repo_path(worktree));
5981 else
5982 repo_path = strdup(cwd);
5983 if (repo_path == NULL) {
5984 error = got_error_from_errno("strdup");
5985 goto done;
5989 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5990 if (error)
5991 goto done;
5993 init_curses();
5995 error = apply_unveil(got_repo_get_path(repo), NULL);
5996 if (error)
5997 goto done;
5999 error = tog_load_refs(repo, 0);
6000 if (error)
6001 goto done;
6003 error = got_repo_match_object_id(&id1, &label1, id_str1,
6004 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6005 if (error)
6006 goto done;
6008 error = got_repo_match_object_id(&id2, &label2, id_str2,
6009 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6010 if (error)
6011 goto done;
6013 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
6014 if (view == NULL) {
6015 error = got_error_from_errno("view_open");
6016 goto done;
6018 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
6019 ignore_whitespace, force_text_diff, NULL, repo);
6020 if (error)
6021 goto done;
6022 error = view_loop(view);
6023 done:
6024 free(label1);
6025 free(label2);
6026 free(repo_path);
6027 free(cwd);
6028 if (repo) {
6029 const struct got_error *close_err = got_repo_close(repo);
6030 if (error == NULL)
6031 error = close_err;
6033 if (worktree)
6034 got_worktree_close(worktree);
6035 if (pack_fds) {
6036 const struct got_error *pack_err =
6037 got_repo_pack_fds_close(pack_fds);
6038 if (error == NULL)
6039 error = pack_err;
6041 tog_free_refs();
6042 return error;
6045 __dead static void
6046 usage_blame(void)
6048 endwin();
6049 fprintf(stderr,
6050 "usage: %s blame [-c commit] [-r repository-path] path\n",
6051 getprogname());
6052 exit(1);
6055 struct tog_blame_line {
6056 int annotated;
6057 struct got_object_id *id;
6060 static const struct got_error *
6061 draw_blame(struct tog_view *view)
6063 struct tog_blame_view_state *s = &view->state.blame;
6064 struct tog_blame *blame = &s->blame;
6065 regmatch_t *regmatch = &view->regmatch;
6066 const struct got_error *err;
6067 int lineno = 0, nprinted = 0;
6068 char *line = NULL;
6069 size_t linesize = 0;
6070 ssize_t linelen;
6071 wchar_t *wline;
6072 int width;
6073 struct tog_blame_line *blame_line;
6074 struct got_object_id *prev_id = NULL;
6075 char *id_str;
6076 struct tog_color *tc;
6078 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6079 if (err)
6080 return err;
6082 rewind(blame->f);
6083 werase(view->window);
6085 if (asprintf(&line, "commit %s", id_str) == -1) {
6086 err = got_error_from_errno("asprintf");
6087 free(id_str);
6088 return err;
6091 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6092 free(line);
6093 line = NULL;
6094 if (err)
6095 return err;
6096 if (view_needs_focus_indication(view))
6097 wstandout(view->window);
6098 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6099 if (tc)
6100 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6101 waddwstr(view->window, wline);
6102 while (width++ < view->ncols)
6103 waddch(view->window, ' ');
6104 if (tc)
6105 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6106 if (view_needs_focus_indication(view))
6107 wstandend(view->window);
6108 free(wline);
6109 wline = NULL;
6111 if (view->gline > blame->nlines)
6112 view->gline = blame->nlines;
6114 if (tog_io.wait_for_ui) {
6115 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6116 int rc;
6118 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6119 if (rc)
6120 return got_error_set_errno(rc, "pthread_cond_wait");
6121 tog_io.wait_for_ui = 0;
6124 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6125 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6126 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6127 free(id_str);
6128 return got_error_from_errno("asprintf");
6130 free(id_str);
6131 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6132 free(line);
6133 line = NULL;
6134 if (err)
6135 return err;
6136 waddwstr(view->window, wline);
6137 free(wline);
6138 wline = NULL;
6139 if (width < view->ncols - 1)
6140 waddch(view->window, '\n');
6142 s->eof = 0;
6143 view->maxx = 0;
6144 while (nprinted < view->nlines - 2) {
6145 linelen = getline(&line, &linesize, blame->f);
6146 if (linelen == -1) {
6147 if (feof(blame->f)) {
6148 s->eof = 1;
6149 break;
6151 free(line);
6152 return got_ferror(blame->f, GOT_ERR_IO);
6154 if (++lineno < s->first_displayed_line)
6155 continue;
6156 if (view->gline && !gotoline(view, &lineno, &nprinted))
6157 continue;
6159 /* Set view->maxx based on full line length. */
6160 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6161 if (err) {
6162 free(line);
6163 return err;
6165 free(wline);
6166 wline = NULL;
6167 view->maxx = MAX(view->maxx, width);
6169 if (nprinted == s->selected_line - 1)
6170 wstandout(view->window);
6172 if (blame->nlines > 0) {
6173 blame_line = &blame->lines[lineno - 1];
6174 if (blame_line->annotated && prev_id &&
6175 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6176 !(nprinted == s->selected_line - 1)) {
6177 waddstr(view->window, " ");
6178 } else if (blame_line->annotated) {
6179 char *id_str;
6180 err = got_object_id_str(&id_str,
6181 blame_line->id);
6182 if (err) {
6183 free(line);
6184 return err;
6186 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6187 if (tc)
6188 wattr_on(view->window,
6189 COLOR_PAIR(tc->colorpair), NULL);
6190 wprintw(view->window, "%.8s", id_str);
6191 if (tc)
6192 wattr_off(view->window,
6193 COLOR_PAIR(tc->colorpair), NULL);
6194 free(id_str);
6195 prev_id = blame_line->id;
6196 } else {
6197 waddstr(view->window, "........");
6198 prev_id = NULL;
6200 } else {
6201 waddstr(view->window, "........");
6202 prev_id = NULL;
6205 if (nprinted == s->selected_line - 1)
6206 wstandend(view->window);
6207 waddstr(view->window, " ");
6209 if (view->ncols <= 9) {
6210 width = 9;
6211 } else if (s->first_displayed_line + nprinted ==
6212 s->matched_line &&
6213 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6214 err = add_matched_line(&width, line, view->ncols - 9, 9,
6215 view->window, view->x, regmatch);
6216 if (err) {
6217 free(line);
6218 return err;
6220 width += 9;
6221 } else {
6222 int skip;
6223 err = format_line(&wline, &width, &skip, line,
6224 view->x, view->ncols - 9, 9, 1);
6225 if (err) {
6226 free(line);
6227 return err;
6229 waddwstr(view->window, &wline[skip]);
6230 width += 9;
6231 free(wline);
6232 wline = NULL;
6235 if (width <= view->ncols - 1)
6236 waddch(view->window, '\n');
6237 if (++nprinted == 1)
6238 s->first_displayed_line = lineno;
6240 free(line);
6241 s->last_displayed_line = lineno;
6243 view_border(view);
6245 return NULL;
6248 static const struct got_error *
6249 blame_cb(void *arg, int nlines, int lineno,
6250 struct got_commit_object *commit, struct got_object_id *id)
6252 const struct got_error *err = NULL;
6253 struct tog_blame_cb_args *a = arg;
6254 struct tog_blame_line *line;
6255 int errcode;
6257 if (nlines != a->nlines ||
6258 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6259 return got_error(GOT_ERR_RANGE);
6261 errcode = pthread_mutex_lock(&tog_mutex);
6262 if (errcode)
6263 return got_error_set_errno(errcode, "pthread_mutex_lock");
6265 if (*a->quit) { /* user has quit the blame view */
6266 err = got_error(GOT_ERR_ITER_COMPLETED);
6267 goto done;
6270 if (lineno == -1)
6271 goto done; /* no change in this commit */
6273 line = &a->lines[lineno - 1];
6274 if (line->annotated)
6275 goto done;
6277 line->id = got_object_id_dup(id);
6278 if (line->id == NULL) {
6279 err = got_error_from_errno("got_object_id_dup");
6280 goto done;
6282 line->annotated = 1;
6283 done:
6284 errcode = pthread_mutex_unlock(&tog_mutex);
6285 if (errcode)
6286 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6287 return err;
6290 static void *
6291 blame_thread(void *arg)
6293 const struct got_error *err, *close_err;
6294 struct tog_blame_thread_args *ta = arg;
6295 struct tog_blame_cb_args *a = ta->cb_args;
6296 int errcode, fd1 = -1, fd2 = -1;
6297 FILE *f1 = NULL, *f2 = NULL;
6299 fd1 = got_opentempfd();
6300 if (fd1 == -1)
6301 return (void *)got_error_from_errno("got_opentempfd");
6303 fd2 = got_opentempfd();
6304 if (fd2 == -1) {
6305 err = got_error_from_errno("got_opentempfd");
6306 goto done;
6309 f1 = got_opentemp();
6310 if (f1 == NULL) {
6311 err = (void *)got_error_from_errno("got_opentemp");
6312 goto done;
6314 f2 = got_opentemp();
6315 if (f2 == NULL) {
6316 err = (void *)got_error_from_errno("got_opentemp");
6317 goto done;
6320 err = block_signals_used_by_main_thread();
6321 if (err)
6322 goto done;
6324 err = got_blame(ta->path, a->commit_id, ta->repo,
6325 tog_diff_algo, blame_cb, ta->cb_args,
6326 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6327 if (err && err->code == GOT_ERR_CANCELLED)
6328 err = NULL;
6330 errcode = pthread_mutex_lock(&tog_mutex);
6331 if (errcode) {
6332 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6333 goto done;
6336 close_err = got_repo_close(ta->repo);
6337 if (err == NULL)
6338 err = close_err;
6339 ta->repo = NULL;
6340 *ta->complete = 1;
6342 if (tog_io.wait_for_ui) {
6343 errcode = pthread_cond_signal(&ta->blame_complete);
6344 if (errcode && err == NULL)
6345 err = got_error_set_errno(errcode,
6346 "pthread_cond_signal");
6349 errcode = pthread_mutex_unlock(&tog_mutex);
6350 if (errcode && err == NULL)
6351 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6353 done:
6354 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6355 err = got_error_from_errno("close");
6356 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6357 err = got_error_from_errno("close");
6358 if (f1 && fclose(f1) == EOF && err == NULL)
6359 err = got_error_from_errno("fclose");
6360 if (f2 && fclose(f2) == EOF && err == NULL)
6361 err = got_error_from_errno("fclose");
6363 return (void *)err;
6366 static struct got_object_id *
6367 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6368 int first_displayed_line, int selected_line)
6370 struct tog_blame_line *line;
6372 if (nlines <= 0)
6373 return NULL;
6375 line = &lines[first_displayed_line - 1 + selected_line - 1];
6376 if (!line->annotated)
6377 return NULL;
6379 return line->id;
6382 static struct got_object_id *
6383 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6384 int lineno)
6386 struct tog_blame_line *line;
6388 if (nlines <= 0 || lineno >= nlines)
6389 return NULL;
6391 line = &lines[lineno - 1];
6392 if (!line->annotated)
6393 return NULL;
6395 return line->id;
6398 static const struct got_error *
6399 stop_blame(struct tog_blame *blame)
6401 const struct got_error *err = NULL;
6402 int i;
6404 if (blame->thread) {
6405 int errcode;
6406 errcode = pthread_mutex_unlock(&tog_mutex);
6407 if (errcode)
6408 return got_error_set_errno(errcode,
6409 "pthread_mutex_unlock");
6410 errcode = pthread_join(blame->thread, (void **)&err);
6411 if (errcode)
6412 return got_error_set_errno(errcode, "pthread_join");
6413 errcode = pthread_mutex_lock(&tog_mutex);
6414 if (errcode)
6415 return got_error_set_errno(errcode,
6416 "pthread_mutex_lock");
6417 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6418 err = NULL;
6419 blame->thread = NULL;
6421 if (blame->thread_args.repo) {
6422 const struct got_error *close_err;
6423 close_err = got_repo_close(blame->thread_args.repo);
6424 if (err == NULL)
6425 err = close_err;
6426 blame->thread_args.repo = NULL;
6428 if (blame->f) {
6429 if (fclose(blame->f) == EOF && err == NULL)
6430 err = got_error_from_errno("fclose");
6431 blame->f = NULL;
6433 if (blame->lines) {
6434 for (i = 0; i < blame->nlines; i++)
6435 free(blame->lines[i].id);
6436 free(blame->lines);
6437 blame->lines = NULL;
6439 free(blame->cb_args.commit_id);
6440 blame->cb_args.commit_id = NULL;
6441 if (blame->pack_fds) {
6442 const struct got_error *pack_err =
6443 got_repo_pack_fds_close(blame->pack_fds);
6444 if (err == NULL)
6445 err = pack_err;
6446 blame->pack_fds = NULL;
6448 return err;
6451 static const struct got_error *
6452 cancel_blame_view(void *arg)
6454 const struct got_error *err = NULL;
6455 int *done = arg;
6456 int errcode;
6458 errcode = pthread_mutex_lock(&tog_mutex);
6459 if (errcode)
6460 return got_error_set_errno(errcode,
6461 "pthread_mutex_unlock");
6463 if (*done)
6464 err = got_error(GOT_ERR_CANCELLED);
6466 errcode = pthread_mutex_unlock(&tog_mutex);
6467 if (errcode)
6468 return got_error_set_errno(errcode,
6469 "pthread_mutex_lock");
6471 return err;
6474 static const struct got_error *
6475 run_blame(struct tog_view *view)
6477 struct tog_blame_view_state *s = &view->state.blame;
6478 struct tog_blame *blame = &s->blame;
6479 const struct got_error *err = NULL;
6480 struct got_commit_object *commit = NULL;
6481 struct got_blob_object *blob = NULL;
6482 struct got_repository *thread_repo = NULL;
6483 struct got_object_id *obj_id = NULL;
6484 int obj_type, fd = -1;
6485 int *pack_fds = NULL;
6487 err = got_object_open_as_commit(&commit, s->repo,
6488 &s->blamed_commit->id);
6489 if (err)
6490 return err;
6492 fd = got_opentempfd();
6493 if (fd == -1) {
6494 err = got_error_from_errno("got_opentempfd");
6495 goto done;
6498 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6499 if (err)
6500 goto done;
6502 err = got_object_get_type(&obj_type, s->repo, obj_id);
6503 if (err)
6504 goto done;
6506 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6507 err = got_error(GOT_ERR_OBJ_TYPE);
6508 goto done;
6511 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6512 if (err)
6513 goto done;
6514 blame->f = got_opentemp();
6515 if (blame->f == NULL) {
6516 err = got_error_from_errno("got_opentemp");
6517 goto done;
6519 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6520 &blame->line_offsets, blame->f, blob);
6521 if (err)
6522 goto done;
6523 if (blame->nlines == 0) {
6524 s->blame_complete = 1;
6525 goto done;
6528 /* Don't include \n at EOF in the blame line count. */
6529 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6530 blame->nlines--;
6532 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6533 if (blame->lines == NULL) {
6534 err = got_error_from_errno("calloc");
6535 goto done;
6538 err = got_repo_pack_fds_open(&pack_fds);
6539 if (err)
6540 goto done;
6541 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6542 pack_fds);
6543 if (err)
6544 goto done;
6546 blame->pack_fds = pack_fds;
6547 blame->cb_args.view = view;
6548 blame->cb_args.lines = blame->lines;
6549 blame->cb_args.nlines = blame->nlines;
6550 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6551 if (blame->cb_args.commit_id == NULL) {
6552 err = got_error_from_errno("got_object_id_dup");
6553 goto done;
6555 blame->cb_args.quit = &s->done;
6557 blame->thread_args.path = s->path;
6558 blame->thread_args.repo = thread_repo;
6559 blame->thread_args.cb_args = &blame->cb_args;
6560 blame->thread_args.complete = &s->blame_complete;
6561 blame->thread_args.cancel_cb = cancel_blame_view;
6562 blame->thread_args.cancel_arg = &s->done;
6563 s->blame_complete = 0;
6565 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6566 s->first_displayed_line = 1;
6567 s->last_displayed_line = view->nlines;
6568 s->selected_line = 1;
6570 s->matched_line = 0;
6572 done:
6573 if (commit)
6574 got_object_commit_close(commit);
6575 if (fd != -1 && close(fd) == -1 && err == NULL)
6576 err = got_error_from_errno("close");
6577 if (blob)
6578 got_object_blob_close(blob);
6579 free(obj_id);
6580 if (err)
6581 stop_blame(blame);
6582 return err;
6585 static const struct got_error *
6586 open_blame_view(struct tog_view *view, char *path,
6587 struct got_object_id *commit_id, struct got_repository *repo)
6589 const struct got_error *err = NULL;
6590 struct tog_blame_view_state *s = &view->state.blame;
6592 STAILQ_INIT(&s->blamed_commits);
6594 s->path = strdup(path);
6595 if (s->path == NULL)
6596 return got_error_from_errno("strdup");
6598 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6599 if (err) {
6600 free(s->path);
6601 return err;
6604 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6605 s->first_displayed_line = 1;
6606 s->last_displayed_line = view->nlines;
6607 s->selected_line = 1;
6608 s->blame_complete = 0;
6609 s->repo = repo;
6610 s->commit_id = commit_id;
6611 memset(&s->blame, 0, sizeof(s->blame));
6613 STAILQ_INIT(&s->colors);
6614 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6615 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6616 get_color_value("TOG_COLOR_COMMIT"));
6617 if (err)
6618 return err;
6621 view->show = show_blame_view;
6622 view->input = input_blame_view;
6623 view->reset = reset_blame_view;
6624 view->close = close_blame_view;
6625 view->search_start = search_start_blame_view;
6626 view->search_setup = search_setup_blame_view;
6627 view->search_next = search_next_view_match;
6629 if (using_mock_io) {
6630 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6631 int rc;
6633 rc = pthread_cond_init(&bta->blame_complete, NULL);
6634 if (rc)
6635 return got_error_set_errno(rc, "pthread_cond_init");
6638 return run_blame(view);
6641 static const struct got_error *
6642 close_blame_view(struct tog_view *view)
6644 const struct got_error *err = NULL;
6645 struct tog_blame_view_state *s = &view->state.blame;
6647 if (s->blame.thread)
6648 err = stop_blame(&s->blame);
6650 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6651 struct got_object_qid *blamed_commit;
6652 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6653 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6654 got_object_qid_free(blamed_commit);
6657 if (using_mock_io) {
6658 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6659 int rc;
6661 rc = pthread_cond_destroy(&bta->blame_complete);
6662 if (rc && err == NULL)
6663 err = got_error_set_errno(rc, "pthread_cond_destroy");
6666 free(s->path);
6667 free_colors(&s->colors);
6668 return err;
6671 static const struct got_error *
6672 search_start_blame_view(struct tog_view *view)
6674 struct tog_blame_view_state *s = &view->state.blame;
6676 s->matched_line = 0;
6677 return NULL;
6680 static void
6681 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6682 size_t *nlines, int **first, int **last, int **match, int **selected)
6684 struct tog_blame_view_state *s = &view->state.blame;
6686 *f = s->blame.f;
6687 *nlines = s->blame.nlines;
6688 *line_offsets = s->blame.line_offsets;
6689 *match = &s->matched_line;
6690 *first = &s->first_displayed_line;
6691 *last = &s->last_displayed_line;
6692 *selected = &s->selected_line;
6695 static const struct got_error *
6696 show_blame_view(struct tog_view *view)
6698 const struct got_error *err = NULL;
6699 struct tog_blame_view_state *s = &view->state.blame;
6700 int errcode;
6702 if (s->blame.thread == NULL && !s->blame_complete) {
6703 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6704 &s->blame.thread_args);
6705 if (errcode)
6706 return got_error_set_errno(errcode, "pthread_create");
6708 if (!using_mock_io)
6709 halfdelay(1); /* fast refresh while annotating */
6712 if (s->blame_complete && !using_mock_io)
6713 halfdelay(10); /* disable fast refresh */
6715 err = draw_blame(view);
6717 view_border(view);
6718 return err;
6721 static const struct got_error *
6722 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6723 struct got_repository *repo, struct got_object_id *id)
6725 struct tog_view *log_view;
6726 const struct got_error *err = NULL;
6728 *new_view = NULL;
6730 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6731 if (log_view == NULL)
6732 return got_error_from_errno("view_open");
6734 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6735 if (err)
6736 view_close(log_view);
6737 else
6738 *new_view = log_view;
6740 return err;
6743 static const struct got_error *
6744 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6746 const struct got_error *err = NULL, *thread_err = NULL;
6747 struct tog_view *diff_view;
6748 struct tog_blame_view_state *s = &view->state.blame;
6749 int eos, nscroll, begin_y = 0, begin_x = 0;
6751 eos = nscroll = view->nlines - 2;
6752 if (view_is_hsplit_top(view))
6753 --eos; /* border */
6755 switch (ch) {
6756 case '0':
6757 case '$':
6758 case KEY_RIGHT:
6759 case 'l':
6760 case KEY_LEFT:
6761 case 'h':
6762 horizontal_scroll_input(view, ch);
6763 break;
6764 case 'q':
6765 s->done = 1;
6766 break;
6767 case 'g':
6768 case KEY_HOME:
6769 s->selected_line = 1;
6770 s->first_displayed_line = 1;
6771 view->count = 0;
6772 break;
6773 case 'G':
6774 case KEY_END:
6775 if (s->blame.nlines < eos) {
6776 s->selected_line = s->blame.nlines;
6777 s->first_displayed_line = 1;
6778 } else {
6779 s->selected_line = eos;
6780 s->first_displayed_line = s->blame.nlines - (eos - 1);
6782 view->count = 0;
6783 break;
6784 case 'k':
6785 case KEY_UP:
6786 case CTRL('p'):
6787 if (s->selected_line > 1)
6788 s->selected_line--;
6789 else if (s->selected_line == 1 &&
6790 s->first_displayed_line > 1)
6791 s->first_displayed_line--;
6792 else
6793 view->count = 0;
6794 break;
6795 case CTRL('u'):
6796 case 'u':
6797 nscroll /= 2;
6798 /* FALL THROUGH */
6799 case KEY_PPAGE:
6800 case CTRL('b'):
6801 case 'b':
6802 if (s->first_displayed_line == 1) {
6803 if (view->count > 1)
6804 nscroll += nscroll;
6805 s->selected_line = MAX(1, s->selected_line - nscroll);
6806 view->count = 0;
6807 break;
6809 if (s->first_displayed_line > nscroll)
6810 s->first_displayed_line -= nscroll;
6811 else
6812 s->first_displayed_line = 1;
6813 break;
6814 case 'j':
6815 case KEY_DOWN:
6816 case CTRL('n'):
6817 if (s->selected_line < eos && s->first_displayed_line +
6818 s->selected_line <= s->blame.nlines)
6819 s->selected_line++;
6820 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6821 s->first_displayed_line++;
6822 else
6823 view->count = 0;
6824 break;
6825 case 'c':
6826 case 'p': {
6827 struct got_object_id *id = NULL;
6829 view->count = 0;
6830 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6831 s->first_displayed_line, s->selected_line);
6832 if (id == NULL)
6833 break;
6834 if (ch == 'p') {
6835 struct got_commit_object *commit, *pcommit;
6836 struct got_object_qid *pid;
6837 struct got_object_id *blob_id = NULL;
6838 int obj_type;
6839 err = got_object_open_as_commit(&commit,
6840 s->repo, id);
6841 if (err)
6842 break;
6843 pid = STAILQ_FIRST(
6844 got_object_commit_get_parent_ids(commit));
6845 if (pid == NULL) {
6846 got_object_commit_close(commit);
6847 break;
6849 /* Check if path history ends here. */
6850 err = got_object_open_as_commit(&pcommit,
6851 s->repo, &pid->id);
6852 if (err)
6853 break;
6854 err = got_object_id_by_path(&blob_id, s->repo,
6855 pcommit, s->path);
6856 got_object_commit_close(pcommit);
6857 if (err) {
6858 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6859 err = NULL;
6860 got_object_commit_close(commit);
6861 break;
6863 err = got_object_get_type(&obj_type, s->repo,
6864 blob_id);
6865 free(blob_id);
6866 /* Can't blame non-blob type objects. */
6867 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6868 got_object_commit_close(commit);
6869 break;
6871 err = got_object_qid_alloc(&s->blamed_commit,
6872 &pid->id);
6873 got_object_commit_close(commit);
6874 } else {
6875 if (got_object_id_cmp(id,
6876 &s->blamed_commit->id) == 0)
6877 break;
6878 err = got_object_qid_alloc(&s->blamed_commit,
6879 id);
6881 if (err)
6882 break;
6883 s->done = 1;
6884 thread_err = stop_blame(&s->blame);
6885 s->done = 0;
6886 if (thread_err)
6887 break;
6888 STAILQ_INSERT_HEAD(&s->blamed_commits,
6889 s->blamed_commit, entry);
6890 err = run_blame(view);
6891 if (err)
6892 break;
6893 break;
6895 case 'C': {
6896 struct got_object_qid *first;
6898 view->count = 0;
6899 first = STAILQ_FIRST(&s->blamed_commits);
6900 if (!got_object_id_cmp(&first->id, s->commit_id))
6901 break;
6902 s->done = 1;
6903 thread_err = stop_blame(&s->blame);
6904 s->done = 0;
6905 if (thread_err)
6906 break;
6907 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6908 got_object_qid_free(s->blamed_commit);
6909 s->blamed_commit =
6910 STAILQ_FIRST(&s->blamed_commits);
6911 err = run_blame(view);
6912 if (err)
6913 break;
6914 break;
6916 case 'L':
6917 view->count = 0;
6918 s->id_to_log = get_selected_commit_id(s->blame.lines,
6919 s->blame.nlines, s->first_displayed_line, s->selected_line);
6920 if (s->id_to_log)
6921 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6922 break;
6923 case KEY_ENTER:
6924 case '\r': {
6925 struct got_object_id *id = NULL;
6926 struct got_object_qid *pid;
6927 struct got_commit_object *commit = NULL;
6929 view->count = 0;
6930 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6931 s->first_displayed_line, s->selected_line);
6932 if (id == NULL)
6933 break;
6934 err = got_object_open_as_commit(&commit, s->repo, id);
6935 if (err)
6936 break;
6937 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6938 if (*new_view) {
6939 /* traversed from diff view, release diff resources */
6940 err = close_diff_view(*new_view);
6941 if (err)
6942 break;
6943 diff_view = *new_view;
6944 } else {
6945 if (view_is_parent_view(view))
6946 view_get_split(view, &begin_y, &begin_x);
6948 diff_view = view_open(0, 0, begin_y, begin_x,
6949 TOG_VIEW_DIFF);
6950 if (diff_view == NULL) {
6951 got_object_commit_close(commit);
6952 err = got_error_from_errno("view_open");
6953 break;
6956 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6957 id, NULL, NULL, 3, 0, 0, view, s->repo);
6958 got_object_commit_close(commit);
6959 if (err) {
6960 view_close(diff_view);
6961 break;
6963 s->last_diffed_line = s->first_displayed_line - 1 +
6964 s->selected_line;
6965 if (*new_view)
6966 break; /* still open from active diff view */
6967 if (view_is_parent_view(view) &&
6968 view->mode == TOG_VIEW_SPLIT_HRZN) {
6969 err = view_init_hsplit(view, begin_y);
6970 if (err)
6971 break;
6974 view->focussed = 0;
6975 diff_view->focussed = 1;
6976 diff_view->mode = view->mode;
6977 diff_view->nlines = view->lines - begin_y;
6978 if (view_is_parent_view(view)) {
6979 view_transfer_size(diff_view, view);
6980 err = view_close_child(view);
6981 if (err)
6982 break;
6983 err = view_set_child(view, diff_view);
6984 if (err)
6985 break;
6986 view->focus_child = 1;
6987 } else
6988 *new_view = diff_view;
6989 if (err)
6990 break;
6991 break;
6993 case CTRL('d'):
6994 case 'd':
6995 nscroll /= 2;
6996 /* FALL THROUGH */
6997 case KEY_NPAGE:
6998 case CTRL('f'):
6999 case 'f':
7000 case ' ':
7001 if (s->last_displayed_line >= s->blame.nlines &&
7002 s->selected_line >= MIN(s->blame.nlines,
7003 view->nlines - 2)) {
7004 view->count = 0;
7005 break;
7007 if (s->last_displayed_line >= s->blame.nlines &&
7008 s->selected_line < view->nlines - 2) {
7009 s->selected_line +=
7010 MIN(nscroll, s->last_displayed_line -
7011 s->first_displayed_line - s->selected_line + 1);
7013 if (s->last_displayed_line + nscroll <= s->blame.nlines)
7014 s->first_displayed_line += nscroll;
7015 else
7016 s->first_displayed_line =
7017 s->blame.nlines - (view->nlines - 3);
7018 break;
7019 case KEY_RESIZE:
7020 if (s->selected_line > view->nlines - 2) {
7021 s->selected_line = MIN(s->blame.nlines,
7022 view->nlines - 2);
7024 break;
7025 default:
7026 view->count = 0;
7027 break;
7029 return thread_err ? thread_err : err;
7032 static const struct got_error *
7033 reset_blame_view(struct tog_view *view)
7035 const struct got_error *err;
7036 struct tog_blame_view_state *s = &view->state.blame;
7038 view->count = 0;
7039 s->done = 1;
7040 err = stop_blame(&s->blame);
7041 s->done = 0;
7042 if (err)
7043 return err;
7044 return run_blame(view);
7047 static const struct got_error *
7048 cmd_blame(int argc, char *argv[])
7050 const struct got_error *error;
7051 struct got_repository *repo = NULL;
7052 struct got_worktree *worktree = NULL;
7053 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7054 char *link_target = NULL;
7055 struct got_object_id *commit_id = NULL;
7056 struct got_commit_object *commit = NULL;
7057 char *commit_id_str = NULL;
7058 int ch;
7059 struct tog_view *view = NULL;
7060 int *pack_fds = NULL;
7062 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7063 switch (ch) {
7064 case 'c':
7065 commit_id_str = optarg;
7066 break;
7067 case 'r':
7068 repo_path = realpath(optarg, NULL);
7069 if (repo_path == NULL)
7070 return got_error_from_errno2("realpath",
7071 optarg);
7072 break;
7073 default:
7074 usage_blame();
7075 /* NOTREACHED */
7079 argc -= optind;
7080 argv += optind;
7082 if (argc != 1)
7083 usage_blame();
7085 error = got_repo_pack_fds_open(&pack_fds);
7086 if (error != NULL)
7087 goto done;
7089 if (repo_path == NULL) {
7090 cwd = getcwd(NULL, 0);
7091 if (cwd == NULL)
7092 return got_error_from_errno("getcwd");
7093 error = got_worktree_open(&worktree, cwd);
7094 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7095 goto done;
7096 if (worktree)
7097 repo_path =
7098 strdup(got_worktree_get_repo_path(worktree));
7099 else
7100 repo_path = strdup(cwd);
7101 if (repo_path == NULL) {
7102 error = got_error_from_errno("strdup");
7103 goto done;
7107 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7108 if (error != NULL)
7109 goto done;
7111 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7112 worktree);
7113 if (error)
7114 goto done;
7116 init_curses();
7118 error = apply_unveil(got_repo_get_path(repo), NULL);
7119 if (error)
7120 goto done;
7122 error = tog_load_refs(repo, 0);
7123 if (error)
7124 goto done;
7126 if (commit_id_str == NULL) {
7127 struct got_reference *head_ref;
7128 error = got_ref_open(&head_ref, repo, worktree ?
7129 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7130 if (error != NULL)
7131 goto done;
7132 error = got_ref_resolve(&commit_id, repo, head_ref);
7133 got_ref_close(head_ref);
7134 } else {
7135 error = got_repo_match_object_id(&commit_id, NULL,
7136 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7138 if (error != NULL)
7139 goto done;
7141 error = got_object_open_as_commit(&commit, repo, commit_id);
7142 if (error)
7143 goto done;
7145 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7146 commit, repo);
7147 if (error)
7148 goto done;
7150 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7151 if (view == NULL) {
7152 error = got_error_from_errno("view_open");
7153 goto done;
7155 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7156 commit_id, repo);
7157 if (error != NULL) {
7158 if (view->close == NULL)
7159 close_blame_view(view);
7160 view_close(view);
7161 goto done;
7163 if (worktree) {
7164 /* Release work tree lock. */
7165 got_worktree_close(worktree);
7166 worktree = NULL;
7168 error = view_loop(view);
7169 done:
7170 free(repo_path);
7171 free(in_repo_path);
7172 free(link_target);
7173 free(cwd);
7174 free(commit_id);
7175 if (commit)
7176 got_object_commit_close(commit);
7177 if (worktree)
7178 got_worktree_close(worktree);
7179 if (repo) {
7180 const struct got_error *close_err = got_repo_close(repo);
7181 if (error == NULL)
7182 error = close_err;
7184 if (pack_fds) {
7185 const struct got_error *pack_err =
7186 got_repo_pack_fds_close(pack_fds);
7187 if (error == NULL)
7188 error = pack_err;
7190 tog_free_refs();
7191 return error;
7194 static const struct got_error *
7195 draw_tree_entries(struct tog_view *view, const char *parent_path)
7197 struct tog_tree_view_state *s = &view->state.tree;
7198 const struct got_error *err = NULL;
7199 struct got_tree_entry *te;
7200 wchar_t *wline;
7201 char *index = NULL;
7202 struct tog_color *tc;
7203 int width, n, nentries, scrollx, i = 1;
7204 int limit = view->nlines;
7206 s->ndisplayed = 0;
7207 if (view_is_hsplit_top(view))
7208 --limit; /* border */
7210 werase(view->window);
7212 if (limit == 0)
7213 return NULL;
7215 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7216 0, 0);
7217 if (err)
7218 return err;
7219 if (view_needs_focus_indication(view))
7220 wstandout(view->window);
7221 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7222 if (tc)
7223 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7224 waddwstr(view->window, wline);
7225 free(wline);
7226 wline = NULL;
7227 while (width++ < view->ncols)
7228 waddch(view->window, ' ');
7229 if (tc)
7230 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7231 if (view_needs_focus_indication(view))
7232 wstandend(view->window);
7233 if (--limit <= 0)
7234 return NULL;
7236 i += s->selected;
7237 if (s->first_displayed_entry) {
7238 i += got_tree_entry_get_index(s->first_displayed_entry);
7239 if (s->tree != s->root)
7240 ++i; /* account for ".." entry */
7242 nentries = got_object_tree_get_nentries(s->tree);
7243 if (asprintf(&index, "[%d/%d] %s",
7244 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7245 return got_error_from_errno("asprintf");
7246 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7247 free(index);
7248 if (err)
7249 return err;
7250 waddwstr(view->window, wline);
7251 free(wline);
7252 wline = NULL;
7253 if (width < view->ncols - 1)
7254 waddch(view->window, '\n');
7255 if (--limit <= 0)
7256 return NULL;
7257 waddch(view->window, '\n');
7258 if (--limit <= 0)
7259 return NULL;
7261 if (s->first_displayed_entry == NULL) {
7262 te = got_object_tree_get_first_entry(s->tree);
7263 if (s->selected == 0) {
7264 if (view->focussed)
7265 wstandout(view->window);
7266 s->selected_entry = NULL;
7268 waddstr(view->window, " ..\n"); /* parent directory */
7269 if (s->selected == 0 && view->focussed)
7270 wstandend(view->window);
7271 s->ndisplayed++;
7272 if (--limit <= 0)
7273 return NULL;
7274 n = 1;
7275 } else {
7276 n = 0;
7277 te = s->first_displayed_entry;
7280 view->maxx = 0;
7281 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7282 char *line = NULL, *id_str = NULL, *link_target = NULL;
7283 const char *modestr = "";
7284 mode_t mode;
7286 te = got_object_tree_get_entry(s->tree, i);
7287 mode = got_tree_entry_get_mode(te);
7289 if (s->show_ids) {
7290 err = got_object_id_str(&id_str,
7291 got_tree_entry_get_id(te));
7292 if (err)
7293 return got_error_from_errno(
7294 "got_object_id_str");
7296 if (got_object_tree_entry_is_submodule(te))
7297 modestr = "$";
7298 else if (S_ISLNK(mode)) {
7299 int i;
7301 err = got_tree_entry_get_symlink_target(&link_target,
7302 te, s->repo);
7303 if (err) {
7304 free(id_str);
7305 return err;
7307 for (i = 0; i < strlen(link_target); i++) {
7308 if (!isprint((unsigned char)link_target[i]))
7309 link_target[i] = '?';
7311 modestr = "@";
7313 else if (S_ISDIR(mode))
7314 modestr = "/";
7315 else if (mode & S_IXUSR)
7316 modestr = "*";
7317 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7318 got_tree_entry_get_name(te), modestr,
7319 link_target ? " -> ": "",
7320 link_target ? link_target : "") == -1) {
7321 free(id_str);
7322 free(link_target);
7323 return got_error_from_errno("asprintf");
7325 free(id_str);
7326 free(link_target);
7328 /* use full line width to determine view->maxx */
7329 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7330 if (err) {
7331 free(line);
7332 break;
7334 view->maxx = MAX(view->maxx, width);
7335 free(wline);
7336 wline = NULL;
7338 err = format_line(&wline, &width, &scrollx, line, view->x,
7339 view->ncols, 0, 0);
7340 if (err) {
7341 free(line);
7342 break;
7344 if (n == s->selected) {
7345 if (view->focussed)
7346 wstandout(view->window);
7347 s->selected_entry = te;
7349 tc = match_color(&s->colors, line);
7350 if (tc)
7351 wattr_on(view->window,
7352 COLOR_PAIR(tc->colorpair), NULL);
7353 waddwstr(view->window, &wline[scrollx]);
7354 if (tc)
7355 wattr_off(view->window,
7356 COLOR_PAIR(tc->colorpair), NULL);
7357 if (width < view->ncols)
7358 waddch(view->window, '\n');
7359 if (n == s->selected && view->focussed)
7360 wstandend(view->window);
7361 free(line);
7362 free(wline);
7363 wline = NULL;
7364 n++;
7365 s->ndisplayed++;
7366 s->last_displayed_entry = te;
7367 if (--limit <= 0)
7368 break;
7371 return err;
7374 static void
7375 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7377 struct got_tree_entry *te;
7378 int isroot = s->tree == s->root;
7379 int i = 0;
7381 if (s->first_displayed_entry == NULL)
7382 return;
7384 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7385 while (i++ < maxscroll) {
7386 if (te == NULL) {
7387 if (!isroot)
7388 s->first_displayed_entry = NULL;
7389 break;
7391 s->first_displayed_entry = te;
7392 te = got_tree_entry_get_prev(s->tree, te);
7396 static const struct got_error *
7397 tree_scroll_down(struct tog_view *view, int maxscroll)
7399 struct tog_tree_view_state *s = &view->state.tree;
7400 struct got_tree_entry *next, *last;
7401 int n = 0;
7403 if (s->first_displayed_entry)
7404 next = got_tree_entry_get_next(s->tree,
7405 s->first_displayed_entry);
7406 else
7407 next = got_object_tree_get_first_entry(s->tree);
7409 last = s->last_displayed_entry;
7410 while (next && n++ < maxscroll) {
7411 if (last) {
7412 s->last_displayed_entry = last;
7413 last = got_tree_entry_get_next(s->tree, last);
7415 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7416 s->first_displayed_entry = next;
7417 next = got_tree_entry_get_next(s->tree, next);
7421 return NULL;
7424 static const struct got_error *
7425 tree_entry_path(char **path, struct tog_parent_trees *parents,
7426 struct got_tree_entry *te)
7428 const struct got_error *err = NULL;
7429 struct tog_parent_tree *pt;
7430 size_t len = 2; /* for leading slash and NUL */
7432 TAILQ_FOREACH(pt, parents, entry)
7433 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7434 + 1 /* slash */;
7435 if (te)
7436 len += strlen(got_tree_entry_get_name(te));
7438 *path = calloc(1, len);
7439 if (path == NULL)
7440 return got_error_from_errno("calloc");
7442 (*path)[0] = '/';
7443 pt = TAILQ_LAST(parents, tog_parent_trees);
7444 while (pt) {
7445 const char *name = got_tree_entry_get_name(pt->selected_entry);
7446 if (strlcat(*path, name, len) >= len) {
7447 err = got_error(GOT_ERR_NO_SPACE);
7448 goto done;
7450 if (strlcat(*path, "/", len) >= len) {
7451 err = got_error(GOT_ERR_NO_SPACE);
7452 goto done;
7454 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7456 if (te) {
7457 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7458 err = got_error(GOT_ERR_NO_SPACE);
7459 goto done;
7462 done:
7463 if (err) {
7464 free(*path);
7465 *path = NULL;
7467 return err;
7470 static const struct got_error *
7471 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7472 struct got_tree_entry *te, struct tog_parent_trees *parents,
7473 struct got_object_id *commit_id, struct got_repository *repo)
7475 const struct got_error *err = NULL;
7476 char *path;
7477 struct tog_view *blame_view;
7479 *new_view = NULL;
7481 err = tree_entry_path(&path, parents, te);
7482 if (err)
7483 return err;
7485 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7486 if (blame_view == NULL) {
7487 err = got_error_from_errno("view_open");
7488 goto done;
7491 err = open_blame_view(blame_view, path, commit_id, repo);
7492 if (err) {
7493 if (err->code == GOT_ERR_CANCELLED)
7494 err = NULL;
7495 view_close(blame_view);
7496 } else
7497 *new_view = blame_view;
7498 done:
7499 free(path);
7500 return err;
7503 static const struct got_error *
7504 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7505 struct tog_tree_view_state *s)
7507 struct tog_view *log_view;
7508 const struct got_error *err = NULL;
7509 char *path;
7511 *new_view = NULL;
7513 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7514 if (log_view == NULL)
7515 return got_error_from_errno("view_open");
7517 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7518 if (err)
7519 return err;
7521 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7522 path, 0);
7523 if (err)
7524 view_close(log_view);
7525 else
7526 *new_view = log_view;
7527 free(path);
7528 return err;
7531 static const struct got_error *
7532 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7533 const char *head_ref_name, struct got_repository *repo)
7535 const struct got_error *err = NULL;
7536 char *commit_id_str = NULL;
7537 struct tog_tree_view_state *s = &view->state.tree;
7538 struct got_commit_object *commit = NULL;
7540 TAILQ_INIT(&s->parents);
7541 STAILQ_INIT(&s->colors);
7543 s->commit_id = got_object_id_dup(commit_id);
7544 if (s->commit_id == NULL) {
7545 err = got_error_from_errno("got_object_id_dup");
7546 goto done;
7549 err = got_object_open_as_commit(&commit, repo, commit_id);
7550 if (err)
7551 goto done;
7554 * The root is opened here and will be closed when the view is closed.
7555 * Any visited subtrees and their path-wise parents are opened and
7556 * closed on demand.
7558 err = got_object_open_as_tree(&s->root, repo,
7559 got_object_commit_get_tree_id(commit));
7560 if (err)
7561 goto done;
7562 s->tree = s->root;
7564 err = got_object_id_str(&commit_id_str, commit_id);
7565 if (err != NULL)
7566 goto done;
7568 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7569 err = got_error_from_errno("asprintf");
7570 goto done;
7573 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7574 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7575 if (head_ref_name) {
7576 s->head_ref_name = strdup(head_ref_name);
7577 if (s->head_ref_name == NULL) {
7578 err = got_error_from_errno("strdup");
7579 goto done;
7582 s->repo = repo;
7584 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7585 err = add_color(&s->colors, "\\$$",
7586 TOG_COLOR_TREE_SUBMODULE,
7587 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7588 if (err)
7589 goto done;
7590 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7591 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7592 if (err)
7593 goto done;
7594 err = add_color(&s->colors, "/$",
7595 TOG_COLOR_TREE_DIRECTORY,
7596 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7597 if (err)
7598 goto done;
7600 err = add_color(&s->colors, "\\*$",
7601 TOG_COLOR_TREE_EXECUTABLE,
7602 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7603 if (err)
7604 goto done;
7606 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7607 get_color_value("TOG_COLOR_COMMIT"));
7608 if (err)
7609 goto done;
7612 view->show = show_tree_view;
7613 view->input = input_tree_view;
7614 view->close = close_tree_view;
7615 view->search_start = search_start_tree_view;
7616 view->search_next = search_next_tree_view;
7617 done:
7618 free(commit_id_str);
7619 if (commit)
7620 got_object_commit_close(commit);
7621 if (err) {
7622 if (view->close == NULL)
7623 close_tree_view(view);
7624 view_close(view);
7626 return err;
7629 static const struct got_error *
7630 close_tree_view(struct tog_view *view)
7632 struct tog_tree_view_state *s = &view->state.tree;
7634 free_colors(&s->colors);
7635 free(s->tree_label);
7636 s->tree_label = NULL;
7637 free(s->commit_id);
7638 s->commit_id = NULL;
7639 free(s->head_ref_name);
7640 s->head_ref_name = NULL;
7641 while (!TAILQ_EMPTY(&s->parents)) {
7642 struct tog_parent_tree *parent;
7643 parent = TAILQ_FIRST(&s->parents);
7644 TAILQ_REMOVE(&s->parents, parent, entry);
7645 if (parent->tree != s->root)
7646 got_object_tree_close(parent->tree);
7647 free(parent);
7650 if (s->tree != NULL && s->tree != s->root)
7651 got_object_tree_close(s->tree);
7652 if (s->root)
7653 got_object_tree_close(s->root);
7654 return NULL;
7657 static const struct got_error *
7658 search_start_tree_view(struct tog_view *view)
7660 struct tog_tree_view_state *s = &view->state.tree;
7662 s->matched_entry = NULL;
7663 return NULL;
7666 static int
7667 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7669 regmatch_t regmatch;
7671 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7672 0) == 0;
7675 static const struct got_error *
7676 search_next_tree_view(struct tog_view *view)
7678 struct tog_tree_view_state *s = &view->state.tree;
7679 struct got_tree_entry *te = NULL;
7681 if (!view->searching) {
7682 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7683 return NULL;
7686 if (s->matched_entry) {
7687 if (view->searching == TOG_SEARCH_FORWARD) {
7688 if (s->selected_entry)
7689 te = got_tree_entry_get_next(s->tree,
7690 s->selected_entry);
7691 else
7692 te = got_object_tree_get_first_entry(s->tree);
7693 } else {
7694 if (s->selected_entry == NULL)
7695 te = got_object_tree_get_last_entry(s->tree);
7696 else
7697 te = got_tree_entry_get_prev(s->tree,
7698 s->selected_entry);
7700 } else {
7701 if (s->selected_entry)
7702 te = s->selected_entry;
7703 else if (view->searching == TOG_SEARCH_FORWARD)
7704 te = got_object_tree_get_first_entry(s->tree);
7705 else
7706 te = got_object_tree_get_last_entry(s->tree);
7709 while (1) {
7710 if (te == NULL) {
7711 if (s->matched_entry == NULL) {
7712 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7713 return NULL;
7715 if (view->searching == TOG_SEARCH_FORWARD)
7716 te = got_object_tree_get_first_entry(s->tree);
7717 else
7718 te = got_object_tree_get_last_entry(s->tree);
7721 if (match_tree_entry(te, &view->regex)) {
7722 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7723 s->matched_entry = te;
7724 break;
7727 if (view->searching == TOG_SEARCH_FORWARD)
7728 te = got_tree_entry_get_next(s->tree, te);
7729 else
7730 te = got_tree_entry_get_prev(s->tree, te);
7733 if (s->matched_entry) {
7734 s->first_displayed_entry = s->matched_entry;
7735 s->selected = 0;
7738 return NULL;
7741 static const struct got_error *
7742 show_tree_view(struct tog_view *view)
7744 const struct got_error *err = NULL;
7745 struct tog_tree_view_state *s = &view->state.tree;
7746 char *parent_path;
7748 err = tree_entry_path(&parent_path, &s->parents, NULL);
7749 if (err)
7750 return err;
7752 err = draw_tree_entries(view, parent_path);
7753 free(parent_path);
7755 view_border(view);
7756 return err;
7759 static const struct got_error *
7760 tree_goto_line(struct tog_view *view, int nlines)
7762 const struct got_error *err = NULL;
7763 struct tog_tree_view_state *s = &view->state.tree;
7764 struct got_tree_entry **fte, **lte, **ste;
7765 int g, last, first = 1, i = 1;
7766 int root = s->tree == s->root;
7767 int off = root ? 1 : 2;
7769 g = view->gline;
7770 view->gline = 0;
7772 if (g == 0)
7773 g = 1;
7774 else if (g > got_object_tree_get_nentries(s->tree))
7775 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7777 fte = &s->first_displayed_entry;
7778 lte = &s->last_displayed_entry;
7779 ste = &s->selected_entry;
7781 if (*fte != NULL) {
7782 first = got_tree_entry_get_index(*fte);
7783 first += off; /* account for ".." */
7785 last = got_tree_entry_get_index(*lte);
7786 last += off;
7788 if (g >= first && g <= last && g - first < nlines) {
7789 s->selected = g - first;
7790 return NULL; /* gline is on the current page */
7793 if (*ste != NULL) {
7794 i = got_tree_entry_get_index(*ste);
7795 i += off;
7798 if (i < g) {
7799 err = tree_scroll_down(view, g - i);
7800 if (err)
7801 return err;
7802 if (got_tree_entry_get_index(*lte) >=
7803 got_object_tree_get_nentries(s->tree) - 1 &&
7804 first + s->selected < g &&
7805 s->selected < s->ndisplayed - 1) {
7806 first = got_tree_entry_get_index(*fte);
7807 first += off;
7808 s->selected = g - first;
7810 } else if (i > g)
7811 tree_scroll_up(s, i - g);
7813 if (g < nlines &&
7814 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7815 s->selected = g - 1;
7817 return NULL;
7820 static const struct got_error *
7821 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7823 const struct got_error *err = NULL;
7824 struct tog_tree_view_state *s = &view->state.tree;
7825 struct got_tree_entry *te;
7826 int n, nscroll = view->nlines - 3;
7828 if (view->gline)
7829 return tree_goto_line(view, nscroll);
7831 switch (ch) {
7832 case '0':
7833 case '$':
7834 case KEY_RIGHT:
7835 case 'l':
7836 case KEY_LEFT:
7837 case 'h':
7838 horizontal_scroll_input(view, ch);
7839 break;
7840 case 'i':
7841 s->show_ids = !s->show_ids;
7842 view->count = 0;
7843 break;
7844 case 'L':
7845 view->count = 0;
7846 if (!s->selected_entry)
7847 break;
7848 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7849 break;
7850 case 'R':
7851 view->count = 0;
7852 err = view_request_new(new_view, view, TOG_VIEW_REF);
7853 break;
7854 case 'g':
7855 case '=':
7856 case KEY_HOME:
7857 s->selected = 0;
7858 view->count = 0;
7859 if (s->tree == s->root)
7860 s->first_displayed_entry =
7861 got_object_tree_get_first_entry(s->tree);
7862 else
7863 s->first_displayed_entry = NULL;
7864 break;
7865 case 'G':
7866 case '*':
7867 case KEY_END: {
7868 int eos = view->nlines - 3;
7870 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7871 --eos; /* border */
7872 s->selected = 0;
7873 view->count = 0;
7874 te = got_object_tree_get_last_entry(s->tree);
7875 for (n = 0; n < eos; n++) {
7876 if (te == NULL) {
7877 if (s->tree != s->root) {
7878 s->first_displayed_entry = NULL;
7879 n++;
7881 break;
7883 s->first_displayed_entry = te;
7884 te = got_tree_entry_get_prev(s->tree, te);
7886 if (n > 0)
7887 s->selected = n - 1;
7888 break;
7890 case 'k':
7891 case KEY_UP:
7892 case CTRL('p'):
7893 if (s->selected > 0) {
7894 s->selected--;
7895 break;
7897 tree_scroll_up(s, 1);
7898 if (s->selected_entry == NULL ||
7899 (s->tree == s->root && s->selected_entry ==
7900 got_object_tree_get_first_entry(s->tree)))
7901 view->count = 0;
7902 break;
7903 case CTRL('u'):
7904 case 'u':
7905 nscroll /= 2;
7906 /* FALL THROUGH */
7907 case KEY_PPAGE:
7908 case CTRL('b'):
7909 case 'b':
7910 if (s->tree == s->root) {
7911 if (got_object_tree_get_first_entry(s->tree) ==
7912 s->first_displayed_entry)
7913 s->selected -= MIN(s->selected, nscroll);
7914 } else {
7915 if (s->first_displayed_entry == NULL)
7916 s->selected -= MIN(s->selected, nscroll);
7918 tree_scroll_up(s, MAX(0, nscroll));
7919 if (s->selected_entry == NULL ||
7920 (s->tree == s->root && s->selected_entry ==
7921 got_object_tree_get_first_entry(s->tree)))
7922 view->count = 0;
7923 break;
7924 case 'j':
7925 case KEY_DOWN:
7926 case CTRL('n'):
7927 if (s->selected < s->ndisplayed - 1) {
7928 s->selected++;
7929 break;
7931 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7932 == NULL) {
7933 /* can't scroll any further */
7934 view->count = 0;
7935 break;
7937 tree_scroll_down(view, 1);
7938 break;
7939 case CTRL('d'):
7940 case 'd':
7941 nscroll /= 2;
7942 /* FALL THROUGH */
7943 case KEY_NPAGE:
7944 case CTRL('f'):
7945 case 'f':
7946 case ' ':
7947 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7948 == NULL) {
7949 /* can't scroll any further; move cursor down */
7950 if (s->selected < s->ndisplayed - 1)
7951 s->selected += MIN(nscroll,
7952 s->ndisplayed - s->selected - 1);
7953 else
7954 view->count = 0;
7955 break;
7957 tree_scroll_down(view, nscroll);
7958 break;
7959 case KEY_ENTER:
7960 case '\r':
7961 case KEY_BACKSPACE:
7962 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7963 struct tog_parent_tree *parent;
7964 /* user selected '..' */
7965 if (s->tree == s->root) {
7966 view->count = 0;
7967 break;
7969 parent = TAILQ_FIRST(&s->parents);
7970 TAILQ_REMOVE(&s->parents, parent,
7971 entry);
7972 got_object_tree_close(s->tree);
7973 s->tree = parent->tree;
7974 s->first_displayed_entry =
7975 parent->first_displayed_entry;
7976 s->selected_entry =
7977 parent->selected_entry;
7978 s->selected = parent->selected;
7979 if (s->selected > view->nlines - 3) {
7980 err = offset_selection_down(view);
7981 if (err)
7982 break;
7984 free(parent);
7985 } else if (S_ISDIR(got_tree_entry_get_mode(
7986 s->selected_entry))) {
7987 struct got_tree_object *subtree;
7988 view->count = 0;
7989 err = got_object_open_as_tree(&subtree, s->repo,
7990 got_tree_entry_get_id(s->selected_entry));
7991 if (err)
7992 break;
7993 err = tree_view_visit_subtree(s, subtree);
7994 if (err) {
7995 got_object_tree_close(subtree);
7996 break;
7998 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7999 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
8000 break;
8001 case KEY_RESIZE:
8002 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
8003 s->selected = view->nlines - 4;
8004 view->count = 0;
8005 break;
8006 default:
8007 view->count = 0;
8008 break;
8011 return err;
8014 __dead static void
8015 usage_tree(void)
8017 endwin();
8018 fprintf(stderr,
8019 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
8020 getprogname());
8021 exit(1);
8024 static const struct got_error *
8025 cmd_tree(int argc, char *argv[])
8027 const struct got_error *error;
8028 struct got_repository *repo = NULL;
8029 struct got_worktree *worktree = NULL;
8030 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8031 struct got_object_id *commit_id = NULL;
8032 struct got_commit_object *commit = NULL;
8033 const char *commit_id_arg = NULL;
8034 char *label = NULL;
8035 struct got_reference *ref = NULL;
8036 const char *head_ref_name = NULL;
8037 int ch;
8038 struct tog_view *view;
8039 int *pack_fds = NULL;
8041 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
8042 switch (ch) {
8043 case 'c':
8044 commit_id_arg = optarg;
8045 break;
8046 case 'r':
8047 repo_path = realpath(optarg, NULL);
8048 if (repo_path == NULL)
8049 return got_error_from_errno2("realpath",
8050 optarg);
8051 break;
8052 default:
8053 usage_tree();
8054 /* NOTREACHED */
8058 argc -= optind;
8059 argv += optind;
8061 if (argc > 1)
8062 usage_tree();
8064 error = got_repo_pack_fds_open(&pack_fds);
8065 if (error != NULL)
8066 goto done;
8068 if (repo_path == NULL) {
8069 cwd = getcwd(NULL, 0);
8070 if (cwd == NULL)
8071 return got_error_from_errno("getcwd");
8072 error = got_worktree_open(&worktree, cwd);
8073 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8074 goto done;
8075 if (worktree)
8076 repo_path =
8077 strdup(got_worktree_get_repo_path(worktree));
8078 else
8079 repo_path = strdup(cwd);
8080 if (repo_path == NULL) {
8081 error = got_error_from_errno("strdup");
8082 goto done;
8086 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8087 if (error != NULL)
8088 goto done;
8090 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8091 repo, worktree);
8092 if (error)
8093 goto done;
8095 init_curses();
8097 error = apply_unveil(got_repo_get_path(repo), NULL);
8098 if (error)
8099 goto done;
8101 error = tog_load_refs(repo, 0);
8102 if (error)
8103 goto done;
8105 if (commit_id_arg == NULL) {
8106 error = got_repo_match_object_id(&commit_id, &label,
8107 worktree ? got_worktree_get_head_ref_name(worktree) :
8108 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8109 if (error)
8110 goto done;
8111 head_ref_name = label;
8112 } else {
8113 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8114 if (error == NULL)
8115 head_ref_name = got_ref_get_name(ref);
8116 else if (error->code != GOT_ERR_NOT_REF)
8117 goto done;
8118 error = got_repo_match_object_id(&commit_id, NULL,
8119 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8120 if (error)
8121 goto done;
8124 error = got_object_open_as_commit(&commit, repo, commit_id);
8125 if (error)
8126 goto done;
8128 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8129 if (view == NULL) {
8130 error = got_error_from_errno("view_open");
8131 goto done;
8133 error = open_tree_view(view, commit_id, head_ref_name, repo);
8134 if (error)
8135 goto done;
8136 if (!got_path_is_root_dir(in_repo_path)) {
8137 error = tree_view_walk_path(&view->state.tree, commit,
8138 in_repo_path);
8139 if (error)
8140 goto done;
8143 if (worktree) {
8144 /* Release work tree lock. */
8145 got_worktree_close(worktree);
8146 worktree = NULL;
8148 error = view_loop(view);
8149 done:
8150 free(repo_path);
8151 free(cwd);
8152 free(commit_id);
8153 free(label);
8154 if (ref)
8155 got_ref_close(ref);
8156 if (repo) {
8157 const struct got_error *close_err = got_repo_close(repo);
8158 if (error == NULL)
8159 error = close_err;
8161 if (pack_fds) {
8162 const struct got_error *pack_err =
8163 got_repo_pack_fds_close(pack_fds);
8164 if (error == NULL)
8165 error = pack_err;
8167 tog_free_refs();
8168 return error;
8171 static const struct got_error *
8172 ref_view_load_refs(struct tog_ref_view_state *s)
8174 struct got_reflist_entry *sre;
8175 struct tog_reflist_entry *re;
8177 s->nrefs = 0;
8178 TAILQ_FOREACH(sre, &tog_refs, entry) {
8179 if (strncmp(got_ref_get_name(sre->ref),
8180 "refs/got/", 9) == 0 &&
8181 strncmp(got_ref_get_name(sre->ref),
8182 "refs/got/backup/", 16) != 0)
8183 continue;
8185 re = malloc(sizeof(*re));
8186 if (re == NULL)
8187 return got_error_from_errno("malloc");
8189 re->ref = got_ref_dup(sre->ref);
8190 if (re->ref == NULL)
8191 return got_error_from_errno("got_ref_dup");
8192 re->idx = s->nrefs++;
8193 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8196 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8197 return NULL;
8200 static void
8201 ref_view_free_refs(struct tog_ref_view_state *s)
8203 struct tog_reflist_entry *re;
8205 while (!TAILQ_EMPTY(&s->refs)) {
8206 re = TAILQ_FIRST(&s->refs);
8207 TAILQ_REMOVE(&s->refs, re, entry);
8208 got_ref_close(re->ref);
8209 free(re);
8213 static const struct got_error *
8214 open_ref_view(struct tog_view *view, struct got_repository *repo)
8216 const struct got_error *err = NULL;
8217 struct tog_ref_view_state *s = &view->state.ref;
8219 s->selected_entry = 0;
8220 s->repo = repo;
8222 TAILQ_INIT(&s->refs);
8223 STAILQ_INIT(&s->colors);
8225 err = ref_view_load_refs(s);
8226 if (err)
8227 goto done;
8229 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8230 err = add_color(&s->colors, "^refs/heads/",
8231 TOG_COLOR_REFS_HEADS,
8232 get_color_value("TOG_COLOR_REFS_HEADS"));
8233 if (err)
8234 goto done;
8236 err = add_color(&s->colors, "^refs/tags/",
8237 TOG_COLOR_REFS_TAGS,
8238 get_color_value("TOG_COLOR_REFS_TAGS"));
8239 if (err)
8240 goto done;
8242 err = add_color(&s->colors, "^refs/remotes/",
8243 TOG_COLOR_REFS_REMOTES,
8244 get_color_value("TOG_COLOR_REFS_REMOTES"));
8245 if (err)
8246 goto done;
8248 err = add_color(&s->colors, "^refs/got/backup/",
8249 TOG_COLOR_REFS_BACKUP,
8250 get_color_value("TOG_COLOR_REFS_BACKUP"));
8251 if (err)
8252 goto done;
8255 view->show = show_ref_view;
8256 view->input = input_ref_view;
8257 view->close = close_ref_view;
8258 view->search_start = search_start_ref_view;
8259 view->search_next = search_next_ref_view;
8260 done:
8261 if (err) {
8262 if (view->close == NULL)
8263 close_ref_view(view);
8264 view_close(view);
8266 return err;
8269 static const struct got_error *
8270 close_ref_view(struct tog_view *view)
8272 struct tog_ref_view_state *s = &view->state.ref;
8274 ref_view_free_refs(s);
8275 free_colors(&s->colors);
8277 return NULL;
8280 static const struct got_error *
8281 resolve_reflist_entry(struct got_object_id **commit_id,
8282 struct tog_reflist_entry *re, struct got_repository *repo)
8284 const struct got_error *err = NULL;
8285 struct got_object_id *obj_id;
8286 struct got_tag_object *tag = NULL;
8287 int obj_type;
8289 *commit_id = NULL;
8291 err = got_ref_resolve(&obj_id, repo, re->ref);
8292 if (err)
8293 return err;
8295 err = got_object_get_type(&obj_type, repo, obj_id);
8296 if (err)
8297 goto done;
8299 switch (obj_type) {
8300 case GOT_OBJ_TYPE_COMMIT:
8301 *commit_id = obj_id;
8302 break;
8303 case GOT_OBJ_TYPE_TAG:
8304 err = got_object_open_as_tag(&tag, repo, obj_id);
8305 if (err)
8306 goto done;
8307 free(obj_id);
8308 err = got_object_get_type(&obj_type, repo,
8309 got_object_tag_get_object_id(tag));
8310 if (err)
8311 goto done;
8312 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8313 err = got_error(GOT_ERR_OBJ_TYPE);
8314 goto done;
8316 *commit_id = got_object_id_dup(
8317 got_object_tag_get_object_id(tag));
8318 if (*commit_id == NULL) {
8319 err = got_error_from_errno("got_object_id_dup");
8320 goto done;
8322 break;
8323 default:
8324 err = got_error(GOT_ERR_OBJ_TYPE);
8325 break;
8328 done:
8329 if (tag)
8330 got_object_tag_close(tag);
8331 if (err) {
8332 free(*commit_id);
8333 *commit_id = NULL;
8335 return err;
8338 static const struct got_error *
8339 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8340 struct tog_reflist_entry *re, struct got_repository *repo)
8342 struct tog_view *log_view;
8343 const struct got_error *err = NULL;
8344 struct got_object_id *commit_id = NULL;
8346 *new_view = NULL;
8348 err = resolve_reflist_entry(&commit_id, re, repo);
8349 if (err) {
8350 if (err->code != GOT_ERR_OBJ_TYPE)
8351 return err;
8352 else
8353 return NULL;
8356 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8357 if (log_view == NULL) {
8358 err = got_error_from_errno("view_open");
8359 goto done;
8362 err = open_log_view(log_view, commit_id, repo,
8363 got_ref_get_name(re->ref), "", 0);
8364 done:
8365 if (err)
8366 view_close(log_view);
8367 else
8368 *new_view = log_view;
8369 free(commit_id);
8370 return err;
8373 static void
8374 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8376 struct tog_reflist_entry *re;
8377 int i = 0;
8379 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8380 return;
8382 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8383 while (i++ < maxscroll) {
8384 if (re == NULL)
8385 break;
8386 s->first_displayed_entry = re;
8387 re = TAILQ_PREV(re, tog_reflist_head, entry);
8391 static const struct got_error *
8392 ref_scroll_down(struct tog_view *view, int maxscroll)
8394 struct tog_ref_view_state *s = &view->state.ref;
8395 struct tog_reflist_entry *next, *last;
8396 int n = 0;
8398 if (s->first_displayed_entry)
8399 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8400 else
8401 next = TAILQ_FIRST(&s->refs);
8403 last = s->last_displayed_entry;
8404 while (next && n++ < maxscroll) {
8405 if (last) {
8406 s->last_displayed_entry = last;
8407 last = TAILQ_NEXT(last, entry);
8409 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8410 s->first_displayed_entry = next;
8411 next = TAILQ_NEXT(next, entry);
8415 return NULL;
8418 static const struct got_error *
8419 search_start_ref_view(struct tog_view *view)
8421 struct tog_ref_view_state *s = &view->state.ref;
8423 s->matched_entry = NULL;
8424 return NULL;
8427 static int
8428 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8430 regmatch_t regmatch;
8432 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8433 0) == 0;
8436 static const struct got_error *
8437 search_next_ref_view(struct tog_view *view)
8439 struct tog_ref_view_state *s = &view->state.ref;
8440 struct tog_reflist_entry *re = NULL;
8442 if (!view->searching) {
8443 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8444 return NULL;
8447 if (s->matched_entry) {
8448 if (view->searching == TOG_SEARCH_FORWARD) {
8449 if (s->selected_entry)
8450 re = TAILQ_NEXT(s->selected_entry, entry);
8451 else
8452 re = TAILQ_PREV(s->selected_entry,
8453 tog_reflist_head, entry);
8454 } else {
8455 if (s->selected_entry == NULL)
8456 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8457 else
8458 re = TAILQ_PREV(s->selected_entry,
8459 tog_reflist_head, entry);
8461 } else {
8462 if (s->selected_entry)
8463 re = s->selected_entry;
8464 else if (view->searching == TOG_SEARCH_FORWARD)
8465 re = TAILQ_FIRST(&s->refs);
8466 else
8467 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8470 while (1) {
8471 if (re == NULL) {
8472 if (s->matched_entry == NULL) {
8473 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8474 return NULL;
8476 if (view->searching == TOG_SEARCH_FORWARD)
8477 re = TAILQ_FIRST(&s->refs);
8478 else
8479 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8482 if (match_reflist_entry(re, &view->regex)) {
8483 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8484 s->matched_entry = re;
8485 break;
8488 if (view->searching == TOG_SEARCH_FORWARD)
8489 re = TAILQ_NEXT(re, entry);
8490 else
8491 re = TAILQ_PREV(re, tog_reflist_head, entry);
8494 if (s->matched_entry) {
8495 s->first_displayed_entry = s->matched_entry;
8496 s->selected = 0;
8499 return NULL;
8502 static const struct got_error *
8503 show_ref_view(struct tog_view *view)
8505 const struct got_error *err = NULL;
8506 struct tog_ref_view_state *s = &view->state.ref;
8507 struct tog_reflist_entry *re;
8508 char *line = NULL;
8509 wchar_t *wline;
8510 struct tog_color *tc;
8511 int width, n, scrollx;
8512 int limit = view->nlines;
8514 werase(view->window);
8516 s->ndisplayed = 0;
8517 if (view_is_hsplit_top(view))
8518 --limit; /* border */
8520 if (limit == 0)
8521 return NULL;
8523 re = s->first_displayed_entry;
8525 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8526 s->nrefs) == -1)
8527 return got_error_from_errno("asprintf");
8529 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8530 if (err) {
8531 free(line);
8532 return err;
8534 if (view_needs_focus_indication(view))
8535 wstandout(view->window);
8536 waddwstr(view->window, wline);
8537 while (width++ < view->ncols)
8538 waddch(view->window, ' ');
8539 if (view_needs_focus_indication(view))
8540 wstandend(view->window);
8541 free(wline);
8542 wline = NULL;
8543 free(line);
8544 line = NULL;
8545 if (--limit <= 0)
8546 return NULL;
8548 n = 0;
8549 view->maxx = 0;
8550 while (re && limit > 0) {
8551 char *line = NULL;
8552 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8554 if (s->show_date) {
8555 struct got_commit_object *ci;
8556 struct got_tag_object *tag;
8557 struct got_object_id *id;
8558 struct tm tm;
8559 time_t t;
8561 err = got_ref_resolve(&id, s->repo, re->ref);
8562 if (err)
8563 return err;
8564 err = got_object_open_as_tag(&tag, s->repo, id);
8565 if (err) {
8566 if (err->code != GOT_ERR_OBJ_TYPE) {
8567 free(id);
8568 return err;
8570 err = got_object_open_as_commit(&ci, s->repo,
8571 id);
8572 if (err) {
8573 free(id);
8574 return err;
8576 t = got_object_commit_get_committer_time(ci);
8577 got_object_commit_close(ci);
8578 } else {
8579 t = got_object_tag_get_tagger_time(tag);
8580 got_object_tag_close(tag);
8582 free(id);
8583 if (gmtime_r(&t, &tm) == NULL)
8584 return got_error_from_errno("gmtime_r");
8585 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8586 return got_error(GOT_ERR_NO_SPACE);
8588 if (got_ref_is_symbolic(re->ref)) {
8589 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8590 ymd : "", got_ref_get_name(re->ref),
8591 got_ref_get_symref_target(re->ref)) == -1)
8592 return got_error_from_errno("asprintf");
8593 } else if (s->show_ids) {
8594 struct got_object_id *id;
8595 char *id_str;
8596 err = got_ref_resolve(&id, s->repo, re->ref);
8597 if (err)
8598 return err;
8599 err = got_object_id_str(&id_str, id);
8600 if (err) {
8601 free(id);
8602 return err;
8604 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8605 got_ref_get_name(re->ref), id_str) == -1) {
8606 err = got_error_from_errno("asprintf");
8607 free(id);
8608 free(id_str);
8609 return err;
8611 free(id);
8612 free(id_str);
8613 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8614 got_ref_get_name(re->ref)) == -1)
8615 return got_error_from_errno("asprintf");
8617 /* use full line width to determine view->maxx */
8618 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8619 if (err) {
8620 free(line);
8621 return err;
8623 view->maxx = MAX(view->maxx, width);
8624 free(wline);
8625 wline = NULL;
8627 err = format_line(&wline, &width, &scrollx, line, view->x,
8628 view->ncols, 0, 0);
8629 if (err) {
8630 free(line);
8631 return err;
8633 if (n == s->selected) {
8634 if (view->focussed)
8635 wstandout(view->window);
8636 s->selected_entry = re;
8638 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8639 if (tc)
8640 wattr_on(view->window,
8641 COLOR_PAIR(tc->colorpair), NULL);
8642 waddwstr(view->window, &wline[scrollx]);
8643 if (tc)
8644 wattr_off(view->window,
8645 COLOR_PAIR(tc->colorpair), NULL);
8646 if (width < view->ncols)
8647 waddch(view->window, '\n');
8648 if (n == s->selected && view->focussed)
8649 wstandend(view->window);
8650 free(line);
8651 free(wline);
8652 wline = NULL;
8653 n++;
8654 s->ndisplayed++;
8655 s->last_displayed_entry = re;
8657 limit--;
8658 re = TAILQ_NEXT(re, entry);
8661 view_border(view);
8662 return err;
8665 static const struct got_error *
8666 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8667 struct tog_reflist_entry *re, struct got_repository *repo)
8669 const struct got_error *err = NULL;
8670 struct got_object_id *commit_id = NULL;
8671 struct tog_view *tree_view;
8673 *new_view = NULL;
8675 err = resolve_reflist_entry(&commit_id, re, repo);
8676 if (err) {
8677 if (err->code != GOT_ERR_OBJ_TYPE)
8678 return err;
8679 else
8680 return NULL;
8684 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8685 if (tree_view == NULL) {
8686 err = got_error_from_errno("view_open");
8687 goto done;
8690 err = open_tree_view(tree_view, commit_id,
8691 got_ref_get_name(re->ref), repo);
8692 if (err)
8693 goto done;
8695 *new_view = tree_view;
8696 done:
8697 free(commit_id);
8698 return err;
8701 static const struct got_error *
8702 ref_goto_line(struct tog_view *view, int nlines)
8704 const struct got_error *err = NULL;
8705 struct tog_ref_view_state *s = &view->state.ref;
8706 int g, idx = s->selected_entry->idx;
8708 g = view->gline;
8709 view->gline = 0;
8711 if (g == 0)
8712 g = 1;
8713 else if (g > s->nrefs)
8714 g = s->nrefs;
8716 if (g >= s->first_displayed_entry->idx + 1 &&
8717 g <= s->last_displayed_entry->idx + 1 &&
8718 g - s->first_displayed_entry->idx - 1 < nlines) {
8719 s->selected = g - s->first_displayed_entry->idx - 1;
8720 return NULL;
8723 if (idx + 1 < g) {
8724 err = ref_scroll_down(view, g - idx - 1);
8725 if (err)
8726 return err;
8727 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8728 s->first_displayed_entry->idx + s->selected < g &&
8729 s->selected < s->ndisplayed - 1)
8730 s->selected = g - s->first_displayed_entry->idx - 1;
8731 } else if (idx + 1 > g)
8732 ref_scroll_up(s, idx - g + 1);
8734 if (g < nlines && s->first_displayed_entry->idx == 0)
8735 s->selected = g - 1;
8737 return NULL;
8741 static const struct got_error *
8742 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8744 const struct got_error *err = NULL;
8745 struct tog_ref_view_state *s = &view->state.ref;
8746 struct tog_reflist_entry *re;
8747 int n, nscroll = view->nlines - 1;
8749 if (view->gline)
8750 return ref_goto_line(view, nscroll);
8752 switch (ch) {
8753 case '0':
8754 case '$':
8755 case KEY_RIGHT:
8756 case 'l':
8757 case KEY_LEFT:
8758 case 'h':
8759 horizontal_scroll_input(view, ch);
8760 break;
8761 case 'i':
8762 s->show_ids = !s->show_ids;
8763 view->count = 0;
8764 break;
8765 case 'm':
8766 s->show_date = !s->show_date;
8767 view->count = 0;
8768 break;
8769 case 'o':
8770 s->sort_by_date = !s->sort_by_date;
8771 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8772 view->count = 0;
8773 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8774 got_ref_cmp_by_commit_timestamp_descending :
8775 tog_ref_cmp_by_name, s->repo);
8776 if (err)
8777 break;
8778 got_reflist_object_id_map_free(tog_refs_idmap);
8779 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8780 &tog_refs, s->repo);
8781 if (err)
8782 break;
8783 ref_view_free_refs(s);
8784 err = ref_view_load_refs(s);
8785 break;
8786 case KEY_ENTER:
8787 case '\r':
8788 view->count = 0;
8789 if (!s->selected_entry)
8790 break;
8791 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8792 break;
8793 case 'T':
8794 view->count = 0;
8795 if (!s->selected_entry)
8796 break;
8797 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8798 break;
8799 case 'g':
8800 case '=':
8801 case KEY_HOME:
8802 s->selected = 0;
8803 view->count = 0;
8804 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8805 break;
8806 case 'G':
8807 case '*':
8808 case KEY_END: {
8809 int eos = view->nlines - 1;
8811 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8812 --eos; /* border */
8813 s->selected = 0;
8814 view->count = 0;
8815 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8816 for (n = 0; n < eos; n++) {
8817 if (re == NULL)
8818 break;
8819 s->first_displayed_entry = re;
8820 re = TAILQ_PREV(re, tog_reflist_head, entry);
8822 if (n > 0)
8823 s->selected = n - 1;
8824 break;
8826 case 'k':
8827 case KEY_UP:
8828 case CTRL('p'):
8829 if (s->selected > 0) {
8830 s->selected--;
8831 break;
8833 ref_scroll_up(s, 1);
8834 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8835 view->count = 0;
8836 break;
8837 case CTRL('u'):
8838 case 'u':
8839 nscroll /= 2;
8840 /* FALL THROUGH */
8841 case KEY_PPAGE:
8842 case CTRL('b'):
8843 case 'b':
8844 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8845 s->selected -= MIN(nscroll, s->selected);
8846 ref_scroll_up(s, MAX(0, nscroll));
8847 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8848 view->count = 0;
8849 break;
8850 case 'j':
8851 case KEY_DOWN:
8852 case CTRL('n'):
8853 if (s->selected < s->ndisplayed - 1) {
8854 s->selected++;
8855 break;
8857 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8858 /* can't scroll any further */
8859 view->count = 0;
8860 break;
8862 ref_scroll_down(view, 1);
8863 break;
8864 case CTRL('d'):
8865 case 'd':
8866 nscroll /= 2;
8867 /* FALL THROUGH */
8868 case KEY_NPAGE:
8869 case CTRL('f'):
8870 case 'f':
8871 case ' ':
8872 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8873 /* can't scroll any further; move cursor down */
8874 if (s->selected < s->ndisplayed - 1)
8875 s->selected += MIN(nscroll,
8876 s->ndisplayed - s->selected - 1);
8877 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8878 s->selected += s->ndisplayed - s->selected - 1;
8879 view->count = 0;
8880 break;
8882 ref_scroll_down(view, nscroll);
8883 break;
8884 case CTRL('l'):
8885 view->count = 0;
8886 tog_free_refs();
8887 err = tog_load_refs(s->repo, s->sort_by_date);
8888 if (err)
8889 break;
8890 ref_view_free_refs(s);
8891 err = ref_view_load_refs(s);
8892 break;
8893 case KEY_RESIZE:
8894 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8895 s->selected = view->nlines - 2;
8896 break;
8897 default:
8898 view->count = 0;
8899 break;
8902 return err;
8905 __dead static void
8906 usage_ref(void)
8908 endwin();
8909 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8910 getprogname());
8911 exit(1);
8914 static const struct got_error *
8915 cmd_ref(int argc, char *argv[])
8917 const struct got_error *error;
8918 struct got_repository *repo = NULL;
8919 struct got_worktree *worktree = NULL;
8920 char *cwd = NULL, *repo_path = NULL;
8921 int ch;
8922 struct tog_view *view;
8923 int *pack_fds = NULL;
8925 while ((ch = getopt(argc, argv, "r:")) != -1) {
8926 switch (ch) {
8927 case 'r':
8928 repo_path = realpath(optarg, NULL);
8929 if (repo_path == NULL)
8930 return got_error_from_errno2("realpath",
8931 optarg);
8932 break;
8933 default:
8934 usage_ref();
8935 /* NOTREACHED */
8939 argc -= optind;
8940 argv += optind;
8942 if (argc > 1)
8943 usage_ref();
8945 error = got_repo_pack_fds_open(&pack_fds);
8946 if (error != NULL)
8947 goto done;
8949 if (repo_path == NULL) {
8950 cwd = getcwd(NULL, 0);
8951 if (cwd == NULL)
8952 return got_error_from_errno("getcwd");
8953 error = got_worktree_open(&worktree, cwd);
8954 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8955 goto done;
8956 if (worktree)
8957 repo_path =
8958 strdup(got_worktree_get_repo_path(worktree));
8959 else
8960 repo_path = strdup(cwd);
8961 if (repo_path == NULL) {
8962 error = got_error_from_errno("strdup");
8963 goto done;
8967 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8968 if (error != NULL)
8969 goto done;
8971 init_curses();
8973 error = apply_unveil(got_repo_get_path(repo), NULL);
8974 if (error)
8975 goto done;
8977 error = tog_load_refs(repo, 0);
8978 if (error)
8979 goto done;
8981 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8982 if (view == NULL) {
8983 error = got_error_from_errno("view_open");
8984 goto done;
8987 error = open_ref_view(view, repo);
8988 if (error)
8989 goto done;
8991 if (worktree) {
8992 /* Release work tree lock. */
8993 got_worktree_close(worktree);
8994 worktree = NULL;
8996 error = view_loop(view);
8997 done:
8998 free(repo_path);
8999 free(cwd);
9000 if (repo) {
9001 const struct got_error *close_err = got_repo_close(repo);
9002 if (close_err)
9003 error = close_err;
9005 if (pack_fds) {
9006 const struct got_error *pack_err =
9007 got_repo_pack_fds_close(pack_fds);
9008 if (error == NULL)
9009 error = pack_err;
9011 tog_free_refs();
9012 return error;
9015 static const struct got_error*
9016 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
9017 const char *str)
9019 size_t len;
9021 if (win == NULL)
9022 win = stdscr;
9024 len = strlen(str);
9025 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
9027 if (focus)
9028 wstandout(win);
9029 if (mvwprintw(win, y, x, "%s", str) == ERR)
9030 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
9031 if (focus)
9032 wstandend(win);
9034 return NULL;
9037 static const struct got_error *
9038 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
9040 off_t *p;
9042 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
9043 if (p == NULL) {
9044 free(*line_offsets);
9045 *line_offsets = NULL;
9046 return got_error_from_errno("reallocarray");
9049 *line_offsets = p;
9050 (*line_offsets)[*nlines] = off;
9051 ++(*nlines);
9052 return NULL;
9055 static const struct got_error *
9056 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
9058 *ret = 0;
9060 for (;n > 0; --n, ++km) {
9061 char *t0, *t, *k;
9062 size_t len = 1;
9064 if (km->keys == NULL)
9065 continue;
9067 t = t0 = strdup(km->keys);
9068 if (t0 == NULL)
9069 return got_error_from_errno("strdup");
9071 len += strlen(t);
9072 while ((k = strsep(&t, " ")) != NULL)
9073 len += strlen(k) > 1 ? 2 : 0;
9074 free(t0);
9075 *ret = MAX(*ret, len);
9078 return NULL;
9082 * Write keymap section headers, keys, and key info in km to f.
9083 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9084 * wrap control and symbolic keys in guillemets, else use <>.
9086 static const struct got_error *
9087 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9089 int n, len = width;
9091 if (km->keys) {
9092 static const char *u8_glyph[] = {
9093 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9094 "\xe2\x80\xba" /* U+203A (utf8 >) */
9096 char *t0, *t, *k;
9097 int cs, s, first = 1;
9099 cs = got_locale_is_utf8();
9101 t = t0 = strdup(km->keys);
9102 if (t0 == NULL)
9103 return got_error_from_errno("strdup");
9105 len = strlen(km->keys);
9106 while ((k = strsep(&t, " ")) != NULL) {
9107 s = strlen(k) > 1; /* control or symbolic key */
9108 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9109 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9110 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9111 if (n < 0) {
9112 free(t0);
9113 return got_error_from_errno("fprintf");
9115 first = 0;
9116 len += s ? 2 : 0;
9117 *off += n;
9119 free(t0);
9121 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9122 if (n < 0)
9123 return got_error_from_errno("fprintf");
9124 *off += n;
9126 return NULL;
9129 static const struct got_error *
9130 format_help(struct tog_help_view_state *s)
9132 const struct got_error *err = NULL;
9133 off_t off = 0;
9134 int i, max, n, show = s->all;
9135 static const struct tog_key_map km[] = {
9136 #define KEYMAP_(info, type) { NULL, (info), type }
9137 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9138 GENERATE_HELP
9139 #undef KEYMAP_
9140 #undef KEY_
9143 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9144 if (err)
9145 return err;
9147 n = nitems(km);
9148 err = max_key_str(&max, km, n);
9149 if (err)
9150 return err;
9152 for (i = 0; i < n; ++i) {
9153 if (km[i].keys == NULL) {
9154 show = s->all;
9155 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9156 km[i].type == s->type || s->all)
9157 show = 1;
9159 if (show) {
9160 err = format_help_line(&off, s->f, &km[i], max);
9161 if (err)
9162 return err;
9163 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9164 if (err)
9165 return err;
9168 fputc('\n', s->f);
9169 ++off;
9170 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9171 return err;
9174 static const struct got_error *
9175 create_help(struct tog_help_view_state *s)
9177 FILE *f;
9178 const struct got_error *err;
9180 free(s->line_offsets);
9181 s->line_offsets = NULL;
9182 s->nlines = 0;
9184 f = got_opentemp();
9185 if (f == NULL)
9186 return got_error_from_errno("got_opentemp");
9187 s->f = f;
9189 err = format_help(s);
9190 if (err)
9191 return err;
9193 if (s->f && fflush(s->f) != 0)
9194 return got_error_from_errno("fflush");
9196 return NULL;
9199 static const struct got_error *
9200 search_start_help_view(struct tog_view *view)
9202 view->state.help.matched_line = 0;
9203 return NULL;
9206 static void
9207 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9208 size_t *nlines, int **first, int **last, int **match, int **selected)
9210 struct tog_help_view_state *s = &view->state.help;
9212 *f = s->f;
9213 *nlines = s->nlines;
9214 *line_offsets = s->line_offsets;
9215 *match = &s->matched_line;
9216 *first = &s->first_displayed_line;
9217 *last = &s->last_displayed_line;
9218 *selected = &s->selected_line;
9221 static const struct got_error *
9222 show_help_view(struct tog_view *view)
9224 struct tog_help_view_state *s = &view->state.help;
9225 const struct got_error *err;
9226 regmatch_t *regmatch = &view->regmatch;
9227 wchar_t *wline;
9228 char *line;
9229 ssize_t linelen;
9230 size_t linesz = 0;
9231 int width, nprinted = 0, rc = 0;
9232 int eos = view->nlines;
9234 if (view_is_hsplit_top(view))
9235 --eos; /* account for border */
9237 s->lineno = 0;
9238 rewind(s->f);
9239 werase(view->window);
9241 if (view->gline > s->nlines - 1)
9242 view->gline = s->nlines - 1;
9244 err = win_draw_center(view->window, 0, 0, view->ncols,
9245 view_needs_focus_indication(view),
9246 "tog help (press q to return to tog)");
9247 if (err)
9248 return err;
9249 if (eos <= 1)
9250 return NULL;
9251 waddstr(view->window, "\n\n");
9252 eos -= 2;
9254 s->eof = 0;
9255 view->maxx = 0;
9256 line = NULL;
9257 while (eos > 0 && nprinted < eos) {
9258 attr_t attr = 0;
9260 linelen = getline(&line, &linesz, s->f);
9261 if (linelen == -1) {
9262 if (!feof(s->f)) {
9263 free(line);
9264 return got_ferror(s->f, GOT_ERR_IO);
9266 s->eof = 1;
9267 break;
9269 if (++s->lineno < s->first_displayed_line)
9270 continue;
9271 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9272 continue;
9273 if (s->lineno == view->hiline)
9274 attr = A_STANDOUT;
9276 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9277 view->x ? 1 : 0);
9278 if (err) {
9279 free(line);
9280 return err;
9282 view->maxx = MAX(view->maxx, width);
9283 free(wline);
9284 wline = NULL;
9286 if (attr)
9287 wattron(view->window, attr);
9288 if (s->first_displayed_line + nprinted == s->matched_line &&
9289 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9290 err = add_matched_line(&width, line, view->ncols - 1, 0,
9291 view->window, view->x, regmatch);
9292 if (err) {
9293 free(line);
9294 return err;
9296 } else {
9297 int skip;
9299 err = format_line(&wline, &width, &skip, line,
9300 view->x, view->ncols, 0, view->x ? 1 : 0);
9301 if (err) {
9302 free(line);
9303 return err;
9305 waddwstr(view->window, &wline[skip]);
9306 free(wline);
9307 wline = NULL;
9309 if (s->lineno == view->hiline) {
9310 while (width++ < view->ncols)
9311 waddch(view->window, ' ');
9312 } else {
9313 if (width < view->ncols)
9314 waddch(view->window, '\n');
9316 if (attr)
9317 wattroff(view->window, attr);
9318 if (++nprinted == 1)
9319 s->first_displayed_line = s->lineno;
9321 free(line);
9322 if (nprinted > 0)
9323 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9324 else
9325 s->last_displayed_line = s->first_displayed_line;
9327 view_border(view);
9329 if (s->eof) {
9330 rc = waddnstr(view->window,
9331 "See the tog(1) manual page for full documentation",
9332 view->ncols - 1);
9333 if (rc == ERR)
9334 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9335 } else {
9336 wmove(view->window, view->nlines - 1, 0);
9337 wclrtoeol(view->window);
9338 wstandout(view->window);
9339 rc = waddnstr(view->window, "scroll down for more...",
9340 view->ncols - 1);
9341 if (rc == ERR)
9342 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9343 if (getcurx(view->window) < view->ncols - 6) {
9344 rc = wprintw(view->window, "[%.0f%%]",
9345 100.00 * s->last_displayed_line / s->nlines);
9346 if (rc == ERR)
9347 return got_error_msg(GOT_ERR_IO, "wprintw");
9349 wstandend(view->window);
9352 return NULL;
9355 static const struct got_error *
9356 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9358 struct tog_help_view_state *s = &view->state.help;
9359 const struct got_error *err = NULL;
9360 char *line = NULL;
9361 ssize_t linelen;
9362 size_t linesz = 0;
9363 int eos, nscroll;
9365 eos = nscroll = view->nlines;
9366 if (view_is_hsplit_top(view))
9367 --eos; /* border */
9369 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9371 switch (ch) {
9372 case '0':
9373 case '$':
9374 case KEY_RIGHT:
9375 case 'l':
9376 case KEY_LEFT:
9377 case 'h':
9378 horizontal_scroll_input(view, ch);
9379 break;
9380 case 'g':
9381 case KEY_HOME:
9382 s->first_displayed_line = 1;
9383 view->count = 0;
9384 break;
9385 case 'G':
9386 case KEY_END:
9387 view->count = 0;
9388 if (s->eof)
9389 break;
9390 s->first_displayed_line = (s->nlines - eos) + 3;
9391 s->eof = 1;
9392 break;
9393 case 'k':
9394 case KEY_UP:
9395 if (s->first_displayed_line > 1)
9396 --s->first_displayed_line;
9397 else
9398 view->count = 0;
9399 break;
9400 case CTRL('u'):
9401 case 'u':
9402 nscroll /= 2;
9403 /* FALL THROUGH */
9404 case KEY_PPAGE:
9405 case CTRL('b'):
9406 case 'b':
9407 if (s->first_displayed_line == 1) {
9408 view->count = 0;
9409 break;
9411 while (--nscroll > 0 && s->first_displayed_line > 1)
9412 s->first_displayed_line--;
9413 break;
9414 case 'j':
9415 case KEY_DOWN:
9416 case CTRL('n'):
9417 if (!s->eof)
9418 ++s->first_displayed_line;
9419 else
9420 view->count = 0;
9421 break;
9422 case CTRL('d'):
9423 case 'd':
9424 nscroll /= 2;
9425 /* FALL THROUGH */
9426 case KEY_NPAGE:
9427 case CTRL('f'):
9428 case 'f':
9429 case ' ':
9430 if (s->eof) {
9431 view->count = 0;
9432 break;
9434 while (!s->eof && --nscroll > 0) {
9435 linelen = getline(&line, &linesz, s->f);
9436 s->first_displayed_line++;
9437 if (linelen == -1) {
9438 if (feof(s->f))
9439 s->eof = 1;
9440 else
9441 err = got_ferror(s->f, GOT_ERR_IO);
9442 break;
9445 free(line);
9446 break;
9447 default:
9448 view->count = 0;
9449 break;
9452 return err;
9455 static const struct got_error *
9456 close_help_view(struct tog_view *view)
9458 struct tog_help_view_state *s = &view->state.help;
9460 free(s->line_offsets);
9461 s->line_offsets = NULL;
9462 if (fclose(s->f) == EOF)
9463 return got_error_from_errno("fclose");
9465 return NULL;
9468 static const struct got_error *
9469 reset_help_view(struct tog_view *view)
9471 struct tog_help_view_state *s = &view->state.help;
9474 if (s->f && fclose(s->f) == EOF)
9475 return got_error_from_errno("fclose");
9477 wclear(view->window);
9478 view->count = 0;
9479 view->x = 0;
9480 s->all = !s->all;
9481 s->first_displayed_line = 1;
9482 s->last_displayed_line = view->nlines;
9483 s->matched_line = 0;
9485 return create_help(s);
9488 static const struct got_error *
9489 open_help_view(struct tog_view *view, struct tog_view *parent)
9491 const struct got_error *err = NULL;
9492 struct tog_help_view_state *s = &view->state.help;
9494 s->type = (enum tog_keymap_type)parent->type;
9495 s->first_displayed_line = 1;
9496 s->last_displayed_line = view->nlines;
9497 s->selected_line = 1;
9499 view->show = show_help_view;
9500 view->input = input_help_view;
9501 view->reset = reset_help_view;
9502 view->close = close_help_view;
9503 view->search_start = search_start_help_view;
9504 view->search_setup = search_setup_help_view;
9505 view->search_next = search_next_view_match;
9507 err = create_help(s);
9508 return err;
9511 static const struct got_error *
9512 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9513 enum tog_view_type request, int y, int x)
9515 const struct got_error *err = NULL;
9517 *new_view = NULL;
9519 switch (request) {
9520 case TOG_VIEW_DIFF:
9521 if (view->type == TOG_VIEW_LOG) {
9522 struct tog_log_view_state *s = &view->state.log;
9524 err = open_diff_view_for_commit(new_view, y, x,
9525 s->selected_entry->commit, s->selected_entry->id,
9526 view, s->repo);
9527 } else
9528 return got_error_msg(GOT_ERR_NOT_IMPL,
9529 "parent/child view pair not supported");
9530 break;
9531 case TOG_VIEW_BLAME:
9532 if (view->type == TOG_VIEW_TREE) {
9533 struct tog_tree_view_state *s = &view->state.tree;
9535 err = blame_tree_entry(new_view, y, x,
9536 s->selected_entry, &s->parents, s->commit_id,
9537 s->repo);
9538 } else
9539 return got_error_msg(GOT_ERR_NOT_IMPL,
9540 "parent/child view pair not supported");
9541 break;
9542 case TOG_VIEW_LOG:
9543 if (view->type == TOG_VIEW_BLAME)
9544 err = log_annotated_line(new_view, y, x,
9545 view->state.blame.repo, view->state.blame.id_to_log);
9546 else if (view->type == TOG_VIEW_TREE)
9547 err = log_selected_tree_entry(new_view, y, x,
9548 &view->state.tree);
9549 else if (view->type == TOG_VIEW_REF)
9550 err = log_ref_entry(new_view, y, x,
9551 view->state.ref.selected_entry,
9552 view->state.ref.repo);
9553 else
9554 return got_error_msg(GOT_ERR_NOT_IMPL,
9555 "parent/child view pair not supported");
9556 break;
9557 case TOG_VIEW_TREE:
9558 if (view->type == TOG_VIEW_LOG)
9559 err = browse_commit_tree(new_view, y, x,
9560 view->state.log.selected_entry,
9561 view->state.log.in_repo_path,
9562 view->state.log.head_ref_name,
9563 view->state.log.repo);
9564 else if (view->type == TOG_VIEW_REF)
9565 err = browse_ref_tree(new_view, y, x,
9566 view->state.ref.selected_entry,
9567 view->state.ref.repo);
9568 else
9569 return got_error_msg(GOT_ERR_NOT_IMPL,
9570 "parent/child view pair not supported");
9571 break;
9572 case TOG_VIEW_REF:
9573 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9574 if (*new_view == NULL)
9575 return got_error_from_errno("view_open");
9576 if (view->type == TOG_VIEW_LOG)
9577 err = open_ref_view(*new_view, view->state.log.repo);
9578 else if (view->type == TOG_VIEW_TREE)
9579 err = open_ref_view(*new_view, view->state.tree.repo);
9580 else
9581 err = got_error_msg(GOT_ERR_NOT_IMPL,
9582 "parent/child view pair not supported");
9583 if (err)
9584 view_close(*new_view);
9585 break;
9586 case TOG_VIEW_HELP:
9587 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9588 if (*new_view == NULL)
9589 return got_error_from_errno("view_open");
9590 err = open_help_view(*new_view, view);
9591 if (err)
9592 view_close(*new_view);
9593 break;
9594 default:
9595 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9598 return err;
9602 * If view was scrolled down to move the selected line into view when opening a
9603 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9605 static void
9606 offset_selection_up(struct tog_view *view)
9608 switch (view->type) {
9609 case TOG_VIEW_BLAME: {
9610 struct tog_blame_view_state *s = &view->state.blame;
9611 if (s->first_displayed_line == 1) {
9612 s->selected_line = MAX(s->selected_line - view->offset,
9613 1);
9614 break;
9616 if (s->first_displayed_line > view->offset)
9617 s->first_displayed_line -= view->offset;
9618 else
9619 s->first_displayed_line = 1;
9620 s->selected_line += view->offset;
9621 break;
9623 case TOG_VIEW_LOG:
9624 log_scroll_up(&view->state.log, view->offset);
9625 view->state.log.selected += view->offset;
9626 break;
9627 case TOG_VIEW_REF:
9628 ref_scroll_up(&view->state.ref, view->offset);
9629 view->state.ref.selected += view->offset;
9630 break;
9631 case TOG_VIEW_TREE:
9632 tree_scroll_up(&view->state.tree, view->offset);
9633 view->state.tree.selected += view->offset;
9634 break;
9635 default:
9636 break;
9639 view->offset = 0;
9643 * If the selected line is in the section of screen covered by the bottom split,
9644 * scroll down offset lines to move it into view and index its new position.
9646 static const struct got_error *
9647 offset_selection_down(struct tog_view *view)
9649 const struct got_error *err = NULL;
9650 const struct got_error *(*scrolld)(struct tog_view *, int);
9651 int *selected = NULL;
9652 int header, offset;
9654 switch (view->type) {
9655 case TOG_VIEW_BLAME: {
9656 struct tog_blame_view_state *s = &view->state.blame;
9657 header = 3;
9658 scrolld = NULL;
9659 if (s->selected_line > view->nlines - header) {
9660 offset = abs(view->nlines - s->selected_line - header);
9661 s->first_displayed_line += offset;
9662 s->selected_line -= offset;
9663 view->offset = offset;
9665 break;
9667 case TOG_VIEW_LOG: {
9668 struct tog_log_view_state *s = &view->state.log;
9669 scrolld = &log_scroll_down;
9670 header = view_is_parent_view(view) ? 3 : 2;
9671 selected = &s->selected;
9672 break;
9674 case TOG_VIEW_REF: {
9675 struct tog_ref_view_state *s = &view->state.ref;
9676 scrolld = &ref_scroll_down;
9677 header = 3;
9678 selected = &s->selected;
9679 break;
9681 case TOG_VIEW_TREE: {
9682 struct tog_tree_view_state *s = &view->state.tree;
9683 scrolld = &tree_scroll_down;
9684 header = 5;
9685 selected = &s->selected;
9686 break;
9688 default:
9689 selected = NULL;
9690 scrolld = NULL;
9691 header = 0;
9692 break;
9695 if (selected && *selected > view->nlines - header) {
9696 offset = abs(view->nlines - *selected - header);
9697 view->offset = offset;
9698 if (scrolld && offset) {
9699 err = scrolld(view, offset);
9700 *selected -= offset;
9704 return err;
9707 static void
9708 list_commands(FILE *fp)
9710 size_t i;
9712 fprintf(fp, "commands:");
9713 for (i = 0; i < nitems(tog_commands); i++) {
9714 const struct tog_cmd *cmd = &tog_commands[i];
9715 fprintf(fp, " %s", cmd->name);
9717 fputc('\n', fp);
9720 __dead static void
9721 usage(int hflag, int status)
9723 FILE *fp = (status == 0) ? stdout : stderr;
9725 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9726 getprogname());
9727 if (hflag) {
9728 fprintf(fp, "lazy usage: %s path\n", getprogname());
9729 list_commands(fp);
9731 exit(status);
9734 static char **
9735 make_argv(int argc, ...)
9737 va_list ap;
9738 char **argv;
9739 int i;
9741 va_start(ap, argc);
9743 argv = calloc(argc, sizeof(char *));
9744 if (argv == NULL)
9745 err(1, "calloc");
9746 for (i = 0; i < argc; i++) {
9747 argv[i] = strdup(va_arg(ap, char *));
9748 if (argv[i] == NULL)
9749 err(1, "strdup");
9752 va_end(ap);
9753 return argv;
9757 * Try to convert 'tog path' into a 'tog log path' command.
9758 * The user could simply have mistyped the command rather than knowingly
9759 * provided a path. So check whether argv[0] can in fact be resolved
9760 * to a path in the HEAD commit and print a special error if not.
9761 * This hack is for mpi@ <3
9763 static const struct got_error *
9764 tog_log_with_path(int argc, char *argv[])
9766 const struct got_error *error = NULL, *close_err;
9767 const struct tog_cmd *cmd = NULL;
9768 struct got_repository *repo = NULL;
9769 struct got_worktree *worktree = NULL;
9770 struct got_object_id *commit_id = NULL, *id = NULL;
9771 struct got_commit_object *commit = NULL;
9772 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9773 char *commit_id_str = NULL, **cmd_argv = NULL;
9774 int *pack_fds = NULL;
9776 cwd = getcwd(NULL, 0);
9777 if (cwd == NULL)
9778 return got_error_from_errno("getcwd");
9780 error = got_repo_pack_fds_open(&pack_fds);
9781 if (error != NULL)
9782 goto done;
9784 error = got_worktree_open(&worktree, cwd);
9785 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9786 goto done;
9788 if (worktree)
9789 repo_path = strdup(got_worktree_get_repo_path(worktree));
9790 else
9791 repo_path = strdup(cwd);
9792 if (repo_path == NULL) {
9793 error = got_error_from_errno("strdup");
9794 goto done;
9797 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9798 if (error != NULL)
9799 goto done;
9801 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9802 repo, worktree);
9803 if (error)
9804 goto done;
9806 error = tog_load_refs(repo, 0);
9807 if (error)
9808 goto done;
9809 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9810 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9811 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9812 if (error)
9813 goto done;
9815 if (worktree) {
9816 got_worktree_close(worktree);
9817 worktree = NULL;
9820 error = got_object_open_as_commit(&commit, repo, commit_id);
9821 if (error)
9822 goto done;
9824 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9825 if (error) {
9826 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9827 goto done;
9828 fprintf(stderr, "%s: '%s' is no known command or path\n",
9829 getprogname(), argv[0]);
9830 usage(1, 1);
9831 /* not reached */
9834 error = got_object_id_str(&commit_id_str, commit_id);
9835 if (error)
9836 goto done;
9838 cmd = &tog_commands[0]; /* log */
9839 argc = 4;
9840 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9841 error = cmd->cmd_main(argc, cmd_argv);
9842 done:
9843 if (repo) {
9844 close_err = got_repo_close(repo);
9845 if (error == NULL)
9846 error = close_err;
9848 if (commit)
9849 got_object_commit_close(commit);
9850 if (worktree)
9851 got_worktree_close(worktree);
9852 if (pack_fds) {
9853 const struct got_error *pack_err =
9854 got_repo_pack_fds_close(pack_fds);
9855 if (error == NULL)
9856 error = pack_err;
9858 free(id);
9859 free(commit_id_str);
9860 free(commit_id);
9861 free(cwd);
9862 free(repo_path);
9863 free(in_repo_path);
9864 if (cmd_argv) {
9865 int i;
9866 for (i = 0; i < argc; i++)
9867 free(cmd_argv[i]);
9868 free(cmd_argv);
9870 tog_free_refs();
9871 return error;
9874 int
9875 main(int argc, char *argv[])
9877 const struct got_error *io_err, *error = NULL;
9878 const struct tog_cmd *cmd = NULL;
9879 int ch, hflag = 0, Vflag = 0;
9880 char **cmd_argv = NULL;
9881 static const struct option longopts[] = {
9882 { "version", no_argument, NULL, 'V' },
9883 { NULL, 0, NULL, 0}
9885 char *diff_algo_str = NULL;
9886 const char *test_script_path;
9888 setlocale(LC_CTYPE, "");
9891 * Test mode init must happen before pledge() because "tty" will
9892 * not allow TTY-related ioctls to occur via regular files.
9894 test_script_path = getenv("TOG_TEST_SCRIPT");
9895 if (test_script_path != NULL) {
9896 error = init_mock_term(test_script_path);
9897 if (error) {
9898 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9899 return 1;
9901 } else if (!isatty(STDIN_FILENO))
9902 errx(1, "standard input is not a tty");
9904 #if !defined(PROFILE)
9905 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9906 NULL) == -1)
9907 err(1, "pledge");
9908 #endif
9910 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9911 switch (ch) {
9912 case 'h':
9913 hflag = 1;
9914 break;
9915 case 'V':
9916 Vflag = 1;
9917 break;
9918 default:
9919 usage(hflag, 1);
9920 /* NOTREACHED */
9924 argc -= optind;
9925 argv += optind;
9926 optind = 1;
9927 optreset = 1;
9929 if (Vflag) {
9930 got_version_print_str();
9931 return 0;
9934 if (argc == 0) {
9935 if (hflag)
9936 usage(hflag, 0);
9937 /* Build an argument vector which runs a default command. */
9938 cmd = &tog_commands[0];
9939 argc = 1;
9940 cmd_argv = make_argv(argc, cmd->name);
9941 } else {
9942 size_t i;
9944 /* Did the user specify a command? */
9945 for (i = 0; i < nitems(tog_commands); i++) {
9946 if (strncmp(tog_commands[i].name, argv[0],
9947 strlen(argv[0])) == 0) {
9948 cmd = &tog_commands[i];
9949 break;
9954 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9955 if (diff_algo_str) {
9956 if (strcasecmp(diff_algo_str, "patience") == 0)
9957 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9958 if (strcasecmp(diff_algo_str, "myers") == 0)
9959 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9962 if (cmd == NULL) {
9963 if (argc != 1)
9964 usage(0, 1);
9965 /* No command specified; try log with a path */
9966 error = tog_log_with_path(argc, argv);
9967 } else {
9968 if (hflag)
9969 cmd->cmd_usage();
9970 else
9971 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9974 if (using_mock_io) {
9975 io_err = tog_io_close();
9976 if (error == NULL)
9977 error = io_err;
9979 endwin();
9980 if (cmd_argv) {
9981 int i;
9982 for (i = 0; i < argc; i++)
9983 free(cmd_argv[i]);
9984 free(cmd_argv);
9987 if (error && error->code != GOT_ERR_CANCELLED &&
9988 error->code != GOT_ERR_EOF &&
9989 error->code != GOT_ERR_PRIVSEP_EXIT &&
9990 error->code != GOT_ERR_PRIVSEP_PIPE &&
9991 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9992 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9993 return 0;