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>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_diff.h"
50 #include "got_opentemp.h"
51 #include "got_utf8.h"
52 #include "got_cancel.h"
53 #include "got_commit_graph.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_path.h"
57 #include "got_worktree.h"
58 #include "got_keyword.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 struct {
154 struct got_object_id *id;
155 int idx;
156 char marker;
157 } tog_base_commit;
158 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
160 static const struct got_error *
161 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
162 struct got_reference* re2)
164 const char *name1 = got_ref_get_name(re1);
165 const char *name2 = got_ref_get_name(re2);
166 int isbackup1, isbackup2;
168 /* Sort backup refs towards the bottom of the list. */
169 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
170 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
171 if (!isbackup1 && isbackup2) {
172 *cmp = -1;
173 return NULL;
174 } else if (isbackup1 && !isbackup2) {
175 *cmp = 1;
176 return NULL;
179 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
180 return NULL;
183 static const struct got_error *
184 tog_load_refs(struct got_repository *repo, int sort_by_date)
186 const struct got_error *err;
188 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
189 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
190 repo);
191 if (err)
192 return err;
194 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
195 repo);
198 static void
199 tog_free_refs(void)
201 if (tog_refs_idmap) {
202 got_reflist_object_id_map_free(tog_refs_idmap);
203 tog_refs_idmap = NULL;
205 got_ref_list_free(&tog_refs);
208 static const struct got_error *
209 add_color(struct tog_colors *colors, const char *pattern,
210 int idx, short color)
212 const struct got_error *err = NULL;
213 struct tog_color *tc;
214 int regerr = 0;
216 if (idx < 1 || idx > COLOR_PAIRS - 1)
217 return NULL;
219 init_pair(idx, color, -1);
221 tc = calloc(1, sizeof(*tc));
222 if (tc == NULL)
223 return got_error_from_errno("calloc");
224 regerr = regcomp(&tc->regex, pattern,
225 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
226 if (regerr) {
227 static char regerr_msg[512];
228 static char err_msg[512];
229 regerror(regerr, &tc->regex, regerr_msg,
230 sizeof(regerr_msg));
231 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
232 regerr_msg);
233 err = got_error_msg(GOT_ERR_REGEX, err_msg);
234 free(tc);
235 return err;
237 tc->colorpair = idx;
238 STAILQ_INSERT_HEAD(colors, tc, entry);
239 return NULL;
242 static void
243 free_colors(struct tog_colors *colors)
245 struct tog_color *tc;
247 while (!STAILQ_EMPTY(colors)) {
248 tc = STAILQ_FIRST(colors);
249 STAILQ_REMOVE_HEAD(colors, entry);
250 regfree(&tc->regex);
251 free(tc);
255 static struct tog_color *
256 get_color(struct tog_colors *colors, int colorpair)
258 struct tog_color *tc = NULL;
260 STAILQ_FOREACH(tc, colors, entry) {
261 if (tc->colorpair == colorpair)
262 return tc;
265 return NULL;
268 static int
269 default_color_value(const char *envvar)
271 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
272 return COLOR_MAGENTA;
273 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
274 return COLOR_CYAN;
275 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
276 return COLOR_YELLOW;
277 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
278 return COLOR_GREEN;
279 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
280 return COLOR_MAGENTA;
281 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
282 return COLOR_MAGENTA;
283 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
284 return COLOR_CYAN;
285 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
286 return COLOR_GREEN;
287 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
288 return COLOR_GREEN;
289 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
290 return COLOR_CYAN;
291 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
292 return COLOR_YELLOW;
293 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
294 return COLOR_GREEN;
295 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
296 return COLOR_MAGENTA;
297 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
298 return COLOR_YELLOW;
299 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
300 return COLOR_CYAN;
302 return -1;
305 static int
306 get_color_value(const char *envvar)
308 const char *val = getenv(envvar);
310 if (val == NULL)
311 return default_color_value(envvar);
313 if (strcasecmp(val, "black") == 0)
314 return COLOR_BLACK;
315 if (strcasecmp(val, "red") == 0)
316 return COLOR_RED;
317 if (strcasecmp(val, "green") == 0)
318 return COLOR_GREEN;
319 if (strcasecmp(val, "yellow") == 0)
320 return COLOR_YELLOW;
321 if (strcasecmp(val, "blue") == 0)
322 return COLOR_BLUE;
323 if (strcasecmp(val, "magenta") == 0)
324 return COLOR_MAGENTA;
325 if (strcasecmp(val, "cyan") == 0)
326 return COLOR_CYAN;
327 if (strcasecmp(val, "white") == 0)
328 return COLOR_WHITE;
329 if (strcasecmp(val, "default") == 0)
330 return -1;
332 return default_color_value(envvar);
335 struct tog_diff_view_state {
336 struct got_object_id *id1, *id2;
337 const char *label1, *label2;
338 FILE *f, *f1, *f2;
339 int fd1, fd2;
340 int lineno;
341 int first_displayed_line;
342 int last_displayed_line;
343 int eof;
344 int diff_context;
345 int ignore_whitespace;
346 int force_text_diff;
347 struct got_repository *repo;
348 struct got_diff_line *lines;
349 size_t nlines;
350 int matched_line;
351 int selected_line;
353 /* passed from log or blame view; may be NULL */
354 struct tog_view *parent_view;
355 };
357 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
358 static volatile sig_atomic_t tog_thread_error;
360 struct tog_log_thread_args {
361 pthread_cond_t need_commits;
362 pthread_cond_t commit_loaded;
363 int commits_needed;
364 int load_all;
365 struct got_commit_graph *graph;
366 struct commit_queue *real_commits;
367 const char *in_repo_path;
368 struct got_object_id *start_id;
369 struct got_repository *repo;
370 int *pack_fds;
371 int log_complete;
372 pthread_cond_t log_loaded;
373 sig_atomic_t *quit;
374 struct commit_queue_entry **first_displayed_entry;
375 struct commit_queue_entry **selected_entry;
376 int *searching;
377 int *search_next_done;
378 regex_t *regex;
379 int *limiting;
380 int limit_match;
381 regex_t *limit_regex;
382 struct commit_queue *limit_commits;
383 struct got_worktree *worktree;
384 int need_commit_marker;
385 };
387 struct tog_log_view_state {
388 struct commit_queue *commits;
389 struct commit_queue_entry *first_displayed_entry;
390 struct commit_queue_entry *last_displayed_entry;
391 struct commit_queue_entry *selected_entry;
392 struct commit_queue real_commits;
393 int selected;
394 char *in_repo_path;
395 char *head_ref_name;
396 int log_branches;
397 struct got_repository *repo;
398 struct got_object_id *start_id;
399 sig_atomic_t quit;
400 pthread_t thread;
401 struct tog_log_thread_args thread_args;
402 struct commit_queue_entry *matched_entry;
403 struct commit_queue_entry *search_entry;
404 struct tog_colors colors;
405 int use_committer;
406 int limit_view;
407 regex_t limit_regex;
408 struct commit_queue limit_commits;
409 };
411 #define TOG_COLOR_DIFF_MINUS 1
412 #define TOG_COLOR_DIFF_PLUS 2
413 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
414 #define TOG_COLOR_DIFF_META 4
415 #define TOG_COLOR_TREE_SUBMODULE 5
416 #define TOG_COLOR_TREE_SYMLINK 6
417 #define TOG_COLOR_TREE_DIRECTORY 7
418 #define TOG_COLOR_TREE_EXECUTABLE 8
419 #define TOG_COLOR_COMMIT 9
420 #define TOG_COLOR_AUTHOR 10
421 #define TOG_COLOR_DATE 11
422 #define TOG_COLOR_REFS_HEADS 12
423 #define TOG_COLOR_REFS_TAGS 13
424 #define TOG_COLOR_REFS_REMOTES 14
425 #define TOG_COLOR_REFS_BACKUP 15
427 struct tog_blame_cb_args {
428 struct tog_blame_line *lines; /* one per line */
429 int nlines;
431 struct tog_view *view;
432 struct got_object_id *commit_id;
433 int *quit;
434 };
436 struct tog_blame_thread_args {
437 const char *path;
438 struct got_repository *repo;
439 struct tog_blame_cb_args *cb_args;
440 int *complete;
441 got_cancel_cb cancel_cb;
442 void *cancel_arg;
443 pthread_cond_t blame_complete;
444 };
446 struct tog_blame {
447 FILE *f;
448 off_t filesize;
449 struct tog_blame_line *lines;
450 int nlines;
451 off_t *line_offsets;
452 pthread_t thread;
453 struct tog_blame_thread_args thread_args;
454 struct tog_blame_cb_args cb_args;
455 const char *path;
456 int *pack_fds;
457 };
459 struct tog_blame_view_state {
460 int first_displayed_line;
461 int last_displayed_line;
462 int selected_line;
463 int last_diffed_line;
464 int blame_complete;
465 int eof;
466 int done;
467 struct got_object_id_queue blamed_commits;
468 struct got_object_qid *blamed_commit;
469 char *path;
470 struct got_repository *repo;
471 struct got_object_id *commit_id;
472 struct got_object_id *id_to_log;
473 struct tog_blame blame;
474 int matched_line;
475 struct tog_colors colors;
476 };
478 struct tog_parent_tree {
479 TAILQ_ENTRY(tog_parent_tree) entry;
480 struct got_tree_object *tree;
481 struct got_tree_entry *first_displayed_entry;
482 struct got_tree_entry *selected_entry;
483 int selected;
484 };
486 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
488 struct tog_tree_view_state {
489 char *tree_label;
490 struct got_object_id *commit_id;/* commit which this tree belongs to */
491 struct got_tree_object *root; /* the commit's root tree entry */
492 struct got_tree_object *tree; /* currently displayed (sub-)tree */
493 struct got_tree_entry *first_displayed_entry;
494 struct got_tree_entry *last_displayed_entry;
495 struct got_tree_entry *selected_entry;
496 int ndisplayed, selected, show_ids;
497 struct tog_parent_trees parents; /* parent trees of current sub-tree */
498 char *head_ref_name;
499 struct got_repository *repo;
500 struct got_tree_entry *matched_entry;
501 struct tog_colors colors;
502 };
504 struct tog_reflist_entry {
505 TAILQ_ENTRY(tog_reflist_entry) entry;
506 struct got_reference *ref;
507 int idx;
508 };
510 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
512 struct tog_ref_view_state {
513 struct tog_reflist_head refs;
514 struct tog_reflist_entry *first_displayed_entry;
515 struct tog_reflist_entry *last_displayed_entry;
516 struct tog_reflist_entry *selected_entry;
517 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
518 struct got_repository *repo;
519 struct tog_reflist_entry *matched_entry;
520 struct tog_colors colors;
521 };
523 struct tog_help_view_state {
524 FILE *f;
525 off_t *line_offsets;
526 size_t nlines;
527 int lineno;
528 int first_displayed_line;
529 int last_displayed_line;
530 int eof;
531 int matched_line;
532 int selected_line;
533 int all;
534 enum tog_keymap_type type;
535 };
537 #define GENERATE_HELP \
538 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
539 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
540 KEY_("k C-p Up", "Move cursor or page up one line"), \
541 KEY_("j C-n Down", "Move cursor or page down one line"), \
542 KEY_("C-b b PgUp", "Scroll the view up one page"), \
543 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
544 KEY_("C-u u", "Scroll the view up one half page"), \
545 KEY_("C-d d", "Scroll the view down one half page"), \
546 KEY_("g", "Go to line N (default: first line)"), \
547 KEY_("Home =", "Go to the first line"), \
548 KEY_("G", "Go to line N (default: last line)"), \
549 KEY_("End *", "Go to the last line"), \
550 KEY_("l Right", "Scroll the view right"), \
551 KEY_("h Left", "Scroll the view left"), \
552 KEY_("$", "Scroll view to the rightmost position"), \
553 KEY_("0", "Scroll view to the leftmost position"), \
554 KEY_("-", "Decrease size of the focussed split"), \
555 KEY_("+", "Increase size of the focussed split"), \
556 KEY_("Tab", "Switch focus between views"), \
557 KEY_("F", "Toggle fullscreen mode"), \
558 KEY_("S", "Switch split-screen layout"), \
559 KEY_("/", "Open prompt to enter search term"), \
560 KEY_("n", "Find next line/token matching the current search term"), \
561 KEY_("N", "Find previous line/token matching the current search term"),\
562 KEY_("q", "Quit the focussed view; Quit help screen"), \
563 KEY_("Q", "Quit tog"), \
565 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
566 KEY_("< ,", "Move cursor up one commit"), \
567 KEY_("> .", "Move cursor down one commit"), \
568 KEY_("Enter", "Open diff view of the selected commit"), \
569 KEY_("B", "Reload the log view and toggle display of merged commits"), \
570 KEY_("R", "Open ref view of all repository references"), \
571 KEY_("T", "Display tree view of the repository from the selected" \
572 " commit"), \
573 KEY_("@", "Toggle between displaying author and committer name"), \
574 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
575 KEY_("C-g Backspace", "Cancel current search or log operation"), \
576 KEY_("C-l", "Reload the log view with new commits in the repository"), \
578 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
579 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
580 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
581 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
582 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
583 " data"), \
584 KEY_("(", "Go to the previous file in the diff"), \
585 KEY_(")", "Go to the next file in the diff"), \
586 KEY_("{", "Go to the previous hunk in the diff"), \
587 KEY_("}", "Go to the next hunk in the diff"), \
588 KEY_("[", "Decrease the number of context lines"), \
589 KEY_("]", "Increase the number of context lines"), \
590 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
592 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
593 KEY_("Enter", "Display diff view of the selected line's commit"), \
594 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
595 KEY_("L", "Open log view for the currently selected annotated line"), \
596 KEY_("C", "Reload view with the previously blamed commit"), \
597 KEY_("c", "Reload view with the version of the file found in the" \
598 " selected line's commit"), \
599 KEY_("p", "Reload view with the version of the file found in the" \
600 " selected line's parent commit"), \
602 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
603 KEY_("Enter", "Enter selected directory or open blame view of the" \
604 " selected file"), \
605 KEY_("L", "Open log view for the selected entry"), \
606 KEY_("R", "Open ref view of all repository references"), \
607 KEY_("i", "Show object IDs for all tree entries"), \
608 KEY_("Backspace", "Return to the parent directory"), \
610 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
611 KEY_("Enter", "Display log view of the selected reference"), \
612 KEY_("T", "Display tree view of the selected reference"), \
613 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
614 KEY_("m", "Toggle display of last modified date for each reference"), \
615 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
616 KEY_("C-l", "Reload view with all repository references")
618 struct tog_key_map {
619 const char *keys;
620 const char *info;
621 enum tog_keymap_type type;
622 };
624 /* curses io for tog regress */
625 struct tog_io {
626 FILE *cin;
627 FILE *cout;
628 FILE *f;
629 FILE *sdump;
630 char *input_str;
631 int wait_for_ui;
632 } tog_io;
633 static int using_mock_io;
635 #define TOG_KEY_SCRDUMP SHRT_MIN
637 /*
638 * We implement two types of views: parent views and child views.
640 * The 'Tab' key switches focus between a parent view and its child view.
641 * Child views are shown side-by-side to their parent view, provided
642 * there is enough screen estate.
644 * When a new view is opened from within a parent view, this new view
645 * becomes a child view of the parent view, replacing any existing child.
647 * When a new view is opened from within a child view, this new view
648 * becomes a parent view which will obscure the views below until the
649 * user quits the new parent view by typing 'q'.
651 * This list of views contains parent views only.
652 * Child views are only pointed to by their parent view.
653 */
654 TAILQ_HEAD(tog_view_list_head, tog_view);
656 struct tog_view {
657 TAILQ_ENTRY(tog_view) entry;
658 WINDOW *window;
659 PANEL *panel;
660 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
661 int resized_y, resized_x; /* begin_y/x based on user resizing */
662 int maxx, x; /* max column and current start column */
663 int lines, cols; /* copies of LINES and COLS */
664 int nscrolled, offset; /* lines scrolled and hsplit line offset */
665 int gline, hiline; /* navigate to and highlight this nG line */
666 int ch, count; /* current keymap and count prefix */
667 int resized; /* set when in a resize event */
668 int focussed; /* Only set on one parent or child view at a time. */
669 int dying;
670 struct tog_view *parent;
671 struct tog_view *child;
673 /*
674 * This flag is initially set on parent views when a new child view
675 * is created. It gets toggled when the 'Tab' key switches focus
676 * between parent and child.
677 * The flag indicates whether focus should be passed on to our child
678 * view if this parent view gets picked for focus after another parent
679 * view was closed. This prevents child views from losing focus in such
680 * situations.
681 */
682 int focus_child;
684 enum tog_view_mode mode;
685 /* type-specific state */
686 enum tog_view_type type;
687 union {
688 struct tog_diff_view_state diff;
689 struct tog_log_view_state log;
690 struct tog_blame_view_state blame;
691 struct tog_tree_view_state tree;
692 struct tog_ref_view_state ref;
693 struct tog_help_view_state help;
694 } state;
696 const struct got_error *(*show)(struct tog_view *);
697 const struct got_error *(*input)(struct tog_view **,
698 struct tog_view *, int);
699 const struct got_error *(*reset)(struct tog_view *);
700 const struct got_error *(*resize)(struct tog_view *, int);
701 const struct got_error *(*close)(struct tog_view *);
703 const struct got_error *(*search_start)(struct tog_view *);
704 const struct got_error *(*search_next)(struct tog_view *);
705 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
706 int **, int **, int **, int **);
707 int search_started;
708 int searching;
709 #define TOG_SEARCH_FORWARD 1
710 #define TOG_SEARCH_BACKWARD 2
711 int search_next_done;
712 #define TOG_SEARCH_HAVE_MORE 1
713 #define TOG_SEARCH_NO_MORE 2
714 #define TOG_SEARCH_HAVE_NONE 3
715 regex_t regex;
716 regmatch_t regmatch;
717 const char *action;
718 };
720 static const struct got_error *open_diff_view(struct tog_view *,
721 struct got_object_id *, struct got_object_id *,
722 const char *, const char *, int, int, int, struct tog_view *,
723 struct got_repository *);
724 static const struct got_error *show_diff_view(struct tog_view *);
725 static const struct got_error *input_diff_view(struct tog_view **,
726 struct tog_view *, int);
727 static const struct got_error *reset_diff_view(struct tog_view *);
728 static const struct got_error* close_diff_view(struct tog_view *);
729 static const struct got_error *search_start_diff_view(struct tog_view *);
730 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
731 size_t *, int **, int **, int **, int **);
732 static const struct got_error *search_next_view_match(struct tog_view *);
734 static const struct got_error *open_log_view(struct tog_view *,
735 struct got_object_id *, struct got_repository *,
736 const char *, const char *, int, struct got_worktree *);
737 static const struct got_error * show_log_view(struct tog_view *);
738 static const struct got_error *input_log_view(struct tog_view **,
739 struct tog_view *, int);
740 static const struct got_error *resize_log_view(struct tog_view *, int);
741 static const struct got_error *close_log_view(struct tog_view *);
742 static const struct got_error *search_start_log_view(struct tog_view *);
743 static const struct got_error *search_next_log_view(struct tog_view *);
745 static const struct got_error *open_blame_view(struct tog_view *, char *,
746 struct got_object_id *, struct got_repository *);
747 static const struct got_error *show_blame_view(struct tog_view *);
748 static const struct got_error *input_blame_view(struct tog_view **,
749 struct tog_view *, int);
750 static const struct got_error *reset_blame_view(struct tog_view *);
751 static const struct got_error *close_blame_view(struct tog_view *);
752 static const struct got_error *search_start_blame_view(struct tog_view *);
753 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
754 size_t *, int **, int **, int **, int **);
756 static const struct got_error *open_tree_view(struct tog_view *,
757 struct got_object_id *, const char *, struct got_repository *);
758 static const struct got_error *show_tree_view(struct tog_view *);
759 static const struct got_error *input_tree_view(struct tog_view **,
760 struct tog_view *, int);
761 static const struct got_error *close_tree_view(struct tog_view *);
762 static const struct got_error *search_start_tree_view(struct tog_view *);
763 static const struct got_error *search_next_tree_view(struct tog_view *);
765 static const struct got_error *open_ref_view(struct tog_view *,
766 struct got_repository *);
767 static const struct got_error *show_ref_view(struct tog_view *);
768 static const struct got_error *input_ref_view(struct tog_view **,
769 struct tog_view *, int);
770 static const struct got_error *close_ref_view(struct tog_view *);
771 static const struct got_error *search_start_ref_view(struct tog_view *);
772 static const struct got_error *search_next_ref_view(struct tog_view *);
774 static const struct got_error *open_help_view(struct tog_view *,
775 struct tog_view *);
776 static const struct got_error *show_help_view(struct tog_view *);
777 static const struct got_error *input_help_view(struct tog_view **,
778 struct tog_view *, int);
779 static const struct got_error *reset_help_view(struct tog_view *);
780 static const struct got_error* close_help_view(struct tog_view *);
781 static const struct got_error *search_start_help_view(struct tog_view *);
782 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
783 size_t *, int **, int **, int **, int **);
785 static volatile sig_atomic_t tog_sigwinch_received;
786 static volatile sig_atomic_t tog_sigpipe_received;
787 static volatile sig_atomic_t tog_sigcont_received;
788 static volatile sig_atomic_t tog_sigint_received;
789 static volatile sig_atomic_t tog_sigterm_received;
791 static void
792 tog_sigwinch(int signo)
794 tog_sigwinch_received = 1;
797 static void
798 tog_sigpipe(int signo)
800 tog_sigpipe_received = 1;
803 static void
804 tog_sigcont(int signo)
806 tog_sigcont_received = 1;
809 static void
810 tog_sigint(int signo)
812 tog_sigint_received = 1;
815 static void
816 tog_sigterm(int signo)
818 tog_sigterm_received = 1;
821 static int
822 tog_fatal_signal_received(void)
824 return (tog_sigpipe_received ||
825 tog_sigint_received || tog_sigterm_received);
828 static const struct got_error *
829 view_close(struct tog_view *view)
831 const struct got_error *err = NULL, *child_err = NULL;
833 if (view->child) {
834 child_err = view_close(view->child);
835 view->child = NULL;
837 if (view->close)
838 err = view->close(view);
839 if (view->panel)
840 del_panel(view->panel);
841 if (view->window)
842 delwin(view->window);
843 free(view);
844 return err ? err : child_err;
847 static struct tog_view *
848 view_open(int nlines, int ncols, int begin_y, int begin_x,
849 enum tog_view_type type)
851 struct tog_view *view = calloc(1, sizeof(*view));
853 if (view == NULL)
854 return NULL;
856 view->type = type;
857 view->lines = LINES;
858 view->cols = COLS;
859 view->nlines = nlines ? nlines : LINES - begin_y;
860 view->ncols = ncols ? ncols : COLS - begin_x;
861 view->begin_y = begin_y;
862 view->begin_x = begin_x;
863 view->window = newwin(nlines, ncols, begin_y, begin_x);
864 if (view->window == NULL) {
865 view_close(view);
866 return NULL;
868 view->panel = new_panel(view->window);
869 if (view->panel == NULL ||
870 set_panel_userptr(view->panel, view) != OK) {
871 view_close(view);
872 return NULL;
875 keypad(view->window, TRUE);
876 return view;
879 static int
880 view_split_begin_x(int begin_x)
882 if (begin_x > 0 || COLS < 120)
883 return 0;
884 return (COLS - MAX(COLS / 2, 80));
887 /* XXX Stub till we decide what to do. */
888 static int
889 view_split_begin_y(int lines)
891 return lines * HSPLIT_SCALE;
894 static const struct got_error *view_resize(struct tog_view *);
896 static const struct got_error *
897 view_splitscreen(struct tog_view *view)
899 const struct got_error *err = NULL;
901 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
902 if (view->resized_y && view->resized_y < view->lines)
903 view->begin_y = view->resized_y;
904 else
905 view->begin_y = view_split_begin_y(view->nlines);
906 view->begin_x = 0;
907 } else if (!view->resized) {
908 if (view->resized_x && view->resized_x < view->cols - 1 &&
909 view->cols > 119)
910 view->begin_x = view->resized_x;
911 else
912 view->begin_x = view_split_begin_x(0);
913 view->begin_y = 0;
915 view->nlines = LINES - view->begin_y;
916 view->ncols = COLS - view->begin_x;
917 view->lines = LINES;
918 view->cols = COLS;
919 err = view_resize(view);
920 if (err)
921 return err;
923 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
924 view->parent->nlines = view->begin_y;
926 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
927 return got_error_from_errno("mvwin");
929 return NULL;
932 static const struct got_error *
933 view_fullscreen(struct tog_view *view)
935 const struct got_error *err = NULL;
937 view->begin_x = 0;
938 view->begin_y = view->resized ? view->begin_y : 0;
939 view->nlines = view->resized ? view->nlines : LINES;
940 view->ncols = COLS;
941 view->lines = LINES;
942 view->cols = COLS;
943 err = view_resize(view);
944 if (err)
945 return err;
947 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
948 return got_error_from_errno("mvwin");
950 return NULL;
953 static int
954 view_is_parent_view(struct tog_view *view)
956 return view->parent == NULL;
959 static int
960 view_is_splitscreen(struct tog_view *view)
962 return view->begin_x > 0 || view->begin_y > 0;
965 static int
966 view_is_fullscreen(struct tog_view *view)
968 return view->nlines == LINES && view->ncols == COLS;
971 static int
972 view_is_hsplit_top(struct tog_view *view)
974 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
975 view_is_splitscreen(view->child);
978 static void
979 view_border(struct tog_view *view)
981 PANEL *panel;
982 const struct tog_view *view_above;
984 if (view->parent)
985 return view_border(view->parent);
987 panel = panel_above(view->panel);
988 if (panel == NULL)
989 return;
991 view_above = panel_userptr(panel);
992 if (view->mode == TOG_VIEW_SPLIT_HRZN)
993 mvwhline(view->window, view_above->begin_y - 1,
994 view->begin_x, ACS_HLINE, view->ncols);
995 else
996 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
997 ACS_VLINE, view->nlines);
1000 static const struct got_error *view_init_hsplit(struct tog_view *, int);
1001 static const struct got_error *request_log_commits(struct tog_view *);
1002 static const struct got_error *offset_selection_down(struct tog_view *);
1003 static void offset_selection_up(struct tog_view *);
1004 static void view_get_split(struct tog_view *, int *, int *);
1006 static const struct got_error *
1007 view_resize(struct tog_view *view)
1009 const struct got_error *err = NULL;
1010 int dif, nlines, ncols;
1012 dif = LINES - view->lines; /* line difference */
1014 if (view->lines > LINES)
1015 nlines = view->nlines - (view->lines - LINES);
1016 else
1017 nlines = view->nlines + (LINES - view->lines);
1018 if (view->cols > COLS)
1019 ncols = view->ncols - (view->cols - COLS);
1020 else
1021 ncols = view->ncols + (COLS - view->cols);
1023 if (view->child) {
1024 int hs = view->child->begin_y;
1026 if (!view_is_fullscreen(view))
1027 view->child->begin_x = view_split_begin_x(view->begin_x);
1028 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1029 view->child->begin_x == 0) {
1030 ncols = COLS;
1032 view_fullscreen(view->child);
1033 if (view->child->focussed)
1034 show_panel(view->child->panel);
1035 else
1036 show_panel(view->panel);
1037 } else {
1038 ncols = view->child->begin_x;
1040 view_splitscreen(view->child);
1041 show_panel(view->child->panel);
1044 * XXX This is ugly and needs to be moved into the above
1045 * logic but "works" for now and my attempts at moving it
1046 * break either 'tab' or 'F' key maps in horizontal splits.
1048 if (hs) {
1049 err = view_splitscreen(view->child);
1050 if (err)
1051 return err;
1052 if (dif < 0) { /* top split decreased */
1053 err = offset_selection_down(view);
1054 if (err)
1055 return err;
1057 view_border(view);
1058 update_panels();
1059 doupdate();
1060 show_panel(view->child->panel);
1061 nlines = view->nlines;
1063 } else if (view->parent == NULL)
1064 ncols = COLS;
1066 if (view->resize && dif > 0) {
1067 err = view->resize(view, dif);
1068 if (err)
1069 return err;
1072 if (wresize(view->window, nlines, ncols) == ERR)
1073 return got_error_from_errno("wresize");
1074 if (replace_panel(view->panel, view->window) == ERR)
1075 return got_error_from_errno("replace_panel");
1076 wclear(view->window);
1078 view->nlines = nlines;
1079 view->ncols = ncols;
1080 view->lines = LINES;
1081 view->cols = COLS;
1083 return NULL;
1086 static const struct got_error *
1087 resize_log_view(struct tog_view *view, int increase)
1089 struct tog_log_view_state *s = &view->state.log;
1090 const struct got_error *err = NULL;
1091 int n = 0;
1093 if (s->selected_entry)
1094 n = s->selected_entry->idx + view->lines - s->selected;
1097 * Request commits to account for the increased
1098 * height so we have enough to populate the view.
1100 if (s->commits->ncommits < n) {
1101 view->nscrolled = n - s->commits->ncommits + increase + 1;
1102 err = request_log_commits(view);
1105 return err;
1108 static void
1109 view_adjust_offset(struct tog_view *view, int n)
1111 if (n == 0)
1112 return;
1114 if (view->parent && view->parent->offset) {
1115 if (view->parent->offset + n >= 0)
1116 view->parent->offset += n;
1117 else
1118 view->parent->offset = 0;
1119 } else if (view->offset) {
1120 if (view->offset - n >= 0)
1121 view->offset -= n;
1122 else
1123 view->offset = 0;
1127 static const struct got_error *
1128 view_resize_split(struct tog_view *view, int resize)
1130 const struct got_error *err = NULL;
1131 struct tog_view *v = NULL;
1133 if (view->parent)
1134 v = view->parent;
1135 else
1136 v = view;
1138 if (!v->child || !view_is_splitscreen(v->child))
1139 return NULL;
1141 v->resized = v->child->resized = resize; /* lock for resize event */
1143 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1144 if (v->child->resized_y)
1145 v->child->begin_y = v->child->resized_y;
1146 if (view->parent)
1147 v->child->begin_y -= resize;
1148 else
1149 v->child->begin_y += resize;
1150 if (v->child->begin_y < 3) {
1151 view->count = 0;
1152 v->child->begin_y = 3;
1153 } else if (v->child->begin_y > LINES - 1) {
1154 view->count = 0;
1155 v->child->begin_y = LINES - 1;
1157 v->ncols = COLS;
1158 v->child->ncols = COLS;
1159 view_adjust_offset(view, resize);
1160 err = view_init_hsplit(v, v->child->begin_y);
1161 if (err)
1162 return err;
1163 v->child->resized_y = v->child->begin_y;
1164 } else {
1165 if (v->child->resized_x)
1166 v->child->begin_x = v->child->resized_x;
1167 if (view->parent)
1168 v->child->begin_x -= resize;
1169 else
1170 v->child->begin_x += resize;
1171 if (v->child->begin_x < 11) {
1172 view->count = 0;
1173 v->child->begin_x = 11;
1174 } else if (v->child->begin_x > COLS - 1) {
1175 view->count = 0;
1176 v->child->begin_x = COLS - 1;
1178 v->child->resized_x = v->child->begin_x;
1181 v->child->mode = v->mode;
1182 v->child->nlines = v->lines - v->child->begin_y;
1183 v->child->ncols = v->cols - v->child->begin_x;
1184 v->focus_child = 1;
1186 err = view_fullscreen(v);
1187 if (err)
1188 return err;
1189 err = view_splitscreen(v->child);
1190 if (err)
1191 return err;
1193 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1194 err = offset_selection_down(v->child);
1195 if (err)
1196 return err;
1199 if (v->resize)
1200 err = v->resize(v, 0);
1201 else if (v->child->resize)
1202 err = v->child->resize(v->child, 0);
1204 v->resized = v->child->resized = 0;
1206 return err;
1209 static void
1210 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1212 struct tog_view *v = src->child ? src->child : src;
1214 dst->resized_x = v->resized_x;
1215 dst->resized_y = v->resized_y;
1218 static const struct got_error *
1219 view_close_child(struct tog_view *view)
1221 const struct got_error *err = NULL;
1223 if (view->child == NULL)
1224 return NULL;
1226 err = view_close(view->child);
1227 view->child = NULL;
1228 return err;
1231 static const struct got_error *
1232 view_set_child(struct tog_view *view, struct tog_view *child)
1234 const struct got_error *err = NULL;
1236 view->child = child;
1237 child->parent = view;
1239 err = view_resize(view);
1240 if (err)
1241 return err;
1243 if (view->child->resized_x || view->child->resized_y)
1244 err = view_resize_split(view, 0);
1246 return err;
1249 static const struct got_error *view_dispatch_request(struct tog_view **,
1250 struct tog_view *, enum tog_view_type, int, int);
1252 static const struct got_error *
1253 view_request_new(struct tog_view **requested, struct tog_view *view,
1254 enum tog_view_type request)
1256 struct tog_view *new_view = NULL;
1257 const struct got_error *err;
1258 int y = 0, x = 0;
1260 *requested = NULL;
1262 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1263 view_get_split(view, &y, &x);
1265 err = view_dispatch_request(&new_view, view, request, y, x);
1266 if (err)
1267 return err;
1269 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1270 request != TOG_VIEW_HELP) {
1271 err = view_init_hsplit(view, y);
1272 if (err)
1273 return err;
1276 view->focussed = 0;
1277 new_view->focussed = 1;
1278 new_view->mode = view->mode;
1279 new_view->nlines = request == TOG_VIEW_HELP ?
1280 view->lines : view->lines - y;
1282 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1283 view_transfer_size(new_view, view);
1284 err = view_close_child(view);
1285 if (err)
1286 return err;
1287 err = view_set_child(view, new_view);
1288 if (err)
1289 return err;
1290 view->focus_child = 1;
1291 } else
1292 *requested = new_view;
1294 return NULL;
1297 static void
1298 tog_resizeterm(void)
1300 int cols, lines;
1301 struct winsize size;
1303 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1304 cols = 80; /* Default */
1305 lines = 24;
1306 } else {
1307 cols = size.ws_col;
1308 lines = size.ws_row;
1310 resize_term(lines, cols);
1313 static const struct got_error *
1314 view_search_start(struct tog_view *view, int fast_refresh)
1316 const struct got_error *err = NULL;
1317 struct tog_view *v = view;
1318 char pattern[1024];
1319 int ret;
1321 if (view->search_started) {
1322 regfree(&view->regex);
1323 view->searching = 0;
1324 memset(&view->regmatch, 0, sizeof(view->regmatch));
1326 view->search_started = 0;
1328 if (view->nlines < 1)
1329 return NULL;
1331 if (view_is_hsplit_top(view))
1332 v = view->child;
1333 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1334 v = view->parent;
1336 if (tog_io.input_str != NULL) {
1337 if (strlcpy(pattern, tog_io.input_str, sizeof(pattern)) >=
1338 sizeof(pattern))
1339 return got_error(GOT_ERR_NO_SPACE);
1340 } else {
1341 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1342 wclrtoeol(v->window);
1343 nodelay(v->window, FALSE); /* block for search term input */
1344 nocbreak();
1345 echo();
1346 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1347 wrefresh(v->window);
1348 cbreak();
1349 noecho();
1350 nodelay(v->window, TRUE);
1351 if (!fast_refresh && !using_mock_io)
1352 halfdelay(10);
1353 if (ret == ERR)
1354 return NULL;
1357 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1358 err = view->search_start(view);
1359 if (err) {
1360 regfree(&view->regex);
1361 return err;
1363 view->search_started = 1;
1364 view->searching = TOG_SEARCH_FORWARD;
1365 view->search_next_done = 0;
1366 view->search_next(view);
1369 return NULL;
1372 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1373 static const struct got_error *
1374 switch_split(struct tog_view *view)
1376 const struct got_error *err = NULL;
1377 struct tog_view *v = NULL;
1379 if (view->parent)
1380 v = view->parent;
1381 else
1382 v = view;
1384 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1385 v->mode = TOG_VIEW_SPLIT_VERT;
1386 else
1387 v->mode = TOG_VIEW_SPLIT_HRZN;
1389 if (!v->child)
1390 return NULL;
1391 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1392 v->mode = TOG_VIEW_SPLIT_NONE;
1394 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1395 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1396 v->child->begin_y = v->child->resized_y;
1397 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1398 v->child->begin_x = v->child->resized_x;
1401 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1402 v->ncols = COLS;
1403 v->child->ncols = COLS;
1404 v->child->nscrolled = LINES - v->child->nlines;
1406 err = view_init_hsplit(v, v->child->begin_y);
1407 if (err)
1408 return err;
1410 v->child->mode = v->mode;
1411 v->child->nlines = v->lines - v->child->begin_y;
1412 v->focus_child = 1;
1414 err = view_fullscreen(v);
1415 if (err)
1416 return err;
1417 err = view_splitscreen(v->child);
1418 if (err)
1419 return err;
1421 if (v->mode == TOG_VIEW_SPLIT_NONE)
1422 v->mode = TOG_VIEW_SPLIT_VERT;
1423 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1424 err = offset_selection_down(v);
1425 if (err)
1426 return err;
1427 err = offset_selection_down(v->child);
1428 if (err)
1429 return err;
1430 } else {
1431 offset_selection_up(v);
1432 offset_selection_up(v->child);
1434 if (v->resize)
1435 err = v->resize(v, 0);
1436 else if (v->child->resize)
1437 err = v->child->resize(v->child, 0);
1439 return err;
1443 * Strip trailing whitespace from str starting at byte *n;
1444 * if *n < 0, use strlen(str). Return new str length in *n.
1446 static void
1447 strip_trailing_ws(char *str, int *n)
1449 size_t x = *n;
1451 if (str == NULL || *str == '\0')
1452 return;
1454 if (x < 0)
1455 x = strlen(str);
1457 while (x-- > 0 && isspace((unsigned char)str[x]))
1458 str[x] = '\0';
1460 *n = x + 1;
1464 * Extract visible substring of line y from the curses screen
1465 * and strip trailing whitespace. If vline is set, overwrite
1466 * line[vline] with '|' because the ACS_VLINE character is
1467 * written out as 'x'. Write the line to file f.
1469 static const struct got_error *
1470 view_write_line(FILE *f, int y, int vline)
1472 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1473 int r, w;
1475 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1476 if (r == ERR)
1477 return got_error_fmt(GOT_ERR_RANGE,
1478 "failed to extract line %d", y);
1481 * In some views, lines are padded with blanks to COLS width.
1482 * Strip them so we can diff without the -b flag when testing.
1484 strip_trailing_ws(line, &r);
1486 if (vline > 0)
1487 line[vline] = '|';
1489 w = fprintf(f, "%s\n", line);
1490 if (w != r + 1) /* \n */
1491 return got_ferror(f, GOT_ERR_IO);
1493 return NULL;
1497 * Capture the visible curses screen by writing each line to the
1498 * file at the path set via the TOG_SCR_DUMP environment variable.
1500 static const struct got_error *
1501 screendump(struct tog_view *view)
1503 const struct got_error *err;
1504 int i;
1506 err = got_opentemp_truncate(tog_io.sdump);
1507 if (err)
1508 return err;
1510 if ((view->child && view->child->begin_x) ||
1511 (view->parent && view->begin_x)) {
1512 int ncols = view->child ? view->ncols : view->parent->ncols;
1514 /* vertical splitscreen */
1515 for (i = 0; i < view->nlines; ++i) {
1516 err = view_write_line(tog_io.sdump, i, ncols - 1);
1517 if (err)
1518 goto done;
1520 } else {
1521 int hline = 0;
1523 /* fullscreen or horizontal splitscreen */
1524 if ((view->child && view->child->begin_y) ||
1525 (view->parent && view->begin_y)) /* hsplit */
1526 hline = view->child ?
1527 view->child->begin_y : view->begin_y;
1529 for (i = 0; i < view->lines; i++) {
1530 if (hline && i == hline - 1) {
1531 int c;
1533 /* ACS_HLINE writes out as 'q', overwrite it */
1534 for (c = 0; c < view->cols; ++c)
1535 fputc('-', tog_io.sdump);
1536 fputc('\n', tog_io.sdump);
1537 continue;
1540 err = view_write_line(tog_io.sdump, i, 0);
1541 if (err)
1542 goto done;
1546 done:
1547 return err;
1551 * Compute view->count from numeric input. Assign total to view->count and
1552 * return first non-numeric key entered.
1554 static int
1555 get_compound_key(struct tog_view *view, int c)
1557 struct tog_view *v = view;
1558 int x, n = 0;
1560 if (view_is_hsplit_top(view))
1561 v = view->child;
1562 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1563 v = view->parent;
1565 view->count = 0;
1566 cbreak(); /* block for input */
1567 nodelay(view->window, FALSE);
1568 wmove(v->window, v->nlines - 1, 0);
1569 wclrtoeol(v->window);
1570 waddch(v->window, ':');
1572 do {
1573 x = getcurx(v->window);
1574 if (x != ERR && x < view->ncols) {
1575 waddch(v->window, c);
1576 wrefresh(v->window);
1580 * Don't overflow. Max valid request should be the greatest
1581 * between the longest and total lines; cap at 10 million.
1583 if (n >= 9999999)
1584 n = 9999999;
1585 else
1586 n = n * 10 + (c - '0');
1587 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1589 if (c == 'G' || c == 'g') { /* nG key map */
1590 view->gline = view->hiline = n;
1591 n = 0;
1592 c = 0;
1595 /* Massage excessive or inapplicable values at the input handler. */
1596 view->count = n;
1598 return c;
1601 static void
1602 action_report(struct tog_view *view)
1604 struct tog_view *v = view;
1606 if (view_is_hsplit_top(view))
1607 v = view->child;
1608 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1609 v = view->parent;
1611 wmove(v->window, v->nlines - 1, 0);
1612 wclrtoeol(v->window);
1613 wprintw(v->window, ":%s", view->action);
1614 wrefresh(v->window);
1617 * Clear action status report. Only clear in blame view
1618 * once annotating is complete, otherwise it's too fast.
1620 if (view->type == TOG_VIEW_BLAME) {
1621 if (view->state.blame.blame_complete)
1622 view->action = NULL;
1623 } else
1624 view->action = NULL;
1628 * Read the next line from the test script and assign
1629 * key instruction to *ch. If at EOF, set the *done flag.
1631 static const struct got_error *
1632 tog_read_script_key(FILE *script, struct tog_view *view, int *ch, int *done)
1634 const struct got_error *err = NULL;
1635 char *line = NULL;
1636 size_t linesz = 0;
1637 ssize_t n;
1640 if (view->count && --view->count) {
1641 *ch = view->ch;
1642 return NULL;
1643 } else
1644 *ch = -1;
1646 if ((n = getline(&line, &linesz, script)) == -1) {
1647 if (feof(script)) {
1648 *done = 1;
1649 goto done;
1650 } else {
1651 err = got_ferror(script, GOT_ERR_IO);
1652 goto done;
1656 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1657 tog_io.wait_for_ui = 1;
1658 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1659 *ch = KEY_ENTER;
1660 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1661 *ch = KEY_RIGHT;
1662 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1663 *ch = KEY_LEFT;
1664 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1665 *ch = KEY_DOWN;
1666 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1667 *ch = KEY_UP;
1668 else if (strncasecmp(line, "TAB", 3) == 0)
1669 *ch = '\t';
1670 else if (strncasecmp(line, "SCREENDUMP", 10) == 0)
1671 *ch = TOG_KEY_SCRDUMP;
1672 else if (isdigit((unsigned char)*line)) {
1673 char *t = line;
1675 while (isdigit((unsigned char)*t))
1676 ++t;
1677 view->ch = *ch = *t;
1678 *t = '\0';
1679 /* ignore error, view->count is 0 if instruction is invalid */
1680 view->count = strtonum(line, 0, INT_MAX, NULL);
1681 } else {
1682 *ch = *line;
1683 if (n > 2 && (*ch == '/' || *ch == '&')) {
1684 /* skip leading keymap and trim trailing newline */
1685 tog_io.input_str = strndup(line + 1, n - 2);
1686 if (tog_io.input_str == NULL) {
1687 err = got_error_from_errno("strndup");
1688 goto done;
1693 done:
1694 free(line);
1695 return err;
1698 static const struct got_error *
1699 view_input(struct tog_view **new, int *done, struct tog_view *view,
1700 struct tog_view_list_head *views, int fast_refresh)
1702 const struct got_error *err = NULL;
1703 struct tog_view *v;
1704 int ch, errcode;
1706 *new = NULL;
1708 if (view->action)
1709 action_report(view);
1711 /* Clear "no matches" indicator. */
1712 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1713 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1714 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1715 view->count = 0;
1718 if (view->searching && !view->search_next_done) {
1719 view->search_next(view);
1720 return NULL;
1723 /* Allow threads to make progress while we are waiting for input. */
1724 errcode = pthread_mutex_unlock(&tog_mutex);
1725 if (errcode)
1726 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1728 if (using_mock_io) {
1729 err = tog_read_script_key(tog_io.f, view, &ch, done);
1730 if (err) {
1731 errcode = pthread_mutex_lock(&tog_mutex);
1732 return err;
1734 } else if (view->count && --view->count) {
1735 cbreak();
1736 nodelay(view->window, TRUE);
1737 ch = wgetch(view->window);
1738 /* let C-g or backspace abort unfinished count */
1739 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1740 view->count = 0;
1741 else
1742 ch = view->ch;
1743 } else {
1744 ch = wgetch(view->window);
1745 if (ch >= '1' && ch <= '9')
1746 view->ch = ch = get_compound_key(view, ch);
1748 if (view->hiline && ch != ERR && ch != 0)
1749 view->hiline = 0; /* key pressed, clear line highlight */
1750 nodelay(view->window, TRUE);
1751 errcode = pthread_mutex_lock(&tog_mutex);
1752 if (errcode)
1753 return got_error_set_errno(errcode, "pthread_mutex_lock");
1755 if (tog_sigwinch_received || tog_sigcont_received) {
1756 tog_resizeterm();
1757 tog_sigwinch_received = 0;
1758 tog_sigcont_received = 0;
1759 TAILQ_FOREACH(v, views, entry) {
1760 err = view_resize(v);
1761 if (err)
1762 return err;
1763 err = v->input(new, v, KEY_RESIZE);
1764 if (err)
1765 return err;
1766 if (v->child) {
1767 err = view_resize(v->child);
1768 if (err)
1769 return err;
1770 err = v->child->input(new, v->child,
1771 KEY_RESIZE);
1772 if (err)
1773 return err;
1774 if (v->child->resized_x || v->child->resized_y) {
1775 err = view_resize_split(v, 0);
1776 if (err)
1777 return err;
1783 switch (ch) {
1784 case '?':
1785 case 'H':
1786 case KEY_F(1):
1787 if (view->type == TOG_VIEW_HELP)
1788 err = view->reset(view);
1789 else
1790 err = view_request_new(new, view, TOG_VIEW_HELP);
1791 break;
1792 case '\t':
1793 view->count = 0;
1794 if (view->child) {
1795 view->focussed = 0;
1796 view->child->focussed = 1;
1797 view->focus_child = 1;
1798 } else if (view->parent) {
1799 view->focussed = 0;
1800 view->parent->focussed = 1;
1801 view->parent->focus_child = 0;
1802 if (!view_is_splitscreen(view)) {
1803 if (view->parent->resize) {
1804 err = view->parent->resize(view->parent,
1805 0);
1806 if (err)
1807 return err;
1809 offset_selection_up(view->parent);
1810 err = view_fullscreen(view->parent);
1811 if (err)
1812 return err;
1815 break;
1816 case 'q':
1817 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1818 if (view->parent->resize) {
1819 /* might need more commits to fill fullscreen */
1820 err = view->parent->resize(view->parent, 0);
1821 if (err)
1822 break;
1824 offset_selection_up(view->parent);
1826 err = view->input(new, view, ch);
1827 view->dying = 1;
1828 break;
1829 case 'Q':
1830 *done = 1;
1831 break;
1832 case 'F':
1833 view->count = 0;
1834 if (view_is_parent_view(view)) {
1835 if (view->child == NULL)
1836 break;
1837 if (view_is_splitscreen(view->child)) {
1838 view->focussed = 0;
1839 view->child->focussed = 1;
1840 err = view_fullscreen(view->child);
1841 } else {
1842 err = view_splitscreen(view->child);
1843 if (!err)
1844 err = view_resize_split(view, 0);
1846 if (err)
1847 break;
1848 err = view->child->input(new, view->child,
1849 KEY_RESIZE);
1850 } else {
1851 if (view_is_splitscreen(view)) {
1852 view->parent->focussed = 0;
1853 view->focussed = 1;
1854 err = view_fullscreen(view);
1855 } else {
1856 err = view_splitscreen(view);
1857 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1858 err = view_resize(view->parent);
1859 if (!err)
1860 err = view_resize_split(view, 0);
1862 if (err)
1863 break;
1864 err = view->input(new, view, KEY_RESIZE);
1866 if (err)
1867 break;
1868 if (view->resize) {
1869 err = view->resize(view, 0);
1870 if (err)
1871 break;
1873 if (view->parent) {
1874 if (view->parent->resize) {
1875 err = view->parent->resize(view->parent, 0);
1876 if (err != NULL)
1877 break;
1879 err = offset_selection_down(view->parent);
1880 if (err != NULL)
1881 break;
1883 err = offset_selection_down(view);
1884 break;
1885 case 'S':
1886 view->count = 0;
1887 err = switch_split(view);
1888 break;
1889 case '-':
1890 err = view_resize_split(view, -1);
1891 break;
1892 case '+':
1893 err = view_resize_split(view, 1);
1894 break;
1895 case KEY_RESIZE:
1896 break;
1897 case '/':
1898 view->count = 0;
1899 if (view->search_start)
1900 view_search_start(view, fast_refresh);
1901 else
1902 err = view->input(new, view, ch);
1903 break;
1904 case 'N':
1905 case 'n':
1906 if (view->search_started && view->search_next) {
1907 view->searching = (ch == 'n' ?
1908 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1909 view->search_next_done = 0;
1910 view->search_next(view);
1911 } else
1912 err = view->input(new, view, ch);
1913 break;
1914 case 'A':
1915 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1916 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1917 view->action = "Patience diff algorithm";
1918 } else {
1919 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1920 view->action = "Myers diff algorithm";
1922 TAILQ_FOREACH(v, views, entry) {
1923 if (v->reset) {
1924 err = v->reset(v);
1925 if (err)
1926 return err;
1928 if (v->child && v->child->reset) {
1929 err = v->child->reset(v->child);
1930 if (err)
1931 return err;
1934 break;
1935 case TOG_KEY_SCRDUMP:
1936 err = screendump(view);
1937 break;
1938 default:
1939 err = view->input(new, view, ch);
1940 break;
1943 return err;
1946 static int
1947 view_needs_focus_indication(struct tog_view *view)
1949 if (view_is_parent_view(view)) {
1950 if (view->child == NULL || view->child->focussed)
1951 return 0;
1952 if (!view_is_splitscreen(view->child))
1953 return 0;
1954 } else if (!view_is_splitscreen(view))
1955 return 0;
1957 return view->focussed;
1960 static const struct got_error *
1961 tog_io_close(void)
1963 const struct got_error *err = NULL;
1965 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1966 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1967 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1968 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1969 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1970 err = got_ferror(tog_io.f, GOT_ERR_IO);
1971 if (tog_io.sdump && fclose(tog_io.sdump) == EOF && err == NULL)
1972 err = got_ferror(tog_io.sdump, GOT_ERR_IO);
1973 if (tog_io.input_str != NULL)
1974 free(tog_io.input_str);
1976 return err;
1979 static const struct got_error *
1980 view_loop(struct tog_view *view)
1982 const struct got_error *err = NULL;
1983 struct tog_view_list_head views;
1984 struct tog_view *new_view;
1985 char *mode;
1986 int fast_refresh = 10;
1987 int done = 0, errcode;
1989 mode = getenv("TOG_VIEW_SPLIT_MODE");
1990 if (!mode || !(*mode == 'h' || *mode == 'H'))
1991 view->mode = TOG_VIEW_SPLIT_VERT;
1992 else
1993 view->mode = TOG_VIEW_SPLIT_HRZN;
1995 errcode = pthread_mutex_lock(&tog_mutex);
1996 if (errcode)
1997 return got_error_set_errno(errcode, "pthread_mutex_lock");
1999 TAILQ_INIT(&views);
2000 TAILQ_INSERT_HEAD(&views, view, entry);
2002 view->focussed = 1;
2003 err = view->show(view);
2004 if (err)
2005 return err;
2006 update_panels();
2007 doupdate();
2008 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
2009 !tog_fatal_signal_received()) {
2010 /* Refresh fast during initialization, then become slower. */
2011 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
2012 halfdelay(10); /* switch to once per second */
2014 err = view_input(&new_view, &done, view, &views, fast_refresh);
2015 if (err)
2016 break;
2018 if (view->dying && view == TAILQ_FIRST(&views) &&
2019 TAILQ_NEXT(view, entry) == NULL)
2020 done = 1;
2021 if (done) {
2022 struct tog_view *v;
2025 * When we quit, scroll the screen up a single line
2026 * so we don't lose any information.
2028 TAILQ_FOREACH(v, &views, entry) {
2029 wmove(v->window, 0, 0);
2030 wdeleteln(v->window);
2031 wnoutrefresh(v->window);
2032 if (v->child && !view_is_fullscreen(v)) {
2033 wmove(v->child->window, 0, 0);
2034 wdeleteln(v->child->window);
2035 wnoutrefresh(v->child->window);
2038 doupdate();
2041 if (view->dying) {
2042 struct tog_view *v, *prev = NULL;
2044 if (view_is_parent_view(view))
2045 prev = TAILQ_PREV(view, tog_view_list_head,
2046 entry);
2047 else if (view->parent)
2048 prev = view->parent;
2050 if (view->parent) {
2051 view->parent->child = NULL;
2052 view->parent->focus_child = 0;
2053 /* Restore fullscreen line height. */
2054 view->parent->nlines = view->parent->lines;
2055 err = view_resize(view->parent);
2056 if (err)
2057 break;
2058 /* Make resized splits persist. */
2059 view_transfer_size(view->parent, view);
2060 } else
2061 TAILQ_REMOVE(&views, view, entry);
2063 err = view_close(view);
2064 if (err)
2065 goto done;
2067 view = NULL;
2068 TAILQ_FOREACH(v, &views, entry) {
2069 if (v->focussed)
2070 break;
2072 if (view == NULL && new_view == NULL) {
2073 /* No view has focus. Try to pick one. */
2074 if (prev)
2075 view = prev;
2076 else if (!TAILQ_EMPTY(&views)) {
2077 view = TAILQ_LAST(&views,
2078 tog_view_list_head);
2080 if (view) {
2081 if (view->focus_child) {
2082 view->child->focussed = 1;
2083 view = view->child;
2084 } else
2085 view->focussed = 1;
2089 if (new_view) {
2090 struct tog_view *v, *t;
2091 /* Only allow one parent view per type. */
2092 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2093 if (v->type != new_view->type)
2094 continue;
2095 TAILQ_REMOVE(&views, v, entry);
2096 err = view_close(v);
2097 if (err)
2098 goto done;
2099 break;
2101 TAILQ_INSERT_TAIL(&views, new_view, entry);
2102 view = new_view;
2104 if (view && !done) {
2105 if (view_is_parent_view(view)) {
2106 if (view->child && view->child->focussed)
2107 view = view->child;
2108 } else {
2109 if (view->parent && view->parent->focussed)
2110 view = view->parent;
2112 show_panel(view->panel);
2113 if (view->child && view_is_splitscreen(view->child))
2114 show_panel(view->child->panel);
2115 if (view->parent && view_is_splitscreen(view)) {
2116 err = view->parent->show(view->parent);
2117 if (err)
2118 goto done;
2120 err = view->show(view);
2121 if (err)
2122 goto done;
2123 if (view->child) {
2124 err = view->child->show(view->child);
2125 if (err)
2126 goto done;
2128 update_panels();
2129 doupdate();
2132 done:
2133 while (!TAILQ_EMPTY(&views)) {
2134 const struct got_error *close_err;
2135 view = TAILQ_FIRST(&views);
2136 TAILQ_REMOVE(&views, view, entry);
2137 close_err = view_close(view);
2138 if (close_err && err == NULL)
2139 err = close_err;
2142 errcode = pthread_mutex_unlock(&tog_mutex);
2143 if (errcode && err == NULL)
2144 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2146 return err;
2149 __dead static void
2150 usage_log(void)
2152 endwin();
2153 fprintf(stderr,
2154 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2155 getprogname());
2156 exit(1);
2159 /* Create newly allocated wide-character string equivalent to a byte string. */
2160 static const struct got_error *
2161 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2163 char *vis = NULL;
2164 const struct got_error *err = NULL;
2166 *ws = NULL;
2167 *wlen = mbstowcs(NULL, s, 0);
2168 if (*wlen == (size_t)-1) {
2169 int vislen;
2170 if (errno != EILSEQ)
2171 return got_error_from_errno("mbstowcs");
2173 /* byte string invalid in current encoding; try to "fix" it */
2174 err = got_mbsavis(&vis, &vislen, s);
2175 if (err)
2176 return err;
2177 *wlen = mbstowcs(NULL, vis, 0);
2178 if (*wlen == (size_t)-1) {
2179 err = got_error_from_errno("mbstowcs"); /* give up */
2180 goto done;
2184 *ws = calloc(*wlen + 1, sizeof(**ws));
2185 if (*ws == NULL) {
2186 err = got_error_from_errno("calloc");
2187 goto done;
2190 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2191 err = got_error_from_errno("mbstowcs");
2192 done:
2193 free(vis);
2194 if (err) {
2195 free(*ws);
2196 *ws = NULL;
2197 *wlen = 0;
2199 return err;
2202 static const struct got_error *
2203 expand_tab(char **ptr, const char *src)
2205 char *dst;
2206 size_t len, n, idx = 0, sz = 0;
2208 *ptr = NULL;
2209 n = len = strlen(src);
2210 dst = malloc(n + 1);
2211 if (dst == NULL)
2212 return got_error_from_errno("malloc");
2214 while (idx < len && src[idx]) {
2215 const char c = src[idx];
2217 if (c == '\t') {
2218 size_t nb = TABSIZE - sz % TABSIZE;
2219 char *p;
2221 p = realloc(dst, n + nb);
2222 if (p == NULL) {
2223 free(dst);
2224 return got_error_from_errno("realloc");
2227 dst = p;
2228 n += nb;
2229 memset(dst + sz, ' ', nb);
2230 sz += nb;
2231 } else
2232 dst[sz++] = src[idx];
2233 ++idx;
2236 dst[sz] = '\0';
2237 *ptr = dst;
2238 return NULL;
2242 * Advance at most n columns from wline starting at offset off.
2243 * Return the index to the first character after the span operation.
2244 * Return the combined column width of all spanned wide characters in
2245 * *rcol.
2247 static int
2248 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2250 int width, i, cols = 0;
2252 if (n == 0) {
2253 *rcol = cols;
2254 return off;
2257 for (i = off; wline[i] != L'\0'; ++i) {
2258 if (wline[i] == L'\t')
2259 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2260 else
2261 width = wcwidth(wline[i]);
2263 if (width == -1) {
2264 width = 1;
2265 wline[i] = L'.';
2268 if (cols + width > n)
2269 break;
2270 cols += width;
2273 *rcol = cols;
2274 return i;
2278 * Format a line for display, ensuring that it won't overflow a width limit.
2279 * With scrolling, the width returned refers to the scrolled version of the
2280 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2282 static const struct got_error *
2283 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2284 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2286 const struct got_error *err = NULL;
2287 int cols;
2288 wchar_t *wline = NULL;
2289 char *exstr = NULL;
2290 size_t wlen;
2291 int i, scrollx;
2293 *wlinep = NULL;
2294 *widthp = 0;
2296 if (expand) {
2297 err = expand_tab(&exstr, line);
2298 if (err)
2299 return err;
2302 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2303 free(exstr);
2304 if (err)
2305 return err;
2307 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2309 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2310 wline[wlen - 1] = L'\0';
2311 wlen--;
2313 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2314 wline[wlen - 1] = L'\0';
2315 wlen--;
2318 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2319 wline[i] = L'\0';
2321 if (widthp)
2322 *widthp = cols;
2323 if (scrollxp)
2324 *scrollxp = scrollx;
2325 if (err)
2326 free(wline);
2327 else
2328 *wlinep = wline;
2329 return err;
2332 static const struct got_error*
2333 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2334 struct got_object_id *id, struct got_repository *repo)
2336 static const struct got_error *err = NULL;
2337 struct got_reflist_entry *re;
2338 char *s;
2339 const char *name;
2341 *refs_str = NULL;
2343 if (refs == NULL)
2344 return NULL;
2346 TAILQ_FOREACH(re, refs, entry) {
2347 struct got_tag_object *tag = NULL;
2348 struct got_object_id *ref_id;
2349 int cmp;
2351 name = got_ref_get_name(re->ref);
2352 if (strcmp(name, GOT_REF_HEAD) == 0)
2353 continue;
2354 if (strncmp(name, "refs/", 5) == 0)
2355 name += 5;
2356 if (strncmp(name, "got/", 4) == 0)
2357 continue;
2358 if (strncmp(name, "heads/", 6) == 0)
2359 name += 6;
2360 if (strncmp(name, "remotes/", 8) == 0) {
2361 name += 8;
2362 s = strstr(name, "/" GOT_REF_HEAD);
2363 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
2364 continue;
2366 err = got_ref_resolve(&ref_id, repo, re->ref);
2367 if (err)
2368 break;
2369 if (strncmp(name, "tags/", 5) == 0) {
2370 err = got_object_open_as_tag(&tag, repo, ref_id);
2371 if (err) {
2372 if (err->code != GOT_ERR_OBJ_TYPE) {
2373 free(ref_id);
2374 break;
2376 /* Ref points at something other than a tag. */
2377 err = NULL;
2378 tag = NULL;
2381 cmp = got_object_id_cmp(tag ?
2382 got_object_tag_get_object_id(tag) : ref_id, id);
2383 free(ref_id);
2384 if (tag)
2385 got_object_tag_close(tag);
2386 if (cmp != 0)
2387 continue;
2388 s = *refs_str;
2389 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2390 s ? ", " : "", name) == -1) {
2391 err = got_error_from_errno("asprintf");
2392 free(s);
2393 *refs_str = NULL;
2394 break;
2396 free(s);
2399 return err;
2402 static const struct got_error *
2403 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2404 int col_tab_align)
2406 char *smallerthan;
2408 smallerthan = strchr(author, '<');
2409 if (smallerthan && smallerthan[1] != '\0')
2410 author = smallerthan + 1;
2411 author[strcspn(author, "@>")] = '\0';
2412 return format_line(wauthor, author_width, NULL, author, 0, limit,
2413 col_tab_align, 0);
2416 static const struct got_error *
2417 draw_commit(struct tog_view *view, struct commit_queue_entry *entry,
2418 const size_t date_display_cols, int author_display_cols)
2420 struct tog_log_view_state *s = &view->state.log;
2421 const struct got_error *err = NULL;
2422 struct got_commit_object *commit = entry->commit;
2423 struct got_object_id *id = entry->id;
2424 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2425 char *refs_str = NULL;
2426 char *logmsg0 = NULL, *logmsg = NULL;
2427 char *author = NULL;
2428 wchar_t *wrefstr = NULL, *wlogmsg = NULL, *wauthor = NULL;
2429 int author_width, refstr_width, logmsg_width;
2430 char *newline, *line = NULL;
2431 int col, limit, scrollx, logmsg_x;
2432 const int avail = view->ncols, marker_column = author_display_cols + 1;
2433 struct tm tm;
2434 time_t committer_time;
2435 struct tog_color *tc;
2436 struct got_reflist_head *refs;
2438 if (tog_base_commit.id != NULL && tog_base_commit.idx == -1 &&
2439 got_object_id_cmp(id, tog_base_commit.id) == 0)
2440 tog_base_commit.idx = entry->idx;
2441 if (tog_io.wait_for_ui && s->thread_args.need_commit_marker) {
2442 int rc;
2444 rc = pthread_cond_wait(&s->thread_args.log_loaded, &tog_mutex);
2445 if (rc)
2446 return got_error_set_errno(rc, "pthread_cond_wait");
2449 committer_time = got_object_commit_get_committer_time(commit);
2450 if (gmtime_r(&committer_time, &tm) == NULL)
2451 return got_error_from_errno("gmtime_r");
2452 if (strftime(datebuf, sizeof(datebuf), "%F ", &tm) == 0)
2453 return got_error(GOT_ERR_NO_SPACE);
2455 if (avail <= date_display_cols)
2456 limit = MIN(sizeof(datebuf) - 1, avail);
2457 else
2458 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2459 tc = get_color(&s->colors, TOG_COLOR_DATE);
2460 if (tc)
2461 wattr_on(view->window,
2462 COLOR_PAIR(tc->colorpair), NULL);
2463 waddnstr(view->window, datebuf, limit);
2464 if (tc)
2465 wattr_off(view->window,
2466 COLOR_PAIR(tc->colorpair), NULL);
2467 col = limit;
2468 if (col > avail)
2469 goto done;
2471 if (avail >= 120) {
2472 char *id_str;
2473 err = got_object_id_str(&id_str, id);
2474 if (err)
2475 goto done;
2476 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2477 if (tc)
2478 wattr_on(view->window,
2479 COLOR_PAIR(tc->colorpair), NULL);
2480 wprintw(view->window, "%.8s ", id_str);
2481 if (tc)
2482 wattr_off(view->window,
2483 COLOR_PAIR(tc->colorpair), NULL);
2484 free(id_str);
2485 col += 9;
2486 if (col > avail)
2487 goto done;
2490 if (s->use_committer)
2491 author = strdup(got_object_commit_get_committer(commit));
2492 else
2493 author = strdup(got_object_commit_get_author(commit));
2494 if (author == NULL) {
2495 err = got_error_from_errno("strdup");
2496 goto done;
2498 err = format_author(&wauthor, &author_width, author, avail - col, col);
2499 if (err)
2500 goto done;
2501 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2502 if (tc)
2503 wattr_on(view->window,
2504 COLOR_PAIR(tc->colorpair), NULL);
2505 waddwstr(view->window, wauthor);
2506 col += author_width;
2507 while (col < avail && author_width < author_display_cols + 2) {
2508 if (tog_base_commit.marker != GOT_WORKTREE_STATE_UNKNOWN &&
2509 author_width == marker_column &&
2510 entry->idx == tog_base_commit.idx && !s->limit_view) {
2511 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2512 if (tc)
2513 wattr_on(view->window,
2514 COLOR_PAIR(tc->colorpair), NULL);
2515 waddch(view->window, tog_base_commit.marker);
2516 if (tc)
2517 wattr_off(view->window,
2518 COLOR_PAIR(tc->colorpair), NULL);
2519 } else
2520 waddch(view->window, ' ');
2521 col++;
2522 author_width++;
2524 if (tc)
2525 wattr_off(view->window,
2526 COLOR_PAIR(tc->colorpair), NULL);
2527 if (col > avail)
2528 goto done;
2530 err = got_object_commit_get_logmsg(&logmsg0, commit);
2531 if (err)
2532 goto done;
2533 logmsg = logmsg0;
2534 while (*logmsg == '\n')
2535 logmsg++;
2536 newline = strchr(logmsg, '\n');
2537 if (newline)
2538 *newline = '\0';
2540 limit = avail - col;
2541 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2542 limit--; /* for the border */
2544 /* Prepend reference labels to log message if possible .*/
2545 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, id);
2546 err = build_refs_str(&refs_str, refs, id, s->repo);
2547 if (err)
2548 goto done;
2549 if (refs_str) {
2550 char *rs;
2552 if (asprintf(&rs, "[%s]", refs_str) == -1) {
2553 err = got_error_from_errno("asprintf");
2554 goto done;
2556 err = format_line(&wrefstr, &refstr_width,
2557 &scrollx, rs, view->x, limit, col, 1);
2558 free(rs);
2559 if (err)
2560 goto done;
2561 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2562 if (tc)
2563 wattr_on(view->window,
2564 COLOR_PAIR(tc->colorpair), NULL);
2565 waddwstr(view->window, &wrefstr[scrollx]);
2566 if (tc)
2567 wattr_off(view->window,
2568 COLOR_PAIR(tc->colorpair), NULL);
2569 col += MAX(refstr_width, 0);
2570 if (col > avail)
2571 goto done;
2573 if (col < avail) {
2574 waddch(view->window, ' ');
2575 col++;
2578 if (refstr_width > 0)
2579 logmsg_x = 0;
2580 else {
2581 int unscrolled_refstr_width;
2582 size_t len = wcslen(wrefstr);
2585 * No need to check for -1 return value here since
2586 * unprintables have been replaced by span_wline().
2588 unscrolled_refstr_width = wcswidth(wrefstr, len);
2589 unscrolled_refstr_width += 1; /* trailing space */
2590 logmsg_x = view->x - unscrolled_refstr_width;
2593 limit = avail - col;
2594 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2595 limit--; /* for the border */
2596 } else
2597 logmsg_x = view->x;
2599 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, logmsg_x,
2600 limit, col, 1);
2601 if (err)
2602 goto done;
2603 waddwstr(view->window, &wlogmsg[scrollx]);
2604 col += MAX(logmsg_width, 0);
2605 while (col < avail) {
2606 waddch(view->window, ' ');
2607 col++;
2609 done:
2610 free(logmsg0);
2611 free(wlogmsg);
2612 free(wrefstr);
2613 free(refs_str);
2614 free(author);
2615 free(wauthor);
2616 free(line);
2617 return err;
2620 static struct commit_queue_entry *
2621 alloc_commit_queue_entry(struct got_commit_object *commit,
2622 struct got_object_id *id)
2624 struct commit_queue_entry *entry;
2625 struct got_object_id *dup;
2627 entry = calloc(1, sizeof(*entry));
2628 if (entry == NULL)
2629 return NULL;
2631 dup = got_object_id_dup(id);
2632 if (dup == NULL) {
2633 free(entry);
2634 return NULL;
2637 entry->id = dup;
2638 entry->commit = commit;
2639 return entry;
2642 static void
2643 pop_commit(struct commit_queue *commits)
2645 struct commit_queue_entry *entry;
2647 entry = TAILQ_FIRST(&commits->head);
2648 TAILQ_REMOVE(&commits->head, entry, entry);
2649 got_object_commit_close(entry->commit);
2650 commits->ncommits--;
2651 free(entry->id);
2652 free(entry);
2655 static void
2656 free_commits(struct commit_queue *commits)
2658 while (!TAILQ_EMPTY(&commits->head))
2659 pop_commit(commits);
2662 static const struct got_error *
2663 match_commit(int *have_match, struct got_object_id *id,
2664 struct got_commit_object *commit, regex_t *regex)
2666 const struct got_error *err = NULL;
2667 regmatch_t regmatch;
2668 char *id_str = NULL, *logmsg = NULL;
2670 *have_match = 0;
2672 err = got_object_id_str(&id_str, id);
2673 if (err)
2674 return err;
2676 err = got_object_commit_get_logmsg(&logmsg, commit);
2677 if (err)
2678 goto done;
2680 if (regexec(regex, got_object_commit_get_author(commit), 1,
2681 &regmatch, 0) == 0 ||
2682 regexec(regex, got_object_commit_get_committer(commit), 1,
2683 &regmatch, 0) == 0 ||
2684 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2685 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2686 *have_match = 1;
2687 done:
2688 free(id_str);
2689 free(logmsg);
2690 return err;
2693 static const struct got_error *
2694 queue_commits(struct tog_log_thread_args *a)
2696 const struct got_error *err = NULL;
2699 * We keep all commits open throughout the lifetime of the log
2700 * view in order to avoid having to re-fetch commits from disk
2701 * while updating the display.
2703 do {
2704 struct got_object_id id;
2705 struct got_commit_object *commit;
2706 struct commit_queue_entry *entry;
2707 int limit_match = 0;
2708 int errcode;
2710 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2711 NULL, NULL);
2712 if (err)
2713 break;
2715 err = got_object_open_as_commit(&commit, a->repo, &id);
2716 if (err)
2717 break;
2718 entry = alloc_commit_queue_entry(commit, &id);
2719 if (entry == NULL) {
2720 err = got_error_from_errno("alloc_commit_queue_entry");
2721 break;
2724 errcode = pthread_mutex_lock(&tog_mutex);
2725 if (errcode) {
2726 err = got_error_set_errno(errcode,
2727 "pthread_mutex_lock");
2728 break;
2731 entry->idx = a->real_commits->ncommits;
2732 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2733 a->real_commits->ncommits++;
2735 if (*a->limiting) {
2736 err = match_commit(&limit_match, &id, commit,
2737 a->limit_regex);
2738 if (err)
2739 break;
2741 if (limit_match) {
2742 struct commit_queue_entry *matched;
2744 matched = alloc_commit_queue_entry(
2745 entry->commit, entry->id);
2746 if (matched == NULL) {
2747 err = got_error_from_errno(
2748 "alloc_commit_queue_entry");
2749 break;
2751 matched->commit = entry->commit;
2752 got_object_commit_retain(entry->commit);
2754 matched->idx = a->limit_commits->ncommits;
2755 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2756 matched, entry);
2757 a->limit_commits->ncommits++;
2761 * This is how we signal log_thread() that we
2762 * have found a match, and that it should be
2763 * counted as a new entry for the view.
2765 a->limit_match = limit_match;
2768 if (*a->searching == TOG_SEARCH_FORWARD &&
2769 !*a->search_next_done) {
2770 int have_match;
2771 err = match_commit(&have_match, &id, commit, a->regex);
2772 if (err)
2773 break;
2775 if (*a->limiting) {
2776 if (limit_match && have_match)
2777 *a->search_next_done =
2778 TOG_SEARCH_HAVE_MORE;
2779 } else if (have_match)
2780 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2783 errcode = pthread_mutex_unlock(&tog_mutex);
2784 if (errcode && err == NULL)
2785 err = got_error_set_errno(errcode,
2786 "pthread_mutex_unlock");
2787 if (err)
2788 break;
2789 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2791 return err;
2794 static void
2795 select_commit(struct tog_log_view_state *s)
2797 struct commit_queue_entry *entry;
2798 int ncommits = 0;
2800 entry = s->first_displayed_entry;
2801 while (entry) {
2802 if (ncommits == s->selected) {
2803 s->selected_entry = entry;
2804 break;
2806 entry = TAILQ_NEXT(entry, entry);
2807 ncommits++;
2811 static const struct got_error *
2812 draw_commits(struct tog_view *view)
2814 const struct got_error *err = NULL;
2815 struct tog_log_view_state *s = &view->state.log;
2816 struct commit_queue_entry *entry = s->selected_entry;
2817 int limit = view->nlines;
2818 int width;
2819 int ncommits, author_cols = 4, refstr_cols;
2820 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2821 char *refs_str = NULL;
2822 wchar_t *wline;
2823 struct tog_color *tc;
2824 static const size_t date_display_cols = 12;
2825 struct got_reflist_head *refs;
2827 if (view_is_hsplit_top(view))
2828 --limit; /* account for border */
2830 if (s->selected_entry &&
2831 !(view->searching && view->search_next_done == 0)) {
2832 err = got_object_id_str(&id_str, s->selected_entry->id);
2833 if (err)
2834 return err;
2835 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2836 s->selected_entry->id);
2837 err = build_refs_str(&refs_str, refs, s->selected_entry->id,
2838 s->repo);
2839 if (err)
2840 goto done;
2843 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2844 halfdelay(10); /* disable fast refresh */
2846 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2847 if (asprintf(&ncommits_str, " [%d/%d] %s",
2848 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2849 (view->searching && !view->search_next_done) ?
2850 "searching..." : "loading...") == -1) {
2851 err = got_error_from_errno("asprintf");
2852 goto done;
2854 } else {
2855 const char *search_str = NULL;
2856 const char *limit_str = NULL;
2858 if (view->searching) {
2859 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2860 search_str = "no more matches";
2861 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2862 search_str = "no matches found";
2863 else if (!view->search_next_done)
2864 search_str = "searching...";
2867 if (s->limit_view && s->commits->ncommits == 0)
2868 limit_str = "no matches found";
2870 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2871 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2872 search_str ? search_str : (refs_str ? refs_str : ""),
2873 limit_str ? limit_str : "") == -1) {
2874 err = got_error_from_errno("asprintf");
2875 goto done;
2879 free(refs_str);
2880 refs_str = NULL;
2882 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2883 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2884 "........................................",
2885 s->in_repo_path, ncommits_str) == -1) {
2886 err = got_error_from_errno("asprintf");
2887 header = NULL;
2888 goto done;
2890 } else if (asprintf(&header, "commit %s%s",
2891 id_str ? id_str : "........................................",
2892 ncommits_str) == -1) {
2893 err = got_error_from_errno("asprintf");
2894 header = NULL;
2895 goto done;
2897 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2898 if (err)
2899 goto done;
2901 werase(view->window);
2903 if (view_needs_focus_indication(view))
2904 wstandout(view->window);
2905 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2906 if (tc)
2907 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2908 waddwstr(view->window, wline);
2909 while (width < view->ncols) {
2910 waddch(view->window, ' ');
2911 width++;
2913 if (tc)
2914 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2915 if (view_needs_focus_indication(view))
2916 wstandend(view->window);
2917 free(wline);
2918 if (limit <= 1)
2919 goto done;
2921 /* Grow author column size if necessary, and set view->maxx. */
2922 entry = s->first_displayed_entry;
2923 ncommits = 0;
2924 view->maxx = 0;
2925 while (entry) {
2926 struct got_commit_object *c = entry->commit;
2927 char *author, *eol, *msg, *msg0;
2928 wchar_t *wauthor, *wmsg;
2929 int width;
2930 if (ncommits >= limit - 1)
2931 break;
2932 if (s->use_committer)
2933 author = strdup(got_object_commit_get_committer(c));
2934 else
2935 author = strdup(got_object_commit_get_author(c));
2936 if (author == NULL) {
2937 err = got_error_from_errno("strdup");
2938 goto done;
2940 err = format_author(&wauthor, &width, author, COLS,
2941 date_display_cols);
2942 if (author_cols < width)
2943 author_cols = width;
2944 free(wauthor);
2945 free(author);
2946 if (err)
2947 goto done;
2948 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2949 entry->id);
2950 err = build_refs_str(&refs_str, refs, entry->id, s->repo);
2951 if (err)
2952 goto done;
2953 if (refs_str) {
2954 wchar_t *ws;
2955 err = format_line(&ws, &width, NULL, refs_str,
2956 0, INT_MAX, date_display_cols + author_cols, 0);
2957 free(ws);
2958 free(refs_str);
2959 refs_str = NULL;
2960 if (err)
2961 goto done;
2962 refstr_cols = width + 3; /* account for [ ] + space */
2963 } else
2964 refstr_cols = 0;
2965 err = got_object_commit_get_logmsg(&msg0, c);
2966 if (err)
2967 goto done;
2968 msg = msg0;
2969 while (*msg == '\n')
2970 ++msg;
2971 if ((eol = strchr(msg, '\n')))
2972 *eol = '\0';
2973 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2974 date_display_cols + author_cols + refstr_cols, 0);
2975 if (err)
2976 goto done;
2977 view->maxx = MAX(view->maxx, width + refstr_cols);
2978 free(msg0);
2979 free(wmsg);
2980 ncommits++;
2981 entry = TAILQ_NEXT(entry, entry);
2984 entry = s->first_displayed_entry;
2985 s->last_displayed_entry = s->first_displayed_entry;
2986 ncommits = 0;
2987 while (entry) {
2988 if (ncommits >= limit - 1)
2989 break;
2990 if (ncommits == s->selected)
2991 wstandout(view->window);
2992 err = draw_commit(view, entry, date_display_cols, author_cols);
2993 if (ncommits == s->selected)
2994 wstandend(view->window);
2995 if (err)
2996 goto done;
2997 ncommits++;
2998 s->last_displayed_entry = entry;
2999 entry = TAILQ_NEXT(entry, entry);
3002 view_border(view);
3003 done:
3004 free(id_str);
3005 free(refs_str);
3006 free(ncommits_str);
3007 free(header);
3008 return err;
3011 static void
3012 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
3014 struct commit_queue_entry *entry;
3015 int nscrolled = 0;
3017 entry = TAILQ_FIRST(&s->commits->head);
3018 if (s->first_displayed_entry == entry)
3019 return;
3021 entry = s->first_displayed_entry;
3022 while (entry && nscrolled < maxscroll) {
3023 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3024 if (entry) {
3025 s->first_displayed_entry = entry;
3026 nscrolled++;
3031 static const struct got_error *
3032 trigger_log_thread(struct tog_view *view, int wait)
3034 struct tog_log_thread_args *ta = &view->state.log.thread_args;
3035 int errcode;
3037 if (!using_mock_io)
3038 halfdelay(1); /* fast refresh while loading commits */
3040 while (!ta->log_complete && !tog_thread_error &&
3041 (ta->commits_needed > 0 || ta->load_all)) {
3042 /* Wake the log thread. */
3043 errcode = pthread_cond_signal(&ta->need_commits);
3044 if (errcode)
3045 return got_error_set_errno(errcode,
3046 "pthread_cond_signal");
3049 * The mutex will be released while the view loop waits
3050 * in wgetch(), at which time the log thread will run.
3052 if (!wait)
3053 break;
3055 /* Display progress update in log view. */
3056 show_log_view(view);
3057 update_panels();
3058 doupdate();
3060 /* Wait right here while next commit is being loaded. */
3061 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
3062 if (errcode)
3063 return got_error_set_errno(errcode,
3064 "pthread_cond_wait");
3066 /* Display progress update in log view. */
3067 show_log_view(view);
3068 update_panels();
3069 doupdate();
3072 return NULL;
3075 static const struct got_error *
3076 request_log_commits(struct tog_view *view)
3078 struct tog_log_view_state *state = &view->state.log;
3079 const struct got_error *err = NULL;
3081 if (state->thread_args.log_complete)
3082 return NULL;
3084 state->thread_args.commits_needed += view->nscrolled;
3085 err = trigger_log_thread(view, 1);
3086 view->nscrolled = 0;
3088 return err;
3091 static const struct got_error *
3092 log_scroll_down(struct tog_view *view, int maxscroll)
3094 struct tog_log_view_state *s = &view->state.log;
3095 const struct got_error *err = NULL;
3096 struct commit_queue_entry *pentry;
3097 int nscrolled = 0, ncommits_needed;
3099 if (s->last_displayed_entry == NULL)
3100 return NULL;
3102 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
3103 if (s->commits->ncommits < ncommits_needed &&
3104 !s->thread_args.log_complete) {
3106 * Ask the log thread for required amount of commits.
3108 s->thread_args.commits_needed +=
3109 ncommits_needed - s->commits->ncommits;
3110 err = trigger_log_thread(view, 1);
3111 if (err)
3112 return err;
3115 do {
3116 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
3117 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
3118 break;
3120 s->last_displayed_entry = pentry ?
3121 pentry : s->last_displayed_entry;
3123 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3124 if (pentry == NULL)
3125 break;
3126 s->first_displayed_entry = pentry;
3127 } while (++nscrolled < maxscroll);
3129 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3130 view->nscrolled += nscrolled;
3131 else
3132 view->nscrolled = 0;
3134 return err;
3137 static const struct got_error *
3138 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3139 struct got_commit_object *commit, struct got_object_id *commit_id,
3140 struct tog_view *log_view, struct got_repository *repo)
3142 const struct got_error *err;
3143 struct got_object_qid *parent_id;
3144 struct tog_view *diff_view;
3146 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3147 if (diff_view == NULL)
3148 return got_error_from_errno("view_open");
3150 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3151 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3152 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3153 if (err == NULL)
3154 *new_view = diff_view;
3155 return err;
3158 static const struct got_error *
3159 tree_view_visit_subtree(struct tog_tree_view_state *s,
3160 struct got_tree_object *subtree)
3162 struct tog_parent_tree *parent;
3164 parent = calloc(1, sizeof(*parent));
3165 if (parent == NULL)
3166 return got_error_from_errno("calloc");
3168 parent->tree = s->tree;
3169 parent->first_displayed_entry = s->first_displayed_entry;
3170 parent->selected_entry = s->selected_entry;
3171 parent->selected = s->selected;
3172 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3173 s->tree = subtree;
3174 s->selected = 0;
3175 s->first_displayed_entry = NULL;
3176 return NULL;
3179 static const struct got_error *
3180 tree_view_walk_path(struct tog_tree_view_state *s,
3181 struct got_commit_object *commit, const char *path)
3183 const struct got_error *err = NULL;
3184 struct got_tree_object *tree = NULL;
3185 const char *p;
3186 char *slash, *subpath = NULL;
3188 /* Walk the path and open corresponding tree objects. */
3189 p = path;
3190 while (*p) {
3191 struct got_tree_entry *te;
3192 struct got_object_id *tree_id;
3193 char *te_name;
3195 while (p[0] == '/')
3196 p++;
3198 /* Ensure the correct subtree entry is selected. */
3199 slash = strchr(p, '/');
3200 if (slash == NULL)
3201 te_name = strdup(p);
3202 else
3203 te_name = strndup(p, slash - p);
3204 if (te_name == NULL) {
3205 err = got_error_from_errno("strndup");
3206 break;
3208 te = got_object_tree_find_entry(s->tree, te_name);
3209 if (te == NULL) {
3210 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3211 free(te_name);
3212 break;
3214 free(te_name);
3215 s->first_displayed_entry = s->selected_entry = te;
3217 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3218 break; /* jump to this file's entry */
3220 slash = strchr(p, '/');
3221 if (slash)
3222 subpath = strndup(path, slash - path);
3223 else
3224 subpath = strdup(path);
3225 if (subpath == NULL) {
3226 err = got_error_from_errno("strdup");
3227 break;
3230 err = got_object_id_by_path(&tree_id, s->repo, commit,
3231 subpath);
3232 if (err)
3233 break;
3235 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3236 free(tree_id);
3237 if (err)
3238 break;
3240 err = tree_view_visit_subtree(s, tree);
3241 if (err) {
3242 got_object_tree_close(tree);
3243 break;
3245 if (slash == NULL)
3246 break;
3247 free(subpath);
3248 subpath = NULL;
3249 p = slash;
3252 free(subpath);
3253 return err;
3256 static const struct got_error *
3257 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3258 struct commit_queue_entry *entry, const char *path,
3259 const char *head_ref_name, struct got_repository *repo)
3261 const struct got_error *err = NULL;
3262 struct tog_tree_view_state *s;
3263 struct tog_view *tree_view;
3265 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3266 if (tree_view == NULL)
3267 return got_error_from_errno("view_open");
3269 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3270 if (err)
3271 return err;
3272 s = &tree_view->state.tree;
3274 *new_view = tree_view;
3276 if (got_path_is_root_dir(path))
3277 return NULL;
3279 return tree_view_walk_path(s, entry->commit, path);
3282 static const struct got_error *
3283 block_signals_used_by_main_thread(void)
3285 sigset_t sigset;
3286 int errcode;
3288 if (sigemptyset(&sigset) == -1)
3289 return got_error_from_errno("sigemptyset");
3291 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3292 if (sigaddset(&sigset, SIGWINCH) == -1)
3293 return got_error_from_errno("sigaddset");
3294 if (sigaddset(&sigset, SIGCONT) == -1)
3295 return got_error_from_errno("sigaddset");
3296 if (sigaddset(&sigset, SIGINT) == -1)
3297 return got_error_from_errno("sigaddset");
3298 if (sigaddset(&sigset, SIGTERM) == -1)
3299 return got_error_from_errno("sigaddset");
3301 /* ncurses handles SIGTSTP */
3302 if (sigaddset(&sigset, SIGTSTP) == -1)
3303 return got_error_from_errno("sigaddset");
3305 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3306 if (errcode)
3307 return got_error_set_errno(errcode, "pthread_sigmask");
3309 return NULL;
3312 static void *
3313 log_thread(void *arg)
3315 const struct got_error *err = NULL;
3316 int errcode = 0;
3317 struct tog_log_thread_args *a = arg;
3318 int done = 0;
3321 * Sync startup with main thread such that we begin our
3322 * work once view_input() has released the mutex.
3324 errcode = pthread_mutex_lock(&tog_mutex);
3325 if (errcode) {
3326 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3327 return (void *)err;
3330 err = block_signals_used_by_main_thread();
3331 if (err) {
3332 pthread_mutex_unlock(&tog_mutex);
3333 goto done;
3336 while (!done && !err && !tog_fatal_signal_received()) {
3337 errcode = pthread_mutex_unlock(&tog_mutex);
3338 if (errcode) {
3339 err = got_error_set_errno(errcode,
3340 "pthread_mutex_unlock");
3341 goto done;
3343 err = queue_commits(a);
3344 if (err) {
3345 if (err->code != GOT_ERR_ITER_COMPLETED)
3346 goto done;
3347 err = NULL;
3348 done = 1;
3349 a->commits_needed = 0;
3350 } else if (a->commits_needed > 0 && !a->load_all) {
3351 if (*a->limiting) {
3352 if (a->limit_match)
3353 a->commits_needed--;
3354 } else
3355 a->commits_needed--;
3358 errcode = pthread_mutex_lock(&tog_mutex);
3359 if (errcode) {
3360 err = got_error_set_errno(errcode,
3361 "pthread_mutex_lock");
3362 goto done;
3363 } else if (*a->quit)
3364 done = 1;
3365 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3366 *a->first_displayed_entry =
3367 TAILQ_FIRST(&a->limit_commits->head);
3368 *a->selected_entry = *a->first_displayed_entry;
3369 } else if (*a->first_displayed_entry == NULL) {
3370 *a->first_displayed_entry =
3371 TAILQ_FIRST(&a->real_commits->head);
3372 *a->selected_entry = *a->first_displayed_entry;
3375 errcode = pthread_cond_signal(&a->commit_loaded);
3376 if (errcode) {
3377 err = got_error_set_errno(errcode,
3378 "pthread_cond_signal");
3379 pthread_mutex_unlock(&tog_mutex);
3380 goto done;
3383 if (a->commits_needed == 0 &&
3384 a->need_commit_marker && a->worktree) {
3385 errcode = pthread_mutex_unlock(&tog_mutex);
3386 if (errcode) {
3387 err = got_error_set_errno(errcode,
3388 "pthread_mutex_unlock");
3389 goto done;
3391 err = got_worktree_get_state(&tog_base_commit.marker,
3392 a->repo, a->worktree, NULL, NULL);
3393 if (err)
3394 goto done;
3395 errcode = pthread_mutex_lock(&tog_mutex);
3396 if (errcode) {
3397 err = got_error_set_errno(errcode,
3398 "pthread_mutex_lock");
3399 goto done;
3401 a->need_commit_marker = 0;
3403 * The main thread did not close this
3404 * work tree yet. Close it now.
3406 got_worktree_close(a->worktree);
3407 a->worktree = NULL;
3409 if (*a->quit)
3410 done = 1;
3413 if (done)
3414 a->commits_needed = 0;
3415 else {
3416 if (a->commits_needed == 0 && !a->load_all) {
3417 if (tog_io.wait_for_ui) {
3418 errcode = pthread_cond_signal(
3419 &a->log_loaded);
3420 if (errcode && err == NULL)
3421 err = got_error_set_errno(
3422 errcode,
3423 "pthread_cond_signal");
3426 errcode = pthread_cond_wait(&a->need_commits,
3427 &tog_mutex);
3428 if (errcode) {
3429 err = got_error_set_errno(errcode,
3430 "pthread_cond_wait");
3431 pthread_mutex_unlock(&tog_mutex);
3432 goto done;
3434 if (*a->quit)
3435 done = 1;
3439 a->log_complete = 1;
3440 if (tog_io.wait_for_ui) {
3441 errcode = pthread_cond_signal(&a->log_loaded);
3442 if (errcode && err == NULL)
3443 err = got_error_set_errno(errcode,
3444 "pthread_cond_signal");
3447 errcode = pthread_mutex_unlock(&tog_mutex);
3448 if (errcode)
3449 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3450 done:
3451 if (err) {
3452 tog_thread_error = 1;
3453 pthread_cond_signal(&a->commit_loaded);
3454 if (a->worktree) {
3455 got_worktree_close(a->worktree);
3456 a->worktree = NULL;
3459 return (void *)err;
3462 static const struct got_error *
3463 stop_log_thread(struct tog_log_view_state *s)
3465 const struct got_error *err = NULL, *thread_err = NULL;
3466 int errcode;
3468 if (s->thread) {
3469 s->quit = 1;
3470 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3471 if (errcode)
3472 return got_error_set_errno(errcode,
3473 "pthread_cond_signal");
3474 errcode = pthread_mutex_unlock(&tog_mutex);
3475 if (errcode)
3476 return got_error_set_errno(errcode,
3477 "pthread_mutex_unlock");
3478 errcode = pthread_join(s->thread, (void **)&thread_err);
3479 if (errcode)
3480 return got_error_set_errno(errcode, "pthread_join");
3481 errcode = pthread_mutex_lock(&tog_mutex);
3482 if (errcode)
3483 return got_error_set_errno(errcode,
3484 "pthread_mutex_lock");
3485 s->thread = NULL;
3488 if (s->thread_args.repo) {
3489 err = got_repo_close(s->thread_args.repo);
3490 s->thread_args.repo = NULL;
3493 if (s->thread_args.pack_fds) {
3494 const struct got_error *pack_err =
3495 got_repo_pack_fds_close(s->thread_args.pack_fds);
3496 if (err == NULL)
3497 err = pack_err;
3498 s->thread_args.pack_fds = NULL;
3501 if (s->thread_args.graph) {
3502 got_commit_graph_close(s->thread_args.graph);
3503 s->thread_args.graph = NULL;
3506 return err ? err : thread_err;
3509 static const struct got_error *
3510 close_log_view(struct tog_view *view)
3512 const struct got_error *err = NULL;
3513 struct tog_log_view_state *s = &view->state.log;
3514 int errcode;
3516 err = stop_log_thread(s);
3518 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3519 if (errcode && err == NULL)
3520 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3522 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3523 if (errcode && err == NULL)
3524 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3526 free_commits(&s->limit_commits);
3527 free_commits(&s->real_commits);
3528 free_colors(&s->colors);
3529 free(s->in_repo_path);
3530 s->in_repo_path = NULL;
3531 free(s->start_id);
3532 s->start_id = NULL;
3533 free(s->head_ref_name);
3534 s->head_ref_name = NULL;
3535 return err;
3539 * We use two queues to implement the limit feature: first consists of
3540 * commits matching the current limit_regex; second is the real queue
3541 * of all known commits (real_commits). When the user starts limiting,
3542 * we swap queues such that all movement and displaying functionality
3543 * works with very slight change.
3545 static const struct got_error *
3546 limit_log_view(struct tog_view *view)
3548 struct tog_log_view_state *s = &view->state.log;
3549 struct commit_queue_entry *entry;
3550 struct tog_view *v = view;
3551 const struct got_error *err = NULL;
3552 char pattern[1024];
3553 int ret;
3555 if (view_is_hsplit_top(view))
3556 v = view->child;
3557 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3558 v = view->parent;
3560 if (tog_io.input_str != NULL) {
3561 if (strlcpy(pattern, tog_io.input_str, sizeof(pattern)) >=
3562 sizeof(pattern))
3563 return got_error(GOT_ERR_NO_SPACE);
3564 } else {
3565 wmove(v->window, v->nlines - 1, 0);
3566 wclrtoeol(v->window);
3567 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3568 nodelay(v->window, FALSE);
3569 nocbreak();
3570 echo();
3571 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3572 cbreak();
3573 noecho();
3574 nodelay(v->window, TRUE);
3575 if (ret == ERR)
3576 return NULL;
3579 if (*pattern == '\0') {
3581 * Safety measure for the situation where the user
3582 * resets limit without previously limiting anything.
3584 if (!s->limit_view)
3585 return NULL;
3588 * User could have pressed Ctrl+L, which refreshed the
3589 * commit queues, it means we can't save previously
3590 * (before limit took place) displayed entries,
3591 * because they would point to already free'ed memory,
3592 * so we are forced to always select first entry of
3593 * the queue.
3595 s->commits = &s->real_commits;
3596 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3597 s->selected_entry = s->first_displayed_entry;
3598 s->selected = 0;
3599 s->limit_view = 0;
3601 return NULL;
3604 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3605 return NULL;
3607 s->limit_view = 1;
3609 /* Clear the screen while loading limit view */
3610 s->first_displayed_entry = NULL;
3611 s->last_displayed_entry = NULL;
3612 s->selected_entry = NULL;
3613 s->commits = &s->limit_commits;
3615 /* Prepare limit queue for new search */
3616 free_commits(&s->limit_commits);
3617 s->limit_commits.ncommits = 0;
3619 /* First process commits, which are in queue already */
3620 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3621 int have_match = 0;
3623 err = match_commit(&have_match, entry->id,
3624 entry->commit, &s->limit_regex);
3625 if (err)
3626 return err;
3628 if (have_match) {
3629 struct commit_queue_entry *matched;
3631 matched = alloc_commit_queue_entry(entry->commit,
3632 entry->id);
3633 if (matched == NULL) {
3634 err = got_error_from_errno(
3635 "alloc_commit_queue_entry");
3636 break;
3638 matched->commit = entry->commit;
3639 got_object_commit_retain(entry->commit);
3641 matched->idx = s->limit_commits.ncommits;
3642 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3643 matched, entry);
3644 s->limit_commits.ncommits++;
3648 /* Second process all the commits, until we fill the screen */
3649 if (s->limit_commits.ncommits < view->nlines - 1 &&
3650 !s->thread_args.log_complete) {
3651 s->thread_args.commits_needed +=
3652 view->nlines - s->limit_commits.ncommits - 1;
3653 err = trigger_log_thread(view, 1);
3654 if (err)
3655 return err;
3658 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3659 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3660 s->selected = 0;
3662 return NULL;
3665 static const struct got_error *
3666 search_start_log_view(struct tog_view *view)
3668 struct tog_log_view_state *s = &view->state.log;
3670 s->matched_entry = NULL;
3671 s->search_entry = NULL;
3672 return NULL;
3675 static const struct got_error *
3676 search_next_log_view(struct tog_view *view)
3678 const struct got_error *err = NULL;
3679 struct tog_log_view_state *s = &view->state.log;
3680 struct commit_queue_entry *entry;
3682 /* Display progress update in log view. */
3683 show_log_view(view);
3684 update_panels();
3685 doupdate();
3687 if (s->search_entry) {
3688 if (!using_mock_io) {
3689 int errcode, ch;
3691 errcode = pthread_mutex_unlock(&tog_mutex);
3692 if (errcode)
3693 return got_error_set_errno(errcode,
3694 "pthread_mutex_unlock");
3695 ch = wgetch(view->window);
3696 errcode = pthread_mutex_lock(&tog_mutex);
3697 if (errcode)
3698 return got_error_set_errno(errcode,
3699 "pthread_mutex_lock");
3700 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3701 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3702 return NULL;
3705 if (view->searching == TOG_SEARCH_FORWARD)
3706 entry = TAILQ_NEXT(s->search_entry, entry);
3707 else
3708 entry = TAILQ_PREV(s->search_entry,
3709 commit_queue_head, entry);
3710 } else if (s->matched_entry) {
3712 * If the user has moved the cursor after we hit a match,
3713 * the position from where we should continue searching
3714 * might have changed.
3716 if (view->searching == TOG_SEARCH_FORWARD)
3717 entry = TAILQ_NEXT(s->selected_entry, entry);
3718 else
3719 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3720 entry);
3721 } else {
3722 entry = s->selected_entry;
3725 while (1) {
3726 int have_match = 0;
3728 if (entry == NULL) {
3729 if (s->thread_args.log_complete ||
3730 view->searching == TOG_SEARCH_BACKWARD) {
3731 view->search_next_done =
3732 (s->matched_entry == NULL ?
3733 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3734 s->search_entry = NULL;
3735 return NULL;
3738 * Poke the log thread for more commits and return,
3739 * allowing the main loop to make progress. Search
3740 * will resume at s->search_entry once we come back.
3742 s->search_entry = s->selected_entry;
3743 s->thread_args.commits_needed++;
3744 return trigger_log_thread(view, 0);
3747 err = match_commit(&have_match, entry->id, entry->commit,
3748 &view->regex);
3749 if (err)
3750 break;
3751 if (have_match) {
3752 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3753 s->matched_entry = entry;
3754 break;
3757 s->search_entry = entry;
3758 if (view->searching == TOG_SEARCH_FORWARD)
3759 entry = TAILQ_NEXT(entry, entry);
3760 else
3761 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3764 if (s->matched_entry) {
3765 int cur = s->selected_entry->idx;
3766 while (cur < s->matched_entry->idx) {
3767 err = input_log_view(NULL, view, KEY_DOWN);
3768 if (err)
3769 return err;
3770 cur++;
3772 while (cur > s->matched_entry->idx) {
3773 err = input_log_view(NULL, view, KEY_UP);
3774 if (err)
3775 return err;
3776 cur--;
3780 s->search_entry = NULL;
3782 return NULL;
3785 static const struct got_error *
3786 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3787 struct got_repository *repo, const char *head_ref_name,
3788 const char *in_repo_path, int log_branches,
3789 struct got_worktree *worktree)
3791 const struct got_error *err = NULL;
3792 struct tog_log_view_state *s = &view->state.log;
3793 struct got_repository *thread_repo = NULL;
3794 struct got_commit_graph *thread_graph = NULL;
3795 int errcode;
3797 if (in_repo_path != s->in_repo_path) {
3798 free(s->in_repo_path);
3799 s->in_repo_path = strdup(in_repo_path);
3800 if (s->in_repo_path == NULL) {
3801 err = got_error_from_errno("strdup");
3802 goto done;
3806 /* The commit queue only contains commits being displayed. */
3807 TAILQ_INIT(&s->real_commits.head);
3808 s->real_commits.ncommits = 0;
3809 s->commits = &s->real_commits;
3811 TAILQ_INIT(&s->limit_commits.head);
3812 s->limit_view = 0;
3813 s->limit_commits.ncommits = 0;
3815 s->repo = repo;
3816 if (head_ref_name) {
3817 s->head_ref_name = strdup(head_ref_name);
3818 if (s->head_ref_name == NULL) {
3819 err = got_error_from_errno("strdup");
3820 goto done;
3823 s->start_id = got_object_id_dup(start_id);
3824 if (s->start_id == NULL) {
3825 err = got_error_from_errno("got_object_id_dup");
3826 goto done;
3828 s->log_branches = log_branches;
3829 s->use_committer = 1;
3831 STAILQ_INIT(&s->colors);
3832 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3833 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3834 get_color_value("TOG_COLOR_COMMIT"));
3835 if (err)
3836 goto done;
3837 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3838 get_color_value("TOG_COLOR_AUTHOR"));
3839 if (err)
3840 goto done;
3841 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3842 get_color_value("TOG_COLOR_DATE"));
3843 if (err)
3844 goto done;
3847 view->show = show_log_view;
3848 view->input = input_log_view;
3849 view->resize = resize_log_view;
3850 view->close = close_log_view;
3851 view->search_start = search_start_log_view;
3852 view->search_next = search_next_log_view;
3854 if (s->thread_args.pack_fds == NULL) {
3855 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3856 if (err)
3857 goto done;
3859 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3860 s->thread_args.pack_fds);
3861 if (err)
3862 goto done;
3863 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3864 !s->log_branches);
3865 if (err)
3866 goto done;
3867 err = got_commit_graph_bfsort(thread_graph, s->start_id,
3868 s->repo, NULL, NULL);
3869 if (err)
3870 goto done;
3872 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3873 if (errcode) {
3874 err = got_error_set_errno(errcode, "pthread_cond_init");
3875 goto done;
3877 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3878 if (errcode) {
3879 err = got_error_set_errno(errcode, "pthread_cond_init");
3880 goto done;
3883 if (using_mock_io) {
3884 int rc;
3886 rc = pthread_cond_init(&s->thread_args.log_loaded, NULL);
3887 if (rc)
3888 return got_error_set_errno(rc, "pthread_cond_init");
3891 s->thread_args.commits_needed = view->nlines;
3892 s->thread_args.graph = thread_graph;
3893 s->thread_args.real_commits = &s->real_commits;
3894 s->thread_args.limit_commits = &s->limit_commits;
3895 s->thread_args.in_repo_path = s->in_repo_path;
3896 s->thread_args.start_id = s->start_id;
3897 s->thread_args.repo = thread_repo;
3898 s->thread_args.log_complete = 0;
3899 s->thread_args.quit = &s->quit;
3900 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3901 s->thread_args.selected_entry = &s->selected_entry;
3902 s->thread_args.searching = &view->searching;
3903 s->thread_args.search_next_done = &view->search_next_done;
3904 s->thread_args.regex = &view->regex;
3905 s->thread_args.limiting = &s->limit_view;
3906 s->thread_args.limit_regex = &s->limit_regex;
3907 s->thread_args.limit_commits = &s->limit_commits;
3908 s->thread_args.worktree = worktree;
3909 if (worktree)
3910 s->thread_args.need_commit_marker = 1;
3911 done:
3912 if (err) {
3913 if (view->close == NULL)
3914 close_log_view(view);
3915 view_close(view);
3917 return err;
3920 static const struct got_error *
3921 show_log_view(struct tog_view *view)
3923 const struct got_error *err;
3924 struct tog_log_view_state *s = &view->state.log;
3926 if (s->thread == NULL) {
3927 int errcode = pthread_create(&s->thread, NULL, log_thread,
3928 &s->thread_args);
3929 if (errcode)
3930 return got_error_set_errno(errcode, "pthread_create");
3931 if (s->thread_args.commits_needed > 0) {
3932 err = trigger_log_thread(view, 1);
3933 if (err)
3934 return err;
3938 return draw_commits(view);
3941 static void
3942 log_move_cursor_up(struct tog_view *view, int page, int home)
3944 struct tog_log_view_state *s = &view->state.log;
3946 if (s->first_displayed_entry == NULL)
3947 return;
3948 if (s->selected_entry->idx == 0)
3949 view->count = 0;
3951 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3952 || home)
3953 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3955 if (!page && !home && s->selected > 0)
3956 --s->selected;
3957 else
3958 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3960 select_commit(s);
3961 return;
3964 static const struct got_error *
3965 log_move_cursor_down(struct tog_view *view, int page)
3967 struct tog_log_view_state *s = &view->state.log;
3968 const struct got_error *err = NULL;
3969 int eos = view->nlines - 2;
3971 if (s->first_displayed_entry == NULL)
3972 return NULL;
3974 if (s->thread_args.log_complete &&
3975 s->selected_entry->idx >= s->commits->ncommits - 1)
3976 return NULL;
3978 if (view_is_hsplit_top(view))
3979 --eos; /* border consumes the last line */
3981 if (!page) {
3982 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3983 ++s->selected;
3984 else
3985 err = log_scroll_down(view, 1);
3986 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3987 struct commit_queue_entry *entry;
3988 int n;
3990 s->selected = 0;
3991 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3992 s->last_displayed_entry = entry;
3993 for (n = 0; n <= eos; n++) {
3994 if (entry == NULL)
3995 break;
3996 s->first_displayed_entry = entry;
3997 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3999 if (n > 0)
4000 s->selected = n - 1;
4001 } else {
4002 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
4003 s->thread_args.log_complete)
4004 s->selected += MIN(page,
4005 s->commits->ncommits - s->selected_entry->idx - 1);
4006 else
4007 err = log_scroll_down(view, page);
4009 if (err)
4010 return err;
4013 * We might necessarily overshoot in horizontal
4014 * splits; if so, select the last displayed commit.
4016 if (s->first_displayed_entry && s->last_displayed_entry) {
4017 s->selected = MIN(s->selected,
4018 s->last_displayed_entry->idx -
4019 s->first_displayed_entry->idx);
4022 select_commit(s);
4024 if (s->thread_args.log_complete &&
4025 s->selected_entry->idx == s->commits->ncommits - 1)
4026 view->count = 0;
4028 return NULL;
4031 static void
4032 view_get_split(struct tog_view *view, int *y, int *x)
4034 *x = 0;
4035 *y = 0;
4037 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
4038 if (view->child && view->child->resized_y)
4039 *y = view->child->resized_y;
4040 else if (view->resized_y)
4041 *y = view->resized_y;
4042 else
4043 *y = view_split_begin_y(view->lines);
4044 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
4045 if (view->child && view->child->resized_x)
4046 *x = view->child->resized_x;
4047 else if (view->resized_x)
4048 *x = view->resized_x;
4049 else
4050 *x = view_split_begin_x(view->begin_x);
4054 /* Split view horizontally at y and offset view->state->selected line. */
4055 static const struct got_error *
4056 view_init_hsplit(struct tog_view *view, int y)
4058 const struct got_error *err = NULL;
4060 view->nlines = y;
4061 view->ncols = COLS;
4062 err = view_resize(view);
4063 if (err)
4064 return err;
4066 err = offset_selection_down(view);
4068 return err;
4071 static const struct got_error *
4072 log_goto_line(struct tog_view *view, int nlines)
4074 const struct got_error *err = NULL;
4075 struct tog_log_view_state *s = &view->state.log;
4076 int g, idx = s->selected_entry->idx;
4078 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
4079 return NULL;
4081 g = view->gline;
4082 view->gline = 0;
4084 if (g >= s->first_displayed_entry->idx + 1 &&
4085 g <= s->last_displayed_entry->idx + 1 &&
4086 g - s->first_displayed_entry->idx - 1 < nlines) {
4087 s->selected = g - s->first_displayed_entry->idx - 1;
4088 select_commit(s);
4089 return NULL;
4092 if (idx + 1 < g) {
4093 err = log_move_cursor_down(view, g - idx - 1);
4094 if (!err && g > s->selected_entry->idx + 1)
4095 err = log_move_cursor_down(view,
4096 g - s->first_displayed_entry->idx - 1);
4097 if (err)
4098 return err;
4099 } else if (idx + 1 > g)
4100 log_move_cursor_up(view, idx - g + 1, 0);
4102 if (g < nlines && s->first_displayed_entry->idx == 0)
4103 s->selected = g - 1;
4105 select_commit(s);
4106 return NULL;
4110 static void
4111 horizontal_scroll_input(struct tog_view *view, int ch)
4114 switch (ch) {
4115 case KEY_LEFT:
4116 case 'h':
4117 view->x -= MIN(view->x, 2);
4118 if (view->x <= 0)
4119 view->count = 0;
4120 break;
4121 case KEY_RIGHT:
4122 case 'l':
4123 if (view->x + view->ncols / 2 < view->maxx)
4124 view->x += 2;
4125 else
4126 view->count = 0;
4127 break;
4128 case '0':
4129 view->x = 0;
4130 break;
4131 case '$':
4132 view->x = MAX(view->maxx - view->ncols / 2, 0);
4133 view->count = 0;
4134 break;
4135 default:
4136 break;
4140 static const struct got_error *
4141 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
4143 const struct got_error *err = NULL;
4144 struct tog_log_view_state *s = &view->state.log;
4145 int eos, nscroll;
4147 if (s->thread_args.load_all) {
4148 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
4149 s->thread_args.load_all = 0;
4150 else if (s->thread_args.log_complete) {
4151 err = log_move_cursor_down(view, s->commits->ncommits);
4152 s->thread_args.load_all = 0;
4154 if (err)
4155 return err;
4158 eos = nscroll = view->nlines - 1;
4159 if (view_is_hsplit_top(view))
4160 --eos; /* border */
4162 if (view->gline)
4163 return log_goto_line(view, eos);
4165 switch (ch) {
4166 case '&':
4167 err = limit_log_view(view);
4168 break;
4169 case 'q':
4170 s->quit = 1;
4171 break;
4172 case '0':
4173 case '$':
4174 case KEY_RIGHT:
4175 case 'l':
4176 case KEY_LEFT:
4177 case 'h':
4178 horizontal_scroll_input(view, ch);
4179 break;
4180 case 'k':
4181 case KEY_UP:
4182 case '<':
4183 case ',':
4184 case CTRL('p'):
4185 log_move_cursor_up(view, 0, 0);
4186 break;
4187 case 'g':
4188 case '=':
4189 case KEY_HOME:
4190 log_move_cursor_up(view, 0, 1);
4191 view->count = 0;
4192 break;
4193 case CTRL('u'):
4194 case 'u':
4195 nscroll /= 2;
4196 /* FALL THROUGH */
4197 case KEY_PPAGE:
4198 case CTRL('b'):
4199 case 'b':
4200 log_move_cursor_up(view, nscroll, 0);
4201 break;
4202 case 'j':
4203 case KEY_DOWN:
4204 case '>':
4205 case '.':
4206 case CTRL('n'):
4207 err = log_move_cursor_down(view, 0);
4208 break;
4209 case '@':
4210 s->use_committer = !s->use_committer;
4211 view->action = s->use_committer ?
4212 "show committer" : "show commit author";
4213 break;
4214 case 'G':
4215 case '*':
4216 case KEY_END: {
4217 /* We don't know yet how many commits, so we're forced to
4218 * traverse them all. */
4219 view->count = 0;
4220 s->thread_args.load_all = 1;
4221 if (!s->thread_args.log_complete)
4222 return trigger_log_thread(view, 0);
4223 err = log_move_cursor_down(view, s->commits->ncommits);
4224 s->thread_args.load_all = 0;
4225 break;
4227 case CTRL('d'):
4228 case 'd':
4229 nscroll /= 2;
4230 /* FALL THROUGH */
4231 case KEY_NPAGE:
4232 case CTRL('f'):
4233 case 'f':
4234 case ' ':
4235 err = log_move_cursor_down(view, nscroll);
4236 break;
4237 case KEY_RESIZE:
4238 if (s->selected > view->nlines - 2)
4239 s->selected = view->nlines - 2;
4240 if (s->selected > s->commits->ncommits - 1)
4241 s->selected = s->commits->ncommits - 1;
4242 select_commit(s);
4243 if (s->commits->ncommits < view->nlines - 1 &&
4244 !s->thread_args.log_complete) {
4245 s->thread_args.commits_needed += (view->nlines - 1) -
4246 s->commits->ncommits;
4247 err = trigger_log_thread(view, 1);
4249 break;
4250 case KEY_ENTER:
4251 case '\r':
4252 view->count = 0;
4253 if (s->selected_entry == NULL)
4254 break;
4255 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4256 break;
4257 case 'T':
4258 view->count = 0;
4259 if (s->selected_entry == NULL)
4260 break;
4261 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4262 break;
4263 case KEY_BACKSPACE:
4264 case CTRL('l'):
4265 case 'B':
4266 view->count = 0;
4267 if (ch == KEY_BACKSPACE &&
4268 got_path_is_root_dir(s->in_repo_path))
4269 break;
4270 err = stop_log_thread(s);
4271 if (err)
4272 return err;
4273 if (ch == KEY_BACKSPACE) {
4274 char *parent_path;
4275 err = got_path_dirname(&parent_path, s->in_repo_path);
4276 if (err)
4277 return err;
4278 free(s->in_repo_path);
4279 s->in_repo_path = parent_path;
4280 s->thread_args.in_repo_path = s->in_repo_path;
4281 } else if (ch == CTRL('l')) {
4282 struct got_object_id *start_id;
4283 err = got_repo_match_object_id(&start_id, NULL,
4284 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4285 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4286 if (err) {
4287 if (s->head_ref_name == NULL ||
4288 err->code != GOT_ERR_NOT_REF)
4289 return err;
4290 /* Try to cope with deleted references. */
4291 free(s->head_ref_name);
4292 s->head_ref_name = NULL;
4293 err = got_repo_match_object_id(&start_id,
4294 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4295 &tog_refs, s->repo);
4296 if (err)
4297 return err;
4299 free(s->start_id);
4300 s->start_id = start_id;
4301 s->thread_args.start_id = s->start_id;
4302 } else /* 'B' */
4303 s->log_branches = !s->log_branches;
4305 if (s->thread_args.pack_fds == NULL) {
4306 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4307 if (err)
4308 return err;
4310 err = got_repo_open(&s->thread_args.repo,
4311 got_repo_get_path(s->repo), NULL,
4312 s->thread_args.pack_fds);
4313 if (err)
4314 return err;
4315 tog_free_refs();
4316 err = tog_load_refs(s->repo, 0);
4317 if (err)
4318 return err;
4319 err = got_commit_graph_open(&s->thread_args.graph,
4320 s->in_repo_path, !s->log_branches);
4321 if (err)
4322 return err;
4323 err = got_commit_graph_bfsort(s->thread_args.graph,
4324 s->start_id, s->repo, NULL, NULL);
4325 if (err)
4326 return err;
4327 free_commits(&s->real_commits);
4328 free_commits(&s->limit_commits);
4329 s->first_displayed_entry = NULL;
4330 s->last_displayed_entry = NULL;
4331 s->selected_entry = NULL;
4332 s->selected = 0;
4333 s->thread_args.log_complete = 0;
4334 s->quit = 0;
4335 s->thread_args.commits_needed = view->lines;
4336 s->matched_entry = NULL;
4337 s->search_entry = NULL;
4338 view->offset = 0;
4339 break;
4340 case 'R':
4341 view->count = 0;
4342 err = view_request_new(new_view, view, TOG_VIEW_REF);
4343 break;
4344 default:
4345 view->count = 0;
4346 break;
4349 return err;
4352 static const struct got_error *
4353 apply_unveil(const char *repo_path, const char *worktree_path)
4355 const struct got_error *error;
4357 #ifdef PROFILE
4358 if (unveil("gmon.out", "rwc") != 0)
4359 return got_error_from_errno2("unveil", "gmon.out");
4360 #endif
4361 if (repo_path && unveil(repo_path, "r") != 0)
4362 return got_error_from_errno2("unveil", repo_path);
4364 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4365 return got_error_from_errno2("unveil", worktree_path);
4367 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4368 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4370 error = got_privsep_unveil_exec_helpers();
4371 if (error != NULL)
4372 return error;
4374 if (unveil(NULL, NULL) != 0)
4375 return got_error_from_errno("unveil");
4377 return NULL;
4380 static const struct got_error *
4381 init_mock_term(const char *test_script_path)
4383 const struct got_error *err = NULL;
4384 const char *screen_dump_path;
4385 int in;
4387 if (test_script_path == NULL || *test_script_path == '\0')
4388 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4390 tog_io.f = fopen(test_script_path, "re");
4391 if (tog_io.f == NULL) {
4392 err = got_error_from_errno_fmt("fopen: %s",
4393 test_script_path);
4394 goto done;
4397 /* test mode, we don't want any output */
4398 tog_io.cout = fopen("/dev/null", "w+");
4399 if (tog_io.cout == NULL) {
4400 err = got_error_from_errno2("fopen", "/dev/null");
4401 goto done;
4404 in = dup(fileno(tog_io.cout));
4405 if (in == -1) {
4406 err = got_error_from_errno("dup");
4407 goto done;
4409 tog_io.cin = fdopen(in, "r");
4410 if (tog_io.cin == NULL) {
4411 err = got_error_from_errno("fdopen");
4412 close(in);
4413 goto done;
4416 screen_dump_path = getenv("TOG_SCR_DUMP");
4417 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4418 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4419 tog_io.sdump = fopen(screen_dump_path, "we");
4420 if (tog_io.sdump == NULL) {
4421 err = got_error_from_errno2("fopen", screen_dump_path);
4422 goto done;
4425 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4426 err = got_error_from_errno("fseeko");
4427 goto done;
4430 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4431 err = got_error_msg(GOT_ERR_IO,
4432 "newterm: failed to initialise curses");
4434 using_mock_io = 1;
4436 done:
4437 if (err)
4438 tog_io_close();
4439 return err;
4442 static void
4443 init_curses(void)
4445 if (using_mock_io) /* In test mode we use a fake terminal */
4446 return;
4448 initscr();
4450 cbreak();
4451 halfdelay(1); /* Fast refresh while initial view is loading. */
4452 noecho();
4453 nonl();
4454 intrflush(stdscr, FALSE);
4455 keypad(stdscr, TRUE);
4456 curs_set(0);
4457 if (getenv("TOG_COLORS") != NULL) {
4458 start_color();
4459 use_default_colors();
4462 return;
4465 static const struct got_error *
4466 set_tog_base_commit(struct got_repository *repo, struct got_worktree *worktree)
4468 tog_base_commit.id = got_object_id_dup(
4469 got_worktree_get_base_commit_id(worktree));
4470 if (tog_base_commit.id == NULL)
4471 return got_error_from_errno( "got_object_id_dup");
4473 return NULL;
4476 static const struct got_error *
4477 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4478 struct got_repository *repo, struct got_worktree *worktree)
4480 const struct got_error *err = NULL;
4482 if (argc == 0) {
4483 *in_repo_path = strdup("/");
4484 if (*in_repo_path == NULL)
4485 return got_error_from_errno("strdup");
4486 return NULL;
4489 if (worktree) {
4490 const char *prefix = got_worktree_get_path_prefix(worktree);
4491 char *p;
4493 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4494 if (err)
4495 return err;
4496 if (asprintf(in_repo_path, "%s%s%s", prefix,
4497 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4498 p) == -1) {
4499 err = got_error_from_errno("asprintf");
4500 *in_repo_path = NULL;
4502 free(p);
4503 } else
4504 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4506 return err;
4509 static const struct got_error *
4510 cmd_log(int argc, char *argv[])
4512 const struct got_error *error;
4513 struct got_repository *repo = NULL;
4514 struct got_worktree *worktree = NULL;
4515 struct got_object_id *start_id = NULL;
4516 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4517 char *keyword_idstr = NULL, *start_commit = NULL, *label = NULL;
4518 struct got_reference *ref = NULL;
4519 const char *head_ref_name = NULL;
4520 int ch, log_branches = 0;
4521 struct tog_view *view;
4522 int *pack_fds = NULL;
4524 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4525 switch (ch) {
4526 case 'b':
4527 log_branches = 1;
4528 break;
4529 case 'c':
4530 start_commit = optarg;
4531 break;
4532 case 'r':
4533 repo_path = realpath(optarg, NULL);
4534 if (repo_path == NULL)
4535 return got_error_from_errno2("realpath",
4536 optarg);
4537 break;
4538 default:
4539 usage_log();
4540 /* NOTREACHED */
4544 argc -= optind;
4545 argv += optind;
4547 if (argc > 1)
4548 usage_log();
4550 error = got_repo_pack_fds_open(&pack_fds);
4551 if (error != NULL)
4552 goto done;
4554 if (repo_path == NULL) {
4555 cwd = getcwd(NULL, 0);
4556 if (cwd == NULL) {
4557 error = got_error_from_errno("getcwd");
4558 goto done;
4560 error = got_worktree_open(&worktree, cwd, NULL);
4561 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4562 goto done;
4563 if (worktree)
4564 repo_path =
4565 strdup(got_worktree_get_repo_path(worktree));
4566 else
4567 repo_path = strdup(cwd);
4568 if (repo_path == NULL) {
4569 error = got_error_from_errno("strdup");
4570 goto done;
4574 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4575 if (error != NULL)
4576 goto done;
4578 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4579 repo, worktree);
4580 if (error)
4581 goto done;
4583 init_curses();
4585 error = apply_unveil(got_repo_get_path(repo),
4586 worktree ? got_worktree_get_root_path(worktree) : NULL);
4587 if (error)
4588 goto done;
4590 /* already loaded by tog_log_with_path()? */
4591 if (TAILQ_EMPTY(&tog_refs)) {
4592 error = tog_load_refs(repo, 0);
4593 if (error)
4594 goto done;
4597 if (start_commit == NULL) {
4598 error = got_repo_match_object_id(&start_id, &label,
4599 worktree ? got_worktree_get_head_ref_name(worktree) :
4600 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4601 if (error)
4602 goto done;
4603 head_ref_name = label;
4604 } else {
4605 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4606 repo, worktree);
4607 if (error != NULL)
4608 goto done;
4609 if (keyword_idstr != NULL)
4610 start_commit = keyword_idstr;
4612 error = got_ref_open(&ref, repo, start_commit, 0);
4613 if (error == NULL)
4614 head_ref_name = got_ref_get_name(ref);
4615 else if (error->code != GOT_ERR_NOT_REF)
4616 goto done;
4617 error = got_repo_match_object_id(&start_id, NULL,
4618 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4619 if (error)
4620 goto done;
4623 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4624 if (view == NULL) {
4625 error = got_error_from_errno("view_open");
4626 goto done;
4629 if (worktree) {
4630 error = set_tog_base_commit(repo, worktree);
4631 if (error != NULL)
4632 goto done;
4635 error = open_log_view(view, start_id, repo, head_ref_name,
4636 in_repo_path, log_branches, worktree);
4637 if (error)
4638 goto done;
4640 if (worktree) {
4641 /* The work tree will be closed by the log thread. */
4642 worktree = NULL;
4645 error = view_loop(view);
4647 done:
4648 free(tog_base_commit.id);
4649 free(keyword_idstr);
4650 free(in_repo_path);
4651 free(repo_path);
4652 free(cwd);
4653 free(start_id);
4654 free(label);
4655 if (ref)
4656 got_ref_close(ref);
4657 if (repo) {
4658 const struct got_error *close_err = got_repo_close(repo);
4659 if (error == NULL)
4660 error = close_err;
4662 if (worktree)
4663 got_worktree_close(worktree);
4664 if (pack_fds) {
4665 const struct got_error *pack_err =
4666 got_repo_pack_fds_close(pack_fds);
4667 if (error == NULL)
4668 error = pack_err;
4670 tog_free_refs();
4671 return error;
4674 __dead static void
4675 usage_diff(void)
4677 endwin();
4678 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4679 "object1 object2\n", getprogname());
4680 exit(1);
4683 static int
4684 match_line(const char *line, regex_t *regex, size_t nmatch,
4685 regmatch_t *regmatch)
4687 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4690 static struct tog_color *
4691 match_color(struct tog_colors *colors, const char *line)
4693 struct tog_color *tc = NULL;
4695 STAILQ_FOREACH(tc, colors, entry) {
4696 if (match_line(line, &tc->regex, 0, NULL))
4697 return tc;
4700 return NULL;
4703 static const struct got_error *
4704 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4705 WINDOW *window, int skipcol, regmatch_t *regmatch)
4707 const struct got_error *err = NULL;
4708 char *exstr = NULL;
4709 wchar_t *wline = NULL;
4710 int rme, rms, n, width, scrollx;
4711 int width0 = 0, width1 = 0, width2 = 0;
4712 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4714 *wtotal = 0;
4716 rms = regmatch->rm_so;
4717 rme = regmatch->rm_eo;
4719 err = expand_tab(&exstr, line);
4720 if (err)
4721 return err;
4723 /* Split the line into 3 segments, according to match offsets. */
4724 seg0 = strndup(exstr, rms);
4725 if (seg0 == NULL) {
4726 err = got_error_from_errno("strndup");
4727 goto done;
4729 seg1 = strndup(exstr + rms, rme - rms);
4730 if (seg1 == NULL) {
4731 err = got_error_from_errno("strndup");
4732 goto done;
4734 seg2 = strdup(exstr + rme);
4735 if (seg2 == NULL) {
4736 err = got_error_from_errno("strndup");
4737 goto done;
4740 /* draw up to matched token if we haven't scrolled past it */
4741 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4742 col_tab_align, 1);
4743 if (err)
4744 goto done;
4745 n = MAX(width0 - skipcol, 0);
4746 if (n) {
4747 free(wline);
4748 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4749 wlimit, col_tab_align, 1);
4750 if (err)
4751 goto done;
4752 waddwstr(window, &wline[scrollx]);
4753 wlimit -= width;
4754 *wtotal += width;
4757 if (wlimit > 0) {
4758 int i = 0, w = 0;
4759 size_t wlen;
4761 free(wline);
4762 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4763 col_tab_align, 1);
4764 if (err)
4765 goto done;
4766 wlen = wcslen(wline);
4767 while (i < wlen) {
4768 width = wcwidth(wline[i]);
4769 if (width == -1) {
4770 /* should not happen, tabs are expanded */
4771 err = got_error(GOT_ERR_RANGE);
4772 goto done;
4774 if (width0 + w + width > skipcol)
4775 break;
4776 w += width;
4777 i++;
4779 /* draw (visible part of) matched token (if scrolled into it) */
4780 if (width1 - w > 0) {
4781 wattron(window, A_STANDOUT);
4782 waddwstr(window, &wline[i]);
4783 wattroff(window, A_STANDOUT);
4784 wlimit -= (width1 - w);
4785 *wtotal += (width1 - w);
4789 if (wlimit > 0) { /* draw rest of line */
4790 free(wline);
4791 if (skipcol > width0 + width1) {
4792 err = format_line(&wline, &width2, &scrollx, seg2,
4793 skipcol - (width0 + width1), wlimit,
4794 col_tab_align, 1);
4795 if (err)
4796 goto done;
4797 waddwstr(window, &wline[scrollx]);
4798 } else {
4799 err = format_line(&wline, &width2, NULL, seg2, 0,
4800 wlimit, col_tab_align, 1);
4801 if (err)
4802 goto done;
4803 waddwstr(window, wline);
4805 *wtotal += width2;
4807 done:
4808 free(wline);
4809 free(exstr);
4810 free(seg0);
4811 free(seg1);
4812 free(seg2);
4813 return err;
4816 static int
4817 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4819 FILE *f = NULL;
4820 int *eof, *first, *selected;
4822 if (view->type == TOG_VIEW_DIFF) {
4823 struct tog_diff_view_state *s = &view->state.diff;
4825 first = &s->first_displayed_line;
4826 selected = first;
4827 eof = &s->eof;
4828 f = s->f;
4829 } else if (view->type == TOG_VIEW_HELP) {
4830 struct tog_help_view_state *s = &view->state.help;
4832 first = &s->first_displayed_line;
4833 selected = first;
4834 eof = &s->eof;
4835 f = s->f;
4836 } else if (view->type == TOG_VIEW_BLAME) {
4837 struct tog_blame_view_state *s = &view->state.blame;
4839 first = &s->first_displayed_line;
4840 selected = &s->selected_line;
4841 eof = &s->eof;
4842 f = s->blame.f;
4843 } else
4844 return 0;
4846 /* Center gline in the middle of the page like vi(1). */
4847 if (*lineno < view->gline - (view->nlines - 3) / 2)
4848 return 0;
4849 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4850 rewind(f);
4851 *eof = 0;
4852 *first = 1;
4853 *lineno = 0;
4854 *nprinted = 0;
4855 return 0;
4858 *selected = view->gline <= (view->nlines - 3) / 2 ?
4859 view->gline : (view->nlines - 3) / 2 + 1;
4860 view->gline = 0;
4862 return 1;
4865 static const struct got_error *
4866 draw_file(struct tog_view *view, const char *header)
4868 struct tog_diff_view_state *s = &view->state.diff;
4869 regmatch_t *regmatch = &view->regmatch;
4870 const struct got_error *err;
4871 int nprinted = 0;
4872 char *line;
4873 size_t linesize = 0;
4874 ssize_t linelen;
4875 wchar_t *wline;
4876 int width;
4877 int max_lines = view->nlines;
4878 int nlines = s->nlines;
4879 off_t line_offset;
4881 s->lineno = s->first_displayed_line - 1;
4882 line_offset = s->lines[s->first_displayed_line - 1].offset;
4883 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4884 return got_error_from_errno("fseek");
4886 werase(view->window);
4888 if (view->gline > s->nlines - 1)
4889 view->gline = s->nlines - 1;
4891 if (header) {
4892 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4893 1 : view->gline - (view->nlines - 3) / 2 :
4894 s->lineno + s->selected_line;
4896 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4897 return got_error_from_errno("asprintf");
4898 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4899 0, 0);
4900 free(line);
4901 if (err)
4902 return err;
4904 if (view_needs_focus_indication(view))
4905 wstandout(view->window);
4906 waddwstr(view->window, wline);
4907 free(wline);
4908 wline = NULL;
4909 while (width++ < view->ncols)
4910 waddch(view->window, ' ');
4911 if (view_needs_focus_indication(view))
4912 wstandend(view->window);
4914 if (max_lines <= 1)
4915 return NULL;
4916 max_lines--;
4919 s->eof = 0;
4920 view->maxx = 0;
4921 line = NULL;
4922 while (max_lines > 0 && nprinted < max_lines) {
4923 enum got_diff_line_type linetype;
4924 attr_t attr = 0;
4926 linelen = getline(&line, &linesize, s->f);
4927 if (linelen == -1) {
4928 if (feof(s->f)) {
4929 s->eof = 1;
4930 break;
4932 free(line);
4933 return got_ferror(s->f, GOT_ERR_IO);
4936 if (++s->lineno < s->first_displayed_line)
4937 continue;
4938 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4939 continue;
4940 if (s->lineno == view->hiline)
4941 attr = A_STANDOUT;
4943 /* Set view->maxx based on full line length. */
4944 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4945 view->x ? 1 : 0);
4946 if (err) {
4947 free(line);
4948 return err;
4950 view->maxx = MAX(view->maxx, width);
4951 free(wline);
4952 wline = NULL;
4954 linetype = s->lines[s->lineno].type;
4955 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4956 linetype < GOT_DIFF_LINE_CONTEXT)
4957 attr |= COLOR_PAIR(linetype);
4958 if (attr)
4959 wattron(view->window, attr);
4960 if (s->first_displayed_line + nprinted == s->matched_line &&
4961 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4962 err = add_matched_line(&width, line, view->ncols, 0,
4963 view->window, view->x, regmatch);
4964 if (err) {
4965 free(line);
4966 return err;
4968 } else {
4969 int skip;
4970 err = format_line(&wline, &width, &skip, line,
4971 view->x, view->ncols, 0, view->x ? 1 : 0);
4972 if (err) {
4973 free(line);
4974 return err;
4976 waddwstr(view->window, &wline[skip]);
4977 free(wline);
4978 wline = NULL;
4980 if (s->lineno == view->hiline) {
4981 /* highlight full gline length */
4982 while (width++ < view->ncols)
4983 waddch(view->window, ' ');
4984 } else {
4985 if (width <= view->ncols - 1)
4986 waddch(view->window, '\n');
4988 if (attr)
4989 wattroff(view->window, attr);
4990 if (++nprinted == 1)
4991 s->first_displayed_line = s->lineno;
4993 free(line);
4994 if (nprinted >= 1)
4995 s->last_displayed_line = s->first_displayed_line +
4996 (nprinted - 1);
4997 else
4998 s->last_displayed_line = s->first_displayed_line;
5000 view_border(view);
5002 if (s->eof) {
5003 while (nprinted < view->nlines) {
5004 waddch(view->window, '\n');
5005 nprinted++;
5008 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
5009 view->ncols, 0, 0);
5010 if (err) {
5011 return err;
5014 wstandout(view->window);
5015 waddwstr(view->window, wline);
5016 free(wline);
5017 wline = NULL;
5018 wstandend(view->window);
5021 return NULL;
5024 static char *
5025 get_datestr(time_t *time, char *datebuf)
5027 struct tm mytm, *tm;
5028 char *p, *s;
5030 tm = gmtime_r(time, &mytm);
5031 if (tm == NULL)
5032 return NULL;
5033 s = asctime_r(tm, datebuf);
5034 if (s == NULL)
5035 return NULL;
5036 p = strchr(s, '\n');
5037 if (p)
5038 *p = '\0';
5039 return s;
5042 static const struct got_error *
5043 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
5044 off_t off, uint8_t type)
5046 struct got_diff_line *p;
5048 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
5049 if (p == NULL)
5050 return got_error_from_errno("reallocarray");
5051 *lines = p;
5052 (*lines)[*nlines].offset = off;
5053 (*lines)[*nlines].type = type;
5054 (*nlines)++;
5056 return NULL;
5059 static const struct got_error *
5060 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
5061 struct got_diff_line *s_lines, size_t s_nlines)
5063 struct got_diff_line *p;
5064 char buf[BUFSIZ];
5065 size_t i, r;
5067 if (fseeko(src, 0L, SEEK_SET) == -1)
5068 return got_error_from_errno("fseeko");
5070 for (;;) {
5071 r = fread(buf, 1, sizeof(buf), src);
5072 if (r == 0) {
5073 if (ferror(src))
5074 return got_error_from_errno("fread");
5075 if (feof(src))
5076 break;
5078 if (fwrite(buf, 1, r, dst) != r)
5079 return got_ferror(dst, GOT_ERR_IO);
5082 if (s_nlines == 0 && *d_nlines == 0)
5083 return NULL;
5086 * If commit info was in dst, increment line offsets
5087 * of the appended diff content, but skip s_lines[0]
5088 * because offset zero is already in *d_lines.
5090 if (*d_nlines > 0) {
5091 for (i = 1; i < s_nlines; ++i)
5092 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
5094 if (s_nlines > 0) {
5095 --s_nlines;
5096 ++s_lines;
5100 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
5101 if (p == NULL) {
5102 /* d_lines is freed in close_diff_view() */
5103 return got_error_from_errno("reallocarray");
5106 *d_lines = p;
5108 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
5109 *d_nlines += s_nlines;
5111 return NULL;
5114 static const struct got_error *
5115 write_commit_info(struct got_diff_line **lines, size_t *nlines,
5116 struct got_object_id *commit_id, struct got_reflist_head *refs,
5117 struct got_repository *repo, int ignore_ws, int force_text_diff,
5118 struct got_diffstat_cb_arg *dsa, FILE *outfile)
5120 const struct got_error *err = NULL;
5121 char datebuf[26], *datestr;
5122 struct got_commit_object *commit;
5123 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
5124 time_t committer_time;
5125 const char *author, *committer;
5126 char *refs_str = NULL;
5127 struct got_pathlist_entry *pe;
5128 off_t outoff = 0;
5129 int n;
5131 err = build_refs_str(&refs_str, refs, commit_id, repo);
5132 if (err)
5133 return err;
5135 err = got_object_open_as_commit(&commit, repo, commit_id);
5136 if (err)
5137 return err;
5139 err = got_object_id_str(&id_str, commit_id);
5140 if (err) {
5141 err = got_error_from_errno("got_object_id_str");
5142 goto done;
5145 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
5146 if (err)
5147 goto done;
5149 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
5150 refs_str ? refs_str : "", refs_str ? ")" : "");
5151 if (n < 0) {
5152 err = got_error_from_errno("fprintf");
5153 goto done;
5155 outoff += n;
5156 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
5157 if (err)
5158 goto done;
5160 n = fprintf(outfile, "from: %s\n",
5161 got_object_commit_get_author(commit));
5162 if (n < 0) {
5163 err = got_error_from_errno("fprintf");
5164 goto done;
5166 outoff += n;
5167 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
5168 if (err)
5169 goto done;
5171 author = got_object_commit_get_author(commit);
5172 committer = got_object_commit_get_committer(commit);
5173 if (strcmp(author, committer) != 0) {
5174 n = fprintf(outfile, "via: %s\n", committer);
5175 if (n < 0) {
5176 err = got_error_from_errno("fprintf");
5177 goto done;
5179 outoff += n;
5180 err = add_line_metadata(lines, nlines, outoff,
5181 GOT_DIFF_LINE_AUTHOR);
5182 if (err)
5183 goto done;
5185 committer_time = got_object_commit_get_committer_time(commit);
5186 datestr = get_datestr(&committer_time, datebuf);
5187 if (datestr) {
5188 n = fprintf(outfile, "date: %s UTC\n", datestr);
5189 if (n < 0) {
5190 err = got_error_from_errno("fprintf");
5191 goto done;
5193 outoff += n;
5194 err = add_line_metadata(lines, nlines, outoff,
5195 GOT_DIFF_LINE_DATE);
5196 if (err)
5197 goto done;
5199 if (got_object_commit_get_nparents(commit) > 1) {
5200 const struct got_object_id_queue *parent_ids;
5201 struct got_object_qid *qid;
5202 int pn = 1;
5203 parent_ids = got_object_commit_get_parent_ids(commit);
5204 STAILQ_FOREACH(qid, parent_ids, entry) {
5205 err = got_object_id_str(&id_str, &qid->id);
5206 if (err)
5207 goto done;
5208 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5209 if (n < 0) {
5210 err = got_error_from_errno("fprintf");
5211 goto done;
5213 outoff += n;
5214 err = add_line_metadata(lines, nlines, outoff,
5215 GOT_DIFF_LINE_META);
5216 if (err)
5217 goto done;
5218 free(id_str);
5219 id_str = NULL;
5223 err = got_object_commit_get_logmsg(&logmsg, commit);
5224 if (err)
5225 goto done;
5226 s = logmsg;
5227 while ((line = strsep(&s, "\n")) != NULL) {
5228 n = fprintf(outfile, "%s\n", line);
5229 if (n < 0) {
5230 err = got_error_from_errno("fprintf");
5231 goto done;
5233 outoff += n;
5234 err = add_line_metadata(lines, nlines, outoff,
5235 GOT_DIFF_LINE_LOGMSG);
5236 if (err)
5237 goto done;
5240 TAILQ_FOREACH(pe, dsa->paths, entry) {
5241 struct got_diff_changed_path *cp = pe->data;
5242 int pad = dsa->max_path_len - pe->path_len + 1;
5244 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5245 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5246 dsa->rm_cols + 1, cp->rm);
5247 if (n < 0) {
5248 err = got_error_from_errno("fprintf");
5249 goto done;
5251 outoff += n;
5252 err = add_line_metadata(lines, nlines, outoff,
5253 GOT_DIFF_LINE_CHANGES);
5254 if (err)
5255 goto done;
5258 fputc('\n', outfile);
5259 outoff++;
5260 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5261 if (err)
5262 goto done;
5264 n = fprintf(outfile,
5265 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5266 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5267 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5268 if (n < 0) {
5269 err = got_error_from_errno("fprintf");
5270 goto done;
5272 outoff += n;
5273 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5274 if (err)
5275 goto done;
5277 fputc('\n', outfile);
5278 outoff++;
5279 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5280 done:
5281 free(id_str);
5282 free(logmsg);
5283 free(refs_str);
5284 got_object_commit_close(commit);
5285 if (err) {
5286 free(*lines);
5287 *lines = NULL;
5288 *nlines = 0;
5290 return err;
5293 static const struct got_error *
5294 create_diff(struct tog_diff_view_state *s)
5296 const struct got_error *err = NULL;
5297 FILE *tmp_diff_file = NULL;
5298 int obj_type;
5299 struct got_diff_line *lines = NULL;
5300 struct got_pathlist_head changed_paths;
5301 struct got_commit_object *commit2 = NULL;
5303 TAILQ_INIT(&changed_paths);
5305 free(s->lines);
5306 s->lines = malloc(sizeof(*s->lines));
5307 if (s->lines == NULL)
5308 return got_error_from_errno("malloc");
5309 s->nlines = 0;
5311 if (s->f && fclose(s->f) == EOF) {
5312 s->f = NULL;
5313 return got_error_from_errno("fclose");
5316 s->f = got_opentemp();
5317 if (s->f == NULL)
5318 return got_error_from_errno("got_opentemp");
5320 tmp_diff_file = got_opentemp();
5321 if (tmp_diff_file == NULL)
5322 return got_error_from_errno("got_opentemp");
5324 if (s->id1)
5325 err = got_object_get_type(&obj_type, s->repo, s->id1);
5326 else
5327 err = got_object_get_type(&obj_type, s->repo, s->id2);
5328 if (err)
5329 goto done;
5331 switch (obj_type) {
5332 case GOT_OBJ_TYPE_BLOB:
5333 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5334 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5335 s->label1, s->label2, tog_diff_algo, s->diff_context,
5336 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5337 s->f);
5338 break;
5339 case GOT_OBJ_TYPE_TREE:
5340 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5341 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5342 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5343 s->force_text_diff, NULL, s->repo, s->f);
5344 break;
5345 case GOT_OBJ_TYPE_COMMIT: {
5346 const struct got_object_id_queue *parent_ids;
5347 struct got_object_qid *pid;
5348 struct got_reflist_head *refs;
5349 size_t nlines = 0;
5350 struct got_diffstat_cb_arg dsa = {
5351 0, 0, 0, 0, 0, 0,
5352 &changed_paths,
5353 s->ignore_whitespace,
5354 s->force_text_diff,
5355 tog_diff_algo
5358 lines = malloc(sizeof(*lines));
5359 if (lines == NULL) {
5360 err = got_error_from_errno("malloc");
5361 goto done;
5364 /* build diff first in tmp file then append to commit info */
5365 err = got_diff_objects_as_commits(&lines, &nlines,
5366 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5367 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5368 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5369 if (err)
5370 break;
5372 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5373 /* Show commit info if we're diffing to a parent/root commit. */
5374 if (s->id1 == NULL) {
5375 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5376 refs, s->repo, s->ignore_whitespace,
5377 s->force_text_diff, &dsa, s->f);
5378 if (err)
5379 goto done;
5380 } else {
5381 err = got_object_open_as_commit(&commit2, s->repo,
5382 s->id2);
5383 if (err)
5384 goto done;
5386 parent_ids = got_object_commit_get_parent_ids(commit2);
5387 STAILQ_FOREACH(pid, parent_ids, entry) {
5388 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5389 err = write_commit_info(&s->lines,
5390 &s->nlines, s->id2, refs, s->repo,
5391 s->ignore_whitespace,
5392 s->force_text_diff, &dsa, s->f);
5393 if (err)
5394 goto done;
5395 break;
5400 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5401 lines, nlines);
5402 break;
5404 default:
5405 err = got_error(GOT_ERR_OBJ_TYPE);
5406 break;
5408 done:
5409 free(lines);
5410 if (commit2 != NULL)
5411 got_object_commit_close(commit2);
5412 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5413 if (s->f && fflush(s->f) != 0 && err == NULL)
5414 err = got_error_from_errno("fflush");
5415 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5416 err = got_error_from_errno("fclose");
5417 return err;
5420 static void
5421 diff_view_indicate_progress(struct tog_view *view)
5423 mvwaddstr(view->window, 0, 0, "diffing...");
5424 update_panels();
5425 doupdate();
5428 static const struct got_error *
5429 search_start_diff_view(struct tog_view *view)
5431 struct tog_diff_view_state *s = &view->state.diff;
5433 s->matched_line = 0;
5434 return NULL;
5437 static void
5438 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5439 size_t *nlines, int **first, int **last, int **match, int **selected)
5441 struct tog_diff_view_state *s = &view->state.diff;
5443 *f = s->f;
5444 *nlines = s->nlines;
5445 *line_offsets = NULL;
5446 *match = &s->matched_line;
5447 *first = &s->first_displayed_line;
5448 *last = &s->last_displayed_line;
5449 *selected = &s->selected_line;
5452 static const struct got_error *
5453 search_next_view_match(struct tog_view *view)
5455 const struct got_error *err = NULL;
5456 FILE *f;
5457 int lineno;
5458 char *line = NULL;
5459 size_t linesize = 0;
5460 ssize_t linelen;
5461 off_t *line_offsets;
5462 size_t nlines = 0;
5463 int *first, *last, *match, *selected;
5465 if (!view->search_setup)
5466 return got_error_msg(GOT_ERR_NOT_IMPL,
5467 "view search not supported");
5468 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5469 &match, &selected);
5471 if (!view->searching) {
5472 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5473 return NULL;
5476 if (*match) {
5477 if (view->searching == TOG_SEARCH_FORWARD)
5478 lineno = *first + 1;
5479 else
5480 lineno = *first - 1;
5481 } else
5482 lineno = *first - 1 + *selected;
5484 while (1) {
5485 off_t offset;
5487 if (lineno <= 0 || lineno > nlines) {
5488 if (*match == 0) {
5489 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5490 break;
5493 if (view->searching == TOG_SEARCH_FORWARD)
5494 lineno = 1;
5495 else
5496 lineno = nlines;
5499 offset = view->type == TOG_VIEW_DIFF ?
5500 view->state.diff.lines[lineno - 1].offset :
5501 line_offsets[lineno - 1];
5502 if (fseeko(f, offset, SEEK_SET) != 0) {
5503 free(line);
5504 return got_error_from_errno("fseeko");
5506 linelen = getline(&line, &linesize, f);
5507 if (linelen != -1) {
5508 char *exstr;
5509 err = expand_tab(&exstr, line);
5510 if (err)
5511 break;
5512 if (match_line(exstr, &view->regex, 1,
5513 &view->regmatch)) {
5514 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5515 *match = lineno;
5516 free(exstr);
5517 break;
5519 free(exstr);
5521 if (view->searching == TOG_SEARCH_FORWARD)
5522 lineno++;
5523 else
5524 lineno--;
5526 free(line);
5528 if (*match) {
5529 *first = *match;
5530 *selected = 1;
5533 return err;
5536 static const struct got_error *
5537 close_diff_view(struct tog_view *view)
5539 const struct got_error *err = NULL;
5540 struct tog_diff_view_state *s = &view->state.diff;
5542 free(s->id1);
5543 s->id1 = NULL;
5544 free(s->id2);
5545 s->id2 = NULL;
5546 if (s->f && fclose(s->f) == EOF)
5547 err = got_error_from_errno("fclose");
5548 s->f = NULL;
5549 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5550 err = got_error_from_errno("fclose");
5551 s->f1 = NULL;
5552 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5553 err = got_error_from_errno("fclose");
5554 s->f2 = NULL;
5555 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5556 err = got_error_from_errno("close");
5557 s->fd1 = -1;
5558 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5559 err = got_error_from_errno("close");
5560 s->fd2 = -1;
5561 free(s->lines);
5562 s->lines = NULL;
5563 s->nlines = 0;
5564 return err;
5567 static const struct got_error *
5568 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5569 struct got_object_id *id2, const char *label1, const char *label2,
5570 int diff_context, int ignore_whitespace, int force_text_diff,
5571 struct tog_view *parent_view, struct got_repository *repo)
5573 const struct got_error *err;
5574 struct tog_diff_view_state *s = &view->state.diff;
5576 memset(s, 0, sizeof(*s));
5577 s->fd1 = -1;
5578 s->fd2 = -1;
5580 if (id1 != NULL && id2 != NULL) {
5581 int type1, type2;
5583 err = got_object_get_type(&type1, repo, id1);
5584 if (err)
5585 goto done;
5586 err = got_object_get_type(&type2, repo, id2);
5587 if (err)
5588 goto done;
5590 if (type1 != type2) {
5591 err = got_error(GOT_ERR_OBJ_TYPE);
5592 goto done;
5595 s->first_displayed_line = 1;
5596 s->last_displayed_line = view->nlines;
5597 s->selected_line = 1;
5598 s->repo = repo;
5599 s->label1 = label1;
5600 s->label2 = label2;
5602 if (id1) {
5603 s->id1 = got_object_id_dup(id1);
5604 if (s->id1 == NULL) {
5605 err = got_error_from_errno("got_object_id_dup");
5606 goto done;
5608 } else
5609 s->id1 = NULL;
5611 s->id2 = got_object_id_dup(id2);
5612 if (s->id2 == NULL) {
5613 err = got_error_from_errno("got_object_id_dup");
5614 goto done;
5617 s->f1 = got_opentemp();
5618 if (s->f1 == NULL) {
5619 err = got_error_from_errno("got_opentemp");
5620 goto done;
5623 s->f2 = got_opentemp();
5624 if (s->f2 == NULL) {
5625 err = got_error_from_errno("got_opentemp");
5626 goto done;
5629 s->fd1 = got_opentempfd();
5630 if (s->fd1 == -1) {
5631 err = got_error_from_errno("got_opentempfd");
5632 goto done;
5635 s->fd2 = got_opentempfd();
5636 if (s->fd2 == -1) {
5637 err = got_error_from_errno("got_opentempfd");
5638 goto done;
5641 s->diff_context = diff_context;
5642 s->ignore_whitespace = ignore_whitespace;
5643 s->force_text_diff = force_text_diff;
5644 s->parent_view = parent_view;
5645 s->repo = repo;
5647 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5648 int rc;
5650 rc = init_pair(GOT_DIFF_LINE_MINUS,
5651 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5652 if (rc != ERR)
5653 rc = init_pair(GOT_DIFF_LINE_PLUS,
5654 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5655 if (rc != ERR)
5656 rc = init_pair(GOT_DIFF_LINE_HUNK,
5657 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5658 if (rc != ERR)
5659 rc = init_pair(GOT_DIFF_LINE_META,
5660 get_color_value("TOG_COLOR_DIFF_META"), -1);
5661 if (rc != ERR)
5662 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5663 get_color_value("TOG_COLOR_DIFF_META"), -1);
5664 if (rc != ERR)
5665 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5666 get_color_value("TOG_COLOR_DIFF_META"), -1);
5667 if (rc != ERR)
5668 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5669 get_color_value("TOG_COLOR_DIFF_META"), -1);
5670 if (rc != ERR)
5671 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5672 get_color_value("TOG_COLOR_AUTHOR"), -1);
5673 if (rc != ERR)
5674 rc = init_pair(GOT_DIFF_LINE_DATE,
5675 get_color_value("TOG_COLOR_DATE"), -1);
5676 if (rc == ERR) {
5677 err = got_error(GOT_ERR_RANGE);
5678 goto done;
5682 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5683 view_is_splitscreen(view))
5684 show_log_view(parent_view); /* draw border */
5685 diff_view_indicate_progress(view);
5687 err = create_diff(s);
5689 view->show = show_diff_view;
5690 view->input = input_diff_view;
5691 view->reset = reset_diff_view;
5692 view->close = close_diff_view;
5693 view->search_start = search_start_diff_view;
5694 view->search_setup = search_setup_diff_view;
5695 view->search_next = search_next_view_match;
5696 done:
5697 if (err) {
5698 if (view->close == NULL)
5699 close_diff_view(view);
5700 view_close(view);
5702 return err;
5705 static const struct got_error *
5706 show_diff_view(struct tog_view *view)
5708 const struct got_error *err;
5709 struct tog_diff_view_state *s = &view->state.diff;
5710 char *id_str1 = NULL, *id_str2, *header;
5711 const char *label1, *label2;
5713 if (s->id1) {
5714 err = got_object_id_str(&id_str1, s->id1);
5715 if (err)
5716 return err;
5717 label1 = s->label1 ? s->label1 : id_str1;
5718 } else
5719 label1 = "/dev/null";
5721 err = got_object_id_str(&id_str2, s->id2);
5722 if (err)
5723 return err;
5724 label2 = s->label2 ? s->label2 : id_str2;
5726 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5727 err = got_error_from_errno("asprintf");
5728 free(id_str1);
5729 free(id_str2);
5730 return err;
5732 free(id_str1);
5733 free(id_str2);
5735 err = draw_file(view, header);
5736 free(header);
5737 return err;
5740 static const struct got_error *
5741 set_selected_commit(struct tog_diff_view_state *s,
5742 struct commit_queue_entry *entry)
5744 const struct got_error *err;
5745 const struct got_object_id_queue *parent_ids;
5746 struct got_commit_object *selected_commit;
5747 struct got_object_qid *pid;
5749 free(s->id2);
5750 s->id2 = got_object_id_dup(entry->id);
5751 if (s->id2 == NULL)
5752 return got_error_from_errno("got_object_id_dup");
5754 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5755 if (err)
5756 return err;
5757 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5758 free(s->id1);
5759 pid = STAILQ_FIRST(parent_ids);
5760 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5761 got_object_commit_close(selected_commit);
5762 return NULL;
5765 static const struct got_error *
5766 reset_diff_view(struct tog_view *view)
5768 struct tog_diff_view_state *s = &view->state.diff;
5770 view->count = 0;
5771 wclear(view->window);
5772 s->first_displayed_line = 1;
5773 s->last_displayed_line = view->nlines;
5774 s->matched_line = 0;
5775 diff_view_indicate_progress(view);
5776 return create_diff(s);
5779 static void
5780 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5782 int start, i;
5784 i = start = s->first_displayed_line - 1;
5786 while (s->lines[i].type != type) {
5787 if (i == 0)
5788 i = s->nlines - 1;
5789 if (--i == start)
5790 return; /* do nothing, requested type not in file */
5793 s->selected_line = 1;
5794 s->first_displayed_line = i;
5797 static void
5798 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5800 int start, i;
5802 i = start = s->first_displayed_line + 1;
5804 while (s->lines[i].type != type) {
5805 if (i == s->nlines - 1)
5806 i = 0;
5807 if (++i == start)
5808 return; /* do nothing, requested type not in file */
5811 s->selected_line = 1;
5812 s->first_displayed_line = i;
5815 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5816 int, int, int);
5817 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5818 int, int);
5820 static const struct got_error *
5821 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5823 const struct got_error *err = NULL;
5824 struct tog_diff_view_state *s = &view->state.diff;
5825 struct tog_log_view_state *ls;
5826 struct commit_queue_entry *old_selected_entry;
5827 char *line = NULL;
5828 size_t linesize = 0;
5829 ssize_t linelen;
5830 int i, nscroll = view->nlines - 1, up = 0;
5832 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5834 switch (ch) {
5835 case '0':
5836 case '$':
5837 case KEY_RIGHT:
5838 case 'l':
5839 case KEY_LEFT:
5840 case 'h':
5841 horizontal_scroll_input(view, ch);
5842 break;
5843 case 'a':
5844 case 'w':
5845 if (ch == 'a') {
5846 s->force_text_diff = !s->force_text_diff;
5847 view->action = s->force_text_diff ?
5848 "force ASCII text enabled" :
5849 "force ASCII text disabled";
5851 else if (ch == 'w') {
5852 s->ignore_whitespace = !s->ignore_whitespace;
5853 view->action = s->ignore_whitespace ?
5854 "ignore whitespace enabled" :
5855 "ignore whitespace disabled";
5857 err = reset_diff_view(view);
5858 break;
5859 case 'g':
5860 case KEY_HOME:
5861 s->first_displayed_line = 1;
5862 view->count = 0;
5863 break;
5864 case 'G':
5865 case KEY_END:
5866 view->count = 0;
5867 if (s->eof)
5868 break;
5870 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5871 s->eof = 1;
5872 break;
5873 case 'k':
5874 case KEY_UP:
5875 case CTRL('p'):
5876 if (s->first_displayed_line > 1)
5877 s->first_displayed_line--;
5878 else
5879 view->count = 0;
5880 break;
5881 case CTRL('u'):
5882 case 'u':
5883 nscroll /= 2;
5884 /* FALL THROUGH */
5885 case KEY_PPAGE:
5886 case CTRL('b'):
5887 case 'b':
5888 if (s->first_displayed_line == 1) {
5889 view->count = 0;
5890 break;
5892 i = 0;
5893 while (i++ < nscroll && s->first_displayed_line > 1)
5894 s->first_displayed_line--;
5895 break;
5896 case 'j':
5897 case KEY_DOWN:
5898 case CTRL('n'):
5899 if (!s->eof)
5900 s->first_displayed_line++;
5901 else
5902 view->count = 0;
5903 break;
5904 case CTRL('d'):
5905 case 'd':
5906 nscroll /= 2;
5907 /* FALL THROUGH */
5908 case KEY_NPAGE:
5909 case CTRL('f'):
5910 case 'f':
5911 case ' ':
5912 if (s->eof) {
5913 view->count = 0;
5914 break;
5916 i = 0;
5917 while (!s->eof && i++ < nscroll) {
5918 linelen = getline(&line, &linesize, s->f);
5919 s->first_displayed_line++;
5920 if (linelen == -1) {
5921 if (feof(s->f)) {
5922 s->eof = 1;
5923 } else
5924 err = got_ferror(s->f, GOT_ERR_IO);
5925 break;
5928 free(line);
5929 break;
5930 case '(':
5931 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5932 break;
5933 case ')':
5934 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5935 break;
5936 case '{':
5937 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5938 break;
5939 case '}':
5940 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5941 break;
5942 case '[':
5943 if (s->diff_context > 0) {
5944 s->diff_context--;
5945 s->matched_line = 0;
5946 diff_view_indicate_progress(view);
5947 err = create_diff(s);
5948 if (s->first_displayed_line + view->nlines - 1 >
5949 s->nlines) {
5950 s->first_displayed_line = 1;
5951 s->last_displayed_line = view->nlines;
5953 } else
5954 view->count = 0;
5955 break;
5956 case ']':
5957 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5958 s->diff_context++;
5959 s->matched_line = 0;
5960 diff_view_indicate_progress(view);
5961 err = create_diff(s);
5962 } else
5963 view->count = 0;
5964 break;
5965 case '<':
5966 case ',':
5967 case 'K':
5968 up = 1;
5969 /* FALL THROUGH */
5970 case '>':
5971 case '.':
5972 case 'J':
5973 if (s->parent_view == NULL) {
5974 view->count = 0;
5975 break;
5977 s->parent_view->count = view->count;
5979 if (s->parent_view->type == TOG_VIEW_LOG) {
5980 ls = &s->parent_view->state.log;
5981 old_selected_entry = ls->selected_entry;
5983 err = input_log_view(NULL, s->parent_view,
5984 up ? KEY_UP : KEY_DOWN);
5985 if (err)
5986 break;
5987 view->count = s->parent_view->count;
5989 if (old_selected_entry == ls->selected_entry)
5990 break;
5992 err = set_selected_commit(s, ls->selected_entry);
5993 if (err)
5994 break;
5995 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5996 struct tog_blame_view_state *bs;
5997 struct got_object_id *id, *prev_id;
5999 bs = &s->parent_view->state.blame;
6000 prev_id = get_annotation_for_line(bs->blame.lines,
6001 bs->blame.nlines, bs->last_diffed_line);
6003 err = input_blame_view(&view, s->parent_view,
6004 up ? KEY_UP : KEY_DOWN);
6005 if (err)
6006 break;
6007 view->count = s->parent_view->count;
6009 if (prev_id == NULL)
6010 break;
6011 id = get_selected_commit_id(bs->blame.lines,
6012 bs->blame.nlines, bs->first_displayed_line,
6013 bs->selected_line);
6014 if (id == NULL)
6015 break;
6017 if (!got_object_id_cmp(prev_id, id))
6018 break;
6020 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
6021 if (err)
6022 break;
6024 s->first_displayed_line = 1;
6025 s->last_displayed_line = view->nlines;
6026 s->matched_line = 0;
6027 view->x = 0;
6029 diff_view_indicate_progress(view);
6030 err = create_diff(s);
6031 break;
6032 default:
6033 view->count = 0;
6034 break;
6037 return err;
6040 static const struct got_error *
6041 cmd_diff(int argc, char *argv[])
6043 const struct got_error *error;
6044 struct got_repository *repo = NULL;
6045 struct got_worktree *worktree = NULL;
6046 struct got_object_id *id1 = NULL, *id2 = NULL;
6047 char *repo_path = NULL, *cwd = NULL;
6048 char *id_str1 = NULL, *id_str2 = NULL;
6049 char *keyword_idstr1 = NULL, *keyword_idstr2 = NULL;
6050 char *label1 = NULL, *label2 = NULL;
6051 int diff_context = 3, ignore_whitespace = 0;
6052 int ch, force_text_diff = 0;
6053 const char *errstr;
6054 struct tog_view *view;
6055 int *pack_fds = NULL;
6057 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
6058 switch (ch) {
6059 case 'a':
6060 force_text_diff = 1;
6061 break;
6062 case 'C':
6063 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
6064 &errstr);
6065 if (errstr != NULL)
6066 errx(1, "number of context lines is %s: %s",
6067 errstr, errstr);
6068 break;
6069 case 'r':
6070 repo_path = realpath(optarg, NULL);
6071 if (repo_path == NULL)
6072 return got_error_from_errno2("realpath",
6073 optarg);
6074 got_path_strip_trailing_slashes(repo_path);
6075 break;
6076 case 'w':
6077 ignore_whitespace = 1;
6078 break;
6079 default:
6080 usage_diff();
6081 /* NOTREACHED */
6085 argc -= optind;
6086 argv += optind;
6088 if (argc == 0) {
6089 usage_diff(); /* TODO show local worktree changes */
6090 } else if (argc == 2) {
6091 id_str1 = argv[0];
6092 id_str2 = argv[1];
6093 } else
6094 usage_diff();
6096 error = got_repo_pack_fds_open(&pack_fds);
6097 if (error)
6098 goto done;
6100 if (repo_path == NULL) {
6101 cwd = getcwd(NULL, 0);
6102 if (cwd == NULL)
6103 return got_error_from_errno("getcwd");
6104 error = got_worktree_open(&worktree, cwd, NULL);
6105 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6106 goto done;
6107 if (worktree)
6108 repo_path =
6109 strdup(got_worktree_get_repo_path(worktree));
6110 else
6111 repo_path = strdup(cwd);
6112 if (repo_path == NULL) {
6113 error = got_error_from_errno("strdup");
6114 goto done;
6118 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6119 if (error)
6120 goto done;
6122 init_curses();
6124 error = apply_unveil(got_repo_get_path(repo), NULL);
6125 if (error)
6126 goto done;
6128 error = tog_load_refs(repo, 0);
6129 if (error)
6130 goto done;
6132 if (id_str1 != NULL) {
6133 error = got_keyword_to_idstr(&keyword_idstr1, id_str1,
6134 repo, worktree);
6135 if (error != NULL)
6136 goto done;
6137 if (keyword_idstr1 != NULL)
6138 id_str1 = keyword_idstr1;
6140 if (id_str2 != NULL) {
6141 error = got_keyword_to_idstr(&keyword_idstr2, id_str2,
6142 repo, worktree);
6143 if (error != NULL)
6144 goto done;
6145 if (keyword_idstr2 != NULL)
6146 id_str2 = keyword_idstr2;
6149 error = got_repo_match_object_id(&id1, &label1, id_str1,
6150 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6151 if (error)
6152 goto done;
6154 error = got_repo_match_object_id(&id2, &label2, id_str2,
6155 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6156 if (error)
6157 goto done;
6159 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
6160 if (view == NULL) {
6161 error = got_error_from_errno("view_open");
6162 goto done;
6164 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
6165 ignore_whitespace, force_text_diff, NULL, repo);
6166 if (error)
6167 goto done;
6169 if (worktree) {
6170 error = set_tog_base_commit(repo, worktree);
6171 if (error != NULL)
6172 goto done;
6174 /* Release work tree lock. */
6175 got_worktree_close(worktree);
6176 worktree = NULL;
6179 error = view_loop(view);
6181 done:
6182 free(tog_base_commit.id);
6183 free(keyword_idstr1);
6184 free(keyword_idstr2);
6185 free(label1);
6186 free(label2);
6187 free(id1);
6188 free(id2);
6189 free(repo_path);
6190 free(cwd);
6191 if (repo) {
6192 const struct got_error *close_err = got_repo_close(repo);
6193 if (error == NULL)
6194 error = close_err;
6196 if (worktree)
6197 got_worktree_close(worktree);
6198 if (pack_fds) {
6199 const struct got_error *pack_err =
6200 got_repo_pack_fds_close(pack_fds);
6201 if (error == NULL)
6202 error = pack_err;
6204 tog_free_refs();
6205 return error;
6208 __dead static void
6209 usage_blame(void)
6211 endwin();
6212 fprintf(stderr,
6213 "usage: %s blame [-c commit] [-r repository-path] path\n",
6214 getprogname());
6215 exit(1);
6218 struct tog_blame_line {
6219 int annotated;
6220 struct got_object_id *id;
6223 static const struct got_error *
6224 draw_blame(struct tog_view *view)
6226 struct tog_blame_view_state *s = &view->state.blame;
6227 struct tog_blame *blame = &s->blame;
6228 regmatch_t *regmatch = &view->regmatch;
6229 const struct got_error *err;
6230 int lineno = 0, nprinted = 0;
6231 char *line = NULL;
6232 size_t linesize = 0;
6233 ssize_t linelen;
6234 wchar_t *wline;
6235 int width;
6236 struct tog_blame_line *blame_line;
6237 struct got_object_id *prev_id = NULL;
6238 char *id_str;
6239 struct tog_color *tc;
6241 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6242 if (err)
6243 return err;
6245 rewind(blame->f);
6246 werase(view->window);
6248 if (asprintf(&line, "commit %s", id_str) == -1) {
6249 err = got_error_from_errno("asprintf");
6250 free(id_str);
6251 return err;
6254 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6255 free(line);
6256 line = NULL;
6257 if (err)
6258 return err;
6259 if (view_needs_focus_indication(view))
6260 wstandout(view->window);
6261 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6262 if (tc)
6263 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6264 waddwstr(view->window, wline);
6265 while (width++ < view->ncols)
6266 waddch(view->window, ' ');
6267 if (tc)
6268 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6269 if (view_needs_focus_indication(view))
6270 wstandend(view->window);
6271 free(wline);
6272 wline = NULL;
6274 if (view->gline > blame->nlines)
6275 view->gline = blame->nlines;
6277 if (tog_io.wait_for_ui) {
6278 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6279 int rc;
6281 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6282 if (rc)
6283 return got_error_set_errno(rc, "pthread_cond_wait");
6284 tog_io.wait_for_ui = 0;
6287 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6288 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6289 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6290 free(id_str);
6291 return got_error_from_errno("asprintf");
6293 free(id_str);
6294 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6295 free(line);
6296 line = NULL;
6297 if (err)
6298 return err;
6299 waddwstr(view->window, wline);
6300 free(wline);
6301 wline = NULL;
6302 if (width < view->ncols - 1)
6303 waddch(view->window, '\n');
6305 s->eof = 0;
6306 view->maxx = 0;
6307 while (nprinted < view->nlines - 2) {
6308 linelen = getline(&line, &linesize, blame->f);
6309 if (linelen == -1) {
6310 if (feof(blame->f)) {
6311 s->eof = 1;
6312 break;
6314 free(line);
6315 return got_ferror(blame->f, GOT_ERR_IO);
6317 if (++lineno < s->first_displayed_line)
6318 continue;
6319 if (view->gline && !gotoline(view, &lineno, &nprinted))
6320 continue;
6322 /* Set view->maxx based on full line length. */
6323 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6324 if (err) {
6325 free(line);
6326 return err;
6328 free(wline);
6329 wline = NULL;
6330 view->maxx = MAX(view->maxx, width);
6332 if (nprinted == s->selected_line - 1)
6333 wstandout(view->window);
6335 if (blame->nlines > 0) {
6336 blame_line = &blame->lines[lineno - 1];
6337 if (blame_line->annotated && prev_id &&
6338 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6339 !(nprinted == s->selected_line - 1)) {
6340 waddstr(view->window, " ");
6341 } else if (blame_line->annotated) {
6342 char *id_str;
6343 err = got_object_id_str(&id_str,
6344 blame_line->id);
6345 if (err) {
6346 free(line);
6347 return err;
6349 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6350 if (tc)
6351 wattr_on(view->window,
6352 COLOR_PAIR(tc->colorpair), NULL);
6353 wprintw(view->window, "%.8s", id_str);
6354 if (tc)
6355 wattr_off(view->window,
6356 COLOR_PAIR(tc->colorpair), NULL);
6357 free(id_str);
6358 prev_id = blame_line->id;
6359 } else {
6360 waddstr(view->window, "........");
6361 prev_id = NULL;
6363 } else {
6364 waddstr(view->window, "........");
6365 prev_id = NULL;
6368 if (nprinted == s->selected_line - 1)
6369 wstandend(view->window);
6370 waddstr(view->window, " ");
6372 if (view->ncols <= 9) {
6373 width = 9;
6374 } else if (s->first_displayed_line + nprinted ==
6375 s->matched_line &&
6376 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6377 err = add_matched_line(&width, line, view->ncols - 9, 9,
6378 view->window, view->x, regmatch);
6379 if (err) {
6380 free(line);
6381 return err;
6383 width += 9;
6384 } else {
6385 int skip;
6386 err = format_line(&wline, &width, &skip, line,
6387 view->x, view->ncols - 9, 9, 1);
6388 if (err) {
6389 free(line);
6390 return err;
6392 waddwstr(view->window, &wline[skip]);
6393 width += 9;
6394 free(wline);
6395 wline = NULL;
6398 if (width <= view->ncols - 1)
6399 waddch(view->window, '\n');
6400 if (++nprinted == 1)
6401 s->first_displayed_line = lineno;
6403 free(line);
6404 s->last_displayed_line = lineno;
6406 view_border(view);
6408 return NULL;
6411 static const struct got_error *
6412 blame_cb(void *arg, int nlines, int lineno,
6413 struct got_commit_object *commit, struct got_object_id *id)
6415 const struct got_error *err = NULL;
6416 struct tog_blame_cb_args *a = arg;
6417 struct tog_blame_line *line;
6418 int errcode;
6420 if (nlines != a->nlines ||
6421 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6422 return got_error(GOT_ERR_RANGE);
6424 errcode = pthread_mutex_lock(&tog_mutex);
6425 if (errcode)
6426 return got_error_set_errno(errcode, "pthread_mutex_lock");
6428 if (*a->quit) { /* user has quit the blame view */
6429 err = got_error(GOT_ERR_ITER_COMPLETED);
6430 goto done;
6433 if (lineno == -1)
6434 goto done; /* no change in this commit */
6436 line = &a->lines[lineno - 1];
6437 if (line->annotated)
6438 goto done;
6440 line->id = got_object_id_dup(id);
6441 if (line->id == NULL) {
6442 err = got_error_from_errno("got_object_id_dup");
6443 goto done;
6445 line->annotated = 1;
6446 done:
6447 errcode = pthread_mutex_unlock(&tog_mutex);
6448 if (errcode)
6449 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6450 return err;
6453 static void *
6454 blame_thread(void *arg)
6456 const struct got_error *err, *close_err;
6457 struct tog_blame_thread_args *ta = arg;
6458 struct tog_blame_cb_args *a = ta->cb_args;
6459 int errcode, fd1 = -1, fd2 = -1;
6460 FILE *f1 = NULL, *f2 = NULL;
6462 fd1 = got_opentempfd();
6463 if (fd1 == -1)
6464 return (void *)got_error_from_errno("got_opentempfd");
6466 fd2 = got_opentempfd();
6467 if (fd2 == -1) {
6468 err = got_error_from_errno("got_opentempfd");
6469 goto done;
6472 f1 = got_opentemp();
6473 if (f1 == NULL) {
6474 err = (void *)got_error_from_errno("got_opentemp");
6475 goto done;
6477 f2 = got_opentemp();
6478 if (f2 == NULL) {
6479 err = (void *)got_error_from_errno("got_opentemp");
6480 goto done;
6483 err = block_signals_used_by_main_thread();
6484 if (err)
6485 goto done;
6487 err = got_blame(ta->path, a->commit_id, ta->repo,
6488 tog_diff_algo, blame_cb, ta->cb_args,
6489 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6490 if (err && err->code == GOT_ERR_CANCELLED)
6491 err = NULL;
6493 errcode = pthread_mutex_lock(&tog_mutex);
6494 if (errcode) {
6495 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6496 goto done;
6499 close_err = got_repo_close(ta->repo);
6500 if (err == NULL)
6501 err = close_err;
6502 ta->repo = NULL;
6503 *ta->complete = 1;
6505 if (tog_io.wait_for_ui) {
6506 errcode = pthread_cond_signal(&ta->blame_complete);
6507 if (errcode && err == NULL)
6508 err = got_error_set_errno(errcode,
6509 "pthread_cond_signal");
6512 errcode = pthread_mutex_unlock(&tog_mutex);
6513 if (errcode && err == NULL)
6514 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6516 done:
6517 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6518 err = got_error_from_errno("close");
6519 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6520 err = got_error_from_errno("close");
6521 if (f1 && fclose(f1) == EOF && err == NULL)
6522 err = got_error_from_errno("fclose");
6523 if (f2 && fclose(f2) == EOF && err == NULL)
6524 err = got_error_from_errno("fclose");
6526 return (void *)err;
6529 static struct got_object_id *
6530 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6531 int first_displayed_line, int selected_line)
6533 struct tog_blame_line *line;
6535 if (nlines <= 0)
6536 return NULL;
6538 line = &lines[first_displayed_line - 1 + selected_line - 1];
6539 if (!line->annotated)
6540 return NULL;
6542 return line->id;
6545 static struct got_object_id *
6546 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6547 int lineno)
6549 struct tog_blame_line *line;
6551 if (nlines <= 0 || lineno >= nlines)
6552 return NULL;
6554 line = &lines[lineno - 1];
6555 if (!line->annotated)
6556 return NULL;
6558 return line->id;
6561 static const struct got_error *
6562 stop_blame(struct tog_blame *blame)
6564 const struct got_error *err = NULL;
6565 int i;
6567 if (blame->thread) {
6568 int errcode;
6569 errcode = pthread_mutex_unlock(&tog_mutex);
6570 if (errcode)
6571 return got_error_set_errno(errcode,
6572 "pthread_mutex_unlock");
6573 errcode = pthread_join(blame->thread, (void **)&err);
6574 if (errcode)
6575 return got_error_set_errno(errcode, "pthread_join");
6576 errcode = pthread_mutex_lock(&tog_mutex);
6577 if (errcode)
6578 return got_error_set_errno(errcode,
6579 "pthread_mutex_lock");
6580 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6581 err = NULL;
6582 blame->thread = NULL;
6584 if (blame->thread_args.repo) {
6585 const struct got_error *close_err;
6586 close_err = got_repo_close(blame->thread_args.repo);
6587 if (err == NULL)
6588 err = close_err;
6589 blame->thread_args.repo = NULL;
6591 if (blame->f) {
6592 if (fclose(blame->f) == EOF && err == NULL)
6593 err = got_error_from_errno("fclose");
6594 blame->f = NULL;
6596 if (blame->lines) {
6597 for (i = 0; i < blame->nlines; i++)
6598 free(blame->lines[i].id);
6599 free(blame->lines);
6600 blame->lines = NULL;
6602 free(blame->cb_args.commit_id);
6603 blame->cb_args.commit_id = NULL;
6604 if (blame->pack_fds) {
6605 const struct got_error *pack_err =
6606 got_repo_pack_fds_close(blame->pack_fds);
6607 if (err == NULL)
6608 err = pack_err;
6609 blame->pack_fds = NULL;
6611 free(blame->line_offsets);
6612 blame->line_offsets = NULL;
6613 return err;
6616 static const struct got_error *
6617 cancel_blame_view(void *arg)
6619 const struct got_error *err = NULL;
6620 int *done = arg;
6621 int errcode;
6623 errcode = pthread_mutex_lock(&tog_mutex);
6624 if (errcode)
6625 return got_error_set_errno(errcode,
6626 "pthread_mutex_unlock");
6628 if (*done)
6629 err = got_error(GOT_ERR_CANCELLED);
6631 errcode = pthread_mutex_unlock(&tog_mutex);
6632 if (errcode)
6633 return got_error_set_errno(errcode,
6634 "pthread_mutex_lock");
6636 return err;
6639 static const struct got_error *
6640 run_blame(struct tog_view *view)
6642 struct tog_blame_view_state *s = &view->state.blame;
6643 struct tog_blame *blame = &s->blame;
6644 const struct got_error *err = NULL;
6645 struct got_commit_object *commit = NULL;
6646 struct got_blob_object *blob = NULL;
6647 struct got_repository *thread_repo = NULL;
6648 struct got_object_id *obj_id = NULL;
6649 int obj_type, fd = -1;
6650 int *pack_fds = NULL;
6652 err = got_object_open_as_commit(&commit, s->repo,
6653 &s->blamed_commit->id);
6654 if (err)
6655 return err;
6657 fd = got_opentempfd();
6658 if (fd == -1) {
6659 err = got_error_from_errno("got_opentempfd");
6660 goto done;
6663 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6664 if (err)
6665 goto done;
6667 err = got_object_get_type(&obj_type, s->repo, obj_id);
6668 if (err)
6669 goto done;
6671 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6672 err = got_error(GOT_ERR_OBJ_TYPE);
6673 goto done;
6676 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6677 if (err)
6678 goto done;
6679 blame->f = got_opentemp();
6680 if (blame->f == NULL) {
6681 err = got_error_from_errno("got_opentemp");
6682 goto done;
6684 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6685 &blame->line_offsets, blame->f, blob);
6686 if (err)
6687 goto done;
6688 if (blame->nlines == 0) {
6689 s->blame_complete = 1;
6690 goto done;
6693 /* Don't include \n at EOF in the blame line count. */
6694 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6695 blame->nlines--;
6697 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6698 if (blame->lines == NULL) {
6699 err = got_error_from_errno("calloc");
6700 goto done;
6703 err = got_repo_pack_fds_open(&pack_fds);
6704 if (err)
6705 goto done;
6706 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6707 pack_fds);
6708 if (err)
6709 goto done;
6711 blame->pack_fds = pack_fds;
6712 blame->cb_args.view = view;
6713 blame->cb_args.lines = blame->lines;
6714 blame->cb_args.nlines = blame->nlines;
6715 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6716 if (blame->cb_args.commit_id == NULL) {
6717 err = got_error_from_errno("got_object_id_dup");
6718 goto done;
6720 blame->cb_args.quit = &s->done;
6722 blame->thread_args.path = s->path;
6723 blame->thread_args.repo = thread_repo;
6724 blame->thread_args.cb_args = &blame->cb_args;
6725 blame->thread_args.complete = &s->blame_complete;
6726 blame->thread_args.cancel_cb = cancel_blame_view;
6727 blame->thread_args.cancel_arg = &s->done;
6728 s->blame_complete = 0;
6730 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6731 s->first_displayed_line = 1;
6732 s->last_displayed_line = view->nlines;
6733 s->selected_line = 1;
6735 s->matched_line = 0;
6737 done:
6738 if (commit)
6739 got_object_commit_close(commit);
6740 if (fd != -1 && close(fd) == -1 && err == NULL)
6741 err = got_error_from_errno("close");
6742 if (blob)
6743 got_object_blob_close(blob);
6744 free(obj_id);
6745 if (err)
6746 stop_blame(blame);
6747 return err;
6750 static const struct got_error *
6751 open_blame_view(struct tog_view *view, char *path,
6752 struct got_object_id *commit_id, struct got_repository *repo)
6754 const struct got_error *err = NULL;
6755 struct tog_blame_view_state *s = &view->state.blame;
6757 STAILQ_INIT(&s->blamed_commits);
6759 s->path = strdup(path);
6760 if (s->path == NULL)
6761 return got_error_from_errno("strdup");
6763 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6764 if (err) {
6765 free(s->path);
6766 return err;
6769 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6770 s->first_displayed_line = 1;
6771 s->last_displayed_line = view->nlines;
6772 s->selected_line = 1;
6773 s->blame_complete = 0;
6774 s->repo = repo;
6775 s->commit_id = commit_id;
6776 memset(&s->blame, 0, sizeof(s->blame));
6778 STAILQ_INIT(&s->colors);
6779 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6780 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6781 get_color_value("TOG_COLOR_COMMIT"));
6782 if (err)
6783 return err;
6786 view->show = show_blame_view;
6787 view->input = input_blame_view;
6788 view->reset = reset_blame_view;
6789 view->close = close_blame_view;
6790 view->search_start = search_start_blame_view;
6791 view->search_setup = search_setup_blame_view;
6792 view->search_next = search_next_view_match;
6794 if (using_mock_io) {
6795 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6796 int rc;
6798 rc = pthread_cond_init(&bta->blame_complete, NULL);
6799 if (rc)
6800 return got_error_set_errno(rc, "pthread_cond_init");
6803 return run_blame(view);
6806 static const struct got_error *
6807 close_blame_view(struct tog_view *view)
6809 const struct got_error *err = NULL;
6810 struct tog_blame_view_state *s = &view->state.blame;
6812 if (s->blame.thread)
6813 err = stop_blame(&s->blame);
6815 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6816 struct got_object_qid *blamed_commit;
6817 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6818 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6819 got_object_qid_free(blamed_commit);
6822 if (using_mock_io) {
6823 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6824 int rc;
6826 rc = pthread_cond_destroy(&bta->blame_complete);
6827 if (rc && err == NULL)
6828 err = got_error_set_errno(rc, "pthread_cond_destroy");
6831 free(s->path);
6832 free_colors(&s->colors);
6833 return err;
6836 static const struct got_error *
6837 search_start_blame_view(struct tog_view *view)
6839 struct tog_blame_view_state *s = &view->state.blame;
6841 s->matched_line = 0;
6842 return NULL;
6845 static void
6846 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6847 size_t *nlines, int **first, int **last, int **match, int **selected)
6849 struct tog_blame_view_state *s = &view->state.blame;
6851 *f = s->blame.f;
6852 *nlines = s->blame.nlines;
6853 *line_offsets = s->blame.line_offsets;
6854 *match = &s->matched_line;
6855 *first = &s->first_displayed_line;
6856 *last = &s->last_displayed_line;
6857 *selected = &s->selected_line;
6860 static const struct got_error *
6861 show_blame_view(struct tog_view *view)
6863 const struct got_error *err = NULL;
6864 struct tog_blame_view_state *s = &view->state.blame;
6865 int errcode;
6867 if (s->blame.thread == NULL && !s->blame_complete) {
6868 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6869 &s->blame.thread_args);
6870 if (errcode)
6871 return got_error_set_errno(errcode, "pthread_create");
6873 if (!using_mock_io)
6874 halfdelay(1); /* fast refresh while annotating */
6877 if (s->blame_complete && !using_mock_io)
6878 halfdelay(10); /* disable fast refresh */
6880 err = draw_blame(view);
6882 view_border(view);
6883 return err;
6886 static const struct got_error *
6887 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6888 struct got_repository *repo, struct got_object_id *id)
6890 struct tog_view *log_view;
6891 const struct got_error *err = NULL;
6893 *new_view = NULL;
6895 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6896 if (log_view == NULL)
6897 return got_error_from_errno("view_open");
6899 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0, NULL);
6900 if (err)
6901 view_close(log_view);
6902 else
6903 *new_view = log_view;
6905 return err;
6908 static const struct got_error *
6909 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6911 const struct got_error *err = NULL, *thread_err = NULL;
6912 struct tog_view *diff_view;
6913 struct tog_blame_view_state *s = &view->state.blame;
6914 int eos, nscroll, begin_y = 0, begin_x = 0;
6916 eos = nscroll = view->nlines - 2;
6917 if (view_is_hsplit_top(view))
6918 --eos; /* border */
6920 switch (ch) {
6921 case '0':
6922 case '$':
6923 case KEY_RIGHT:
6924 case 'l':
6925 case KEY_LEFT:
6926 case 'h':
6927 horizontal_scroll_input(view, ch);
6928 break;
6929 case 'q':
6930 s->done = 1;
6931 break;
6932 case 'g':
6933 case KEY_HOME:
6934 s->selected_line = 1;
6935 s->first_displayed_line = 1;
6936 view->count = 0;
6937 break;
6938 case 'G':
6939 case KEY_END:
6940 if (s->blame.nlines < eos) {
6941 s->selected_line = s->blame.nlines;
6942 s->first_displayed_line = 1;
6943 } else {
6944 s->selected_line = eos;
6945 s->first_displayed_line = s->blame.nlines - (eos - 1);
6947 view->count = 0;
6948 break;
6949 case 'k':
6950 case KEY_UP:
6951 case CTRL('p'):
6952 if (s->selected_line > 1)
6953 s->selected_line--;
6954 else if (s->selected_line == 1 &&
6955 s->first_displayed_line > 1)
6956 s->first_displayed_line--;
6957 else
6958 view->count = 0;
6959 break;
6960 case CTRL('u'):
6961 case 'u':
6962 nscroll /= 2;
6963 /* FALL THROUGH */
6964 case KEY_PPAGE:
6965 case CTRL('b'):
6966 case 'b':
6967 if (s->first_displayed_line == 1) {
6968 if (view->count > 1)
6969 nscroll += nscroll;
6970 s->selected_line = MAX(1, s->selected_line - nscroll);
6971 view->count = 0;
6972 break;
6974 if (s->first_displayed_line > nscroll)
6975 s->first_displayed_line -= nscroll;
6976 else
6977 s->first_displayed_line = 1;
6978 break;
6979 case 'j':
6980 case KEY_DOWN:
6981 case CTRL('n'):
6982 if (s->selected_line < eos && s->first_displayed_line +
6983 s->selected_line <= s->blame.nlines)
6984 s->selected_line++;
6985 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6986 s->first_displayed_line++;
6987 else
6988 view->count = 0;
6989 break;
6990 case 'c':
6991 case 'p': {
6992 struct got_object_id *id = NULL;
6994 view->count = 0;
6995 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6996 s->first_displayed_line, s->selected_line);
6997 if (id == NULL)
6998 break;
6999 if (ch == 'p') {
7000 struct got_commit_object *commit, *pcommit;
7001 struct got_object_qid *pid;
7002 struct got_object_id *blob_id = NULL;
7003 int obj_type;
7004 err = got_object_open_as_commit(&commit,
7005 s->repo, id);
7006 if (err)
7007 break;
7008 pid = STAILQ_FIRST(
7009 got_object_commit_get_parent_ids(commit));
7010 if (pid == NULL) {
7011 got_object_commit_close(commit);
7012 break;
7014 /* Check if path history ends here. */
7015 err = got_object_open_as_commit(&pcommit,
7016 s->repo, &pid->id);
7017 if (err)
7018 break;
7019 err = got_object_id_by_path(&blob_id, s->repo,
7020 pcommit, s->path);
7021 got_object_commit_close(pcommit);
7022 if (err) {
7023 if (err->code == GOT_ERR_NO_TREE_ENTRY)
7024 err = NULL;
7025 got_object_commit_close(commit);
7026 break;
7028 err = got_object_get_type(&obj_type, s->repo,
7029 blob_id);
7030 free(blob_id);
7031 /* Can't blame non-blob type objects. */
7032 if (obj_type != GOT_OBJ_TYPE_BLOB) {
7033 got_object_commit_close(commit);
7034 break;
7036 err = got_object_qid_alloc(&s->blamed_commit,
7037 &pid->id);
7038 got_object_commit_close(commit);
7039 } else {
7040 if (got_object_id_cmp(id,
7041 &s->blamed_commit->id) == 0)
7042 break;
7043 err = got_object_qid_alloc(&s->blamed_commit,
7044 id);
7046 if (err)
7047 break;
7048 s->done = 1;
7049 thread_err = stop_blame(&s->blame);
7050 s->done = 0;
7051 if (thread_err)
7052 break;
7053 STAILQ_INSERT_HEAD(&s->blamed_commits,
7054 s->blamed_commit, entry);
7055 err = run_blame(view);
7056 if (err)
7057 break;
7058 break;
7060 case 'C': {
7061 struct got_object_qid *first;
7063 view->count = 0;
7064 first = STAILQ_FIRST(&s->blamed_commits);
7065 if (!got_object_id_cmp(&first->id, s->commit_id))
7066 break;
7067 s->done = 1;
7068 thread_err = stop_blame(&s->blame);
7069 s->done = 0;
7070 if (thread_err)
7071 break;
7072 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
7073 got_object_qid_free(s->blamed_commit);
7074 s->blamed_commit =
7075 STAILQ_FIRST(&s->blamed_commits);
7076 err = run_blame(view);
7077 if (err)
7078 break;
7079 break;
7081 case 'L':
7082 view->count = 0;
7083 s->id_to_log = get_selected_commit_id(s->blame.lines,
7084 s->blame.nlines, s->first_displayed_line, s->selected_line);
7085 if (s->id_to_log)
7086 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7087 break;
7088 case KEY_ENTER:
7089 case '\r': {
7090 struct got_object_id *id = NULL;
7091 struct got_object_qid *pid;
7092 struct got_commit_object *commit = NULL;
7094 view->count = 0;
7095 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
7096 s->first_displayed_line, s->selected_line);
7097 if (id == NULL)
7098 break;
7099 err = got_object_open_as_commit(&commit, s->repo, id);
7100 if (err)
7101 break;
7102 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7103 if (*new_view) {
7104 /* traversed from diff view, release diff resources */
7105 err = close_diff_view(*new_view);
7106 if (err)
7107 break;
7108 diff_view = *new_view;
7109 } else {
7110 if (view_is_parent_view(view))
7111 view_get_split(view, &begin_y, &begin_x);
7113 diff_view = view_open(0, 0, begin_y, begin_x,
7114 TOG_VIEW_DIFF);
7115 if (diff_view == NULL) {
7116 got_object_commit_close(commit);
7117 err = got_error_from_errno("view_open");
7118 break;
7121 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
7122 id, NULL, NULL, 3, 0, 0, view, s->repo);
7123 got_object_commit_close(commit);
7124 if (err)
7125 break;
7126 s->last_diffed_line = s->first_displayed_line - 1 +
7127 s->selected_line;
7128 if (*new_view)
7129 break; /* still open from active diff view */
7130 if (view_is_parent_view(view) &&
7131 view->mode == TOG_VIEW_SPLIT_HRZN) {
7132 err = view_init_hsplit(view, begin_y);
7133 if (err)
7134 break;
7137 view->focussed = 0;
7138 diff_view->focussed = 1;
7139 diff_view->mode = view->mode;
7140 diff_view->nlines = view->lines - begin_y;
7141 if (view_is_parent_view(view)) {
7142 view_transfer_size(diff_view, view);
7143 err = view_close_child(view);
7144 if (err)
7145 break;
7146 err = view_set_child(view, diff_view);
7147 if (err)
7148 break;
7149 view->focus_child = 1;
7150 } else
7151 *new_view = diff_view;
7152 if (err)
7153 break;
7154 break;
7156 case CTRL('d'):
7157 case 'd':
7158 nscroll /= 2;
7159 /* FALL THROUGH */
7160 case KEY_NPAGE:
7161 case CTRL('f'):
7162 case 'f':
7163 case ' ':
7164 if (s->last_displayed_line >= s->blame.nlines &&
7165 s->selected_line >= MIN(s->blame.nlines,
7166 view->nlines - 2)) {
7167 view->count = 0;
7168 break;
7170 if (s->last_displayed_line >= s->blame.nlines &&
7171 s->selected_line < view->nlines - 2) {
7172 s->selected_line +=
7173 MIN(nscroll, s->last_displayed_line -
7174 s->first_displayed_line - s->selected_line + 1);
7176 if (s->last_displayed_line + nscroll <= s->blame.nlines)
7177 s->first_displayed_line += nscroll;
7178 else
7179 s->first_displayed_line =
7180 s->blame.nlines - (view->nlines - 3);
7181 break;
7182 case KEY_RESIZE:
7183 if (s->selected_line > view->nlines - 2) {
7184 s->selected_line = MIN(s->blame.nlines,
7185 view->nlines - 2);
7187 break;
7188 default:
7189 view->count = 0;
7190 break;
7192 return thread_err ? thread_err : err;
7195 static const struct got_error *
7196 reset_blame_view(struct tog_view *view)
7198 const struct got_error *err;
7199 struct tog_blame_view_state *s = &view->state.blame;
7201 view->count = 0;
7202 s->done = 1;
7203 err = stop_blame(&s->blame);
7204 s->done = 0;
7205 if (err)
7206 return err;
7207 return run_blame(view);
7210 static const struct got_error *
7211 cmd_blame(int argc, char *argv[])
7213 const struct got_error *error;
7214 struct got_repository *repo = NULL;
7215 struct got_worktree *worktree = NULL;
7216 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7217 char *link_target = NULL;
7218 struct got_object_id *commit_id = NULL;
7219 struct got_commit_object *commit = NULL;
7220 char *keyword_idstr = NULL, *commit_id_str = NULL;
7221 int ch;
7222 struct tog_view *view = NULL;
7223 int *pack_fds = NULL;
7225 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7226 switch (ch) {
7227 case 'c':
7228 commit_id_str = optarg;
7229 break;
7230 case 'r':
7231 repo_path = realpath(optarg, NULL);
7232 if (repo_path == NULL)
7233 return got_error_from_errno2("realpath",
7234 optarg);
7235 break;
7236 default:
7237 usage_blame();
7238 /* NOTREACHED */
7242 argc -= optind;
7243 argv += optind;
7245 if (argc != 1)
7246 usage_blame();
7248 error = got_repo_pack_fds_open(&pack_fds);
7249 if (error != NULL)
7250 goto done;
7252 if (repo_path == NULL) {
7253 cwd = getcwd(NULL, 0);
7254 if (cwd == NULL)
7255 return got_error_from_errno("getcwd");
7256 error = got_worktree_open(&worktree, cwd, NULL);
7257 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7258 goto done;
7259 if (worktree)
7260 repo_path =
7261 strdup(got_worktree_get_repo_path(worktree));
7262 else
7263 repo_path = strdup(cwd);
7264 if (repo_path == NULL) {
7265 error = got_error_from_errno("strdup");
7266 goto done;
7270 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7271 if (error != NULL)
7272 goto done;
7274 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7275 worktree);
7276 if (error)
7277 goto done;
7279 init_curses();
7281 error = apply_unveil(got_repo_get_path(repo), NULL);
7282 if (error)
7283 goto done;
7285 error = tog_load_refs(repo, 0);
7286 if (error)
7287 goto done;
7289 if (commit_id_str == NULL) {
7290 struct got_reference *head_ref;
7291 error = got_ref_open(&head_ref, repo, worktree ?
7292 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7293 if (error != NULL)
7294 goto done;
7295 error = got_ref_resolve(&commit_id, repo, head_ref);
7296 got_ref_close(head_ref);
7297 } else {
7298 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
7299 repo, worktree);
7300 if (error != NULL)
7301 goto done;
7302 if (keyword_idstr != NULL)
7303 commit_id_str = keyword_idstr;
7305 error = got_repo_match_object_id(&commit_id, NULL,
7306 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7308 if (error != NULL)
7309 goto done;
7311 error = got_object_open_as_commit(&commit, repo, commit_id);
7312 if (error)
7313 goto done;
7315 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7316 commit, repo);
7317 if (error)
7318 goto done;
7320 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7321 if (view == NULL) {
7322 error = got_error_from_errno("view_open");
7323 goto done;
7325 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7326 commit_id, repo);
7327 if (error != NULL) {
7328 if (view->close == NULL)
7329 close_blame_view(view);
7330 view_close(view);
7331 goto done;
7334 if (worktree) {
7335 error = set_tog_base_commit(repo, worktree);
7336 if (error != NULL)
7337 goto done;
7339 /* Release work tree lock. */
7340 got_worktree_close(worktree);
7341 worktree = NULL;
7344 error = view_loop(view);
7346 done:
7347 free(tog_base_commit.id);
7348 free(repo_path);
7349 free(in_repo_path);
7350 free(link_target);
7351 free(cwd);
7352 free(commit_id);
7353 free(keyword_idstr);
7354 if (commit)
7355 got_object_commit_close(commit);
7356 if (worktree)
7357 got_worktree_close(worktree);
7358 if (repo) {
7359 const struct got_error *close_err = got_repo_close(repo);
7360 if (error == NULL)
7361 error = close_err;
7363 if (pack_fds) {
7364 const struct got_error *pack_err =
7365 got_repo_pack_fds_close(pack_fds);
7366 if (error == NULL)
7367 error = pack_err;
7369 tog_free_refs();
7370 return error;
7373 static const struct got_error *
7374 draw_tree_entries(struct tog_view *view, const char *parent_path)
7376 struct tog_tree_view_state *s = &view->state.tree;
7377 const struct got_error *err = NULL;
7378 struct got_tree_entry *te;
7379 wchar_t *wline;
7380 char *index = NULL;
7381 struct tog_color *tc;
7382 int width, n, nentries, scrollx, i = 1;
7383 int limit = view->nlines;
7385 s->ndisplayed = 0;
7386 if (view_is_hsplit_top(view))
7387 --limit; /* border */
7389 werase(view->window);
7391 if (limit == 0)
7392 return NULL;
7394 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7395 0, 0);
7396 if (err)
7397 return err;
7398 if (view_needs_focus_indication(view))
7399 wstandout(view->window);
7400 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7401 if (tc)
7402 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7403 waddwstr(view->window, wline);
7404 free(wline);
7405 wline = NULL;
7406 while (width++ < view->ncols)
7407 waddch(view->window, ' ');
7408 if (tc)
7409 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7410 if (view_needs_focus_indication(view))
7411 wstandend(view->window);
7412 if (--limit <= 0)
7413 return NULL;
7415 i += s->selected;
7416 if (s->first_displayed_entry) {
7417 i += got_tree_entry_get_index(s->first_displayed_entry);
7418 if (s->tree != s->root)
7419 ++i; /* account for ".." entry */
7421 nentries = got_object_tree_get_nentries(s->tree);
7422 if (asprintf(&index, "[%d/%d] %s",
7423 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7424 return got_error_from_errno("asprintf");
7425 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7426 free(index);
7427 if (err)
7428 return err;
7429 waddwstr(view->window, wline);
7430 free(wline);
7431 wline = NULL;
7432 if (width < view->ncols - 1)
7433 waddch(view->window, '\n');
7434 if (--limit <= 0)
7435 return NULL;
7436 waddch(view->window, '\n');
7437 if (--limit <= 0)
7438 return NULL;
7440 if (s->first_displayed_entry == NULL) {
7441 te = got_object_tree_get_first_entry(s->tree);
7442 if (s->selected == 0) {
7443 if (view->focussed)
7444 wstandout(view->window);
7445 s->selected_entry = NULL;
7447 waddstr(view->window, " ..\n"); /* parent directory */
7448 if (s->selected == 0 && view->focussed)
7449 wstandend(view->window);
7450 s->ndisplayed++;
7451 if (--limit <= 0)
7452 return NULL;
7453 n = 1;
7454 } else {
7455 n = 0;
7456 te = s->first_displayed_entry;
7459 view->maxx = 0;
7460 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7461 char *line = NULL, *id_str = NULL, *link_target = NULL;
7462 const char *modestr = "";
7463 mode_t mode;
7465 te = got_object_tree_get_entry(s->tree, i);
7466 mode = got_tree_entry_get_mode(te);
7468 if (s->show_ids) {
7469 err = got_object_id_str(&id_str,
7470 got_tree_entry_get_id(te));
7471 if (err)
7472 return got_error_from_errno(
7473 "got_object_id_str");
7475 if (got_object_tree_entry_is_submodule(te))
7476 modestr = "$";
7477 else if (S_ISLNK(mode)) {
7478 int i;
7480 err = got_tree_entry_get_symlink_target(&link_target,
7481 te, s->repo);
7482 if (err) {
7483 free(id_str);
7484 return err;
7486 for (i = 0; link_target[i] != '\0'; i++) {
7487 if (!isprint((unsigned char)link_target[i]))
7488 link_target[i] = '?';
7490 modestr = "@";
7492 else if (S_ISDIR(mode))
7493 modestr = "/";
7494 else if (mode & S_IXUSR)
7495 modestr = "*";
7496 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7497 got_tree_entry_get_name(te), modestr,
7498 link_target ? " -> ": "",
7499 link_target ? link_target : "") == -1) {
7500 free(id_str);
7501 free(link_target);
7502 return got_error_from_errno("asprintf");
7504 free(id_str);
7505 free(link_target);
7507 /* use full line width to determine view->maxx */
7508 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7509 if (err) {
7510 free(line);
7511 break;
7513 view->maxx = MAX(view->maxx, width);
7514 free(wline);
7515 wline = NULL;
7517 err = format_line(&wline, &width, &scrollx, line, view->x,
7518 view->ncols, 0, 0);
7519 if (err) {
7520 free(line);
7521 break;
7523 if (n == s->selected) {
7524 if (view->focussed)
7525 wstandout(view->window);
7526 s->selected_entry = te;
7528 tc = match_color(&s->colors, line);
7529 if (tc)
7530 wattr_on(view->window,
7531 COLOR_PAIR(tc->colorpair), NULL);
7532 waddwstr(view->window, &wline[scrollx]);
7533 if (tc)
7534 wattr_off(view->window,
7535 COLOR_PAIR(tc->colorpair), NULL);
7536 if (width < view->ncols)
7537 waddch(view->window, '\n');
7538 if (n == s->selected && view->focussed)
7539 wstandend(view->window);
7540 free(line);
7541 free(wline);
7542 wline = NULL;
7543 n++;
7544 s->ndisplayed++;
7545 s->last_displayed_entry = te;
7546 if (--limit <= 0)
7547 break;
7550 return err;
7553 static void
7554 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7556 struct got_tree_entry *te;
7557 int isroot = s->tree == s->root;
7558 int i = 0;
7560 if (s->first_displayed_entry == NULL)
7561 return;
7563 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7564 while (i++ < maxscroll) {
7565 if (te == NULL) {
7566 if (!isroot)
7567 s->first_displayed_entry = NULL;
7568 break;
7570 s->first_displayed_entry = te;
7571 te = got_tree_entry_get_prev(s->tree, te);
7575 static const struct got_error *
7576 tree_scroll_down(struct tog_view *view, int maxscroll)
7578 struct tog_tree_view_state *s = &view->state.tree;
7579 struct got_tree_entry *next, *last;
7580 int n = 0;
7582 if (s->first_displayed_entry)
7583 next = got_tree_entry_get_next(s->tree,
7584 s->first_displayed_entry);
7585 else
7586 next = got_object_tree_get_first_entry(s->tree);
7588 last = s->last_displayed_entry;
7589 while (next && n++ < maxscroll) {
7590 if (last) {
7591 s->last_displayed_entry = last;
7592 last = got_tree_entry_get_next(s->tree, last);
7594 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7595 s->first_displayed_entry = next;
7596 next = got_tree_entry_get_next(s->tree, next);
7600 return NULL;
7603 static const struct got_error *
7604 tree_entry_path(char **path, struct tog_parent_trees *parents,
7605 struct got_tree_entry *te)
7607 const struct got_error *err = NULL;
7608 struct tog_parent_tree *pt;
7609 size_t len = 2; /* for leading slash and NUL */
7611 TAILQ_FOREACH(pt, parents, entry)
7612 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7613 + 1 /* slash */;
7614 if (te)
7615 len += strlen(got_tree_entry_get_name(te));
7617 *path = calloc(1, len);
7618 if (path == NULL)
7619 return got_error_from_errno("calloc");
7621 (*path)[0] = '/';
7622 pt = TAILQ_LAST(parents, tog_parent_trees);
7623 while (pt) {
7624 const char *name = got_tree_entry_get_name(pt->selected_entry);
7625 if (strlcat(*path, name, len) >= len) {
7626 err = got_error(GOT_ERR_NO_SPACE);
7627 goto done;
7629 if (strlcat(*path, "/", len) >= len) {
7630 err = got_error(GOT_ERR_NO_SPACE);
7631 goto done;
7633 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7635 if (te) {
7636 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7637 err = got_error(GOT_ERR_NO_SPACE);
7638 goto done;
7641 done:
7642 if (err) {
7643 free(*path);
7644 *path = NULL;
7646 return err;
7649 static const struct got_error *
7650 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7651 struct got_tree_entry *te, struct tog_parent_trees *parents,
7652 struct got_object_id *commit_id, struct got_repository *repo)
7654 const struct got_error *err = NULL;
7655 char *path;
7656 struct tog_view *blame_view;
7658 *new_view = NULL;
7660 err = tree_entry_path(&path, parents, te);
7661 if (err)
7662 return err;
7664 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7665 if (blame_view == NULL) {
7666 err = got_error_from_errno("view_open");
7667 goto done;
7670 err = open_blame_view(blame_view, path, commit_id, repo);
7671 if (err) {
7672 if (err->code == GOT_ERR_CANCELLED)
7673 err = NULL;
7674 view_close(blame_view);
7675 } else
7676 *new_view = blame_view;
7677 done:
7678 free(path);
7679 return err;
7682 static const struct got_error *
7683 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7684 struct tog_tree_view_state *s)
7686 struct tog_view *log_view;
7687 const struct got_error *err = NULL;
7688 char *path;
7690 *new_view = NULL;
7692 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7693 if (log_view == NULL)
7694 return got_error_from_errno("view_open");
7696 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7697 if (err)
7698 return err;
7700 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7701 path, 0, NULL);
7702 if (err)
7703 view_close(log_view);
7704 else
7705 *new_view = log_view;
7706 free(path);
7707 return err;
7710 static const struct got_error *
7711 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7712 const char *head_ref_name, struct got_repository *repo)
7714 const struct got_error *err = NULL;
7715 char *commit_id_str = NULL;
7716 struct tog_tree_view_state *s = &view->state.tree;
7717 struct got_commit_object *commit = NULL;
7719 TAILQ_INIT(&s->parents);
7720 STAILQ_INIT(&s->colors);
7722 s->commit_id = got_object_id_dup(commit_id);
7723 if (s->commit_id == NULL) {
7724 err = got_error_from_errno("got_object_id_dup");
7725 goto done;
7728 err = got_object_open_as_commit(&commit, repo, commit_id);
7729 if (err)
7730 goto done;
7733 * The root is opened here and will be closed when the view is closed.
7734 * Any visited subtrees and their path-wise parents are opened and
7735 * closed on demand.
7737 err = got_object_open_as_tree(&s->root, repo,
7738 got_object_commit_get_tree_id(commit));
7739 if (err)
7740 goto done;
7741 s->tree = s->root;
7743 err = got_object_id_str(&commit_id_str, commit_id);
7744 if (err != NULL)
7745 goto done;
7747 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7748 err = got_error_from_errno("asprintf");
7749 goto done;
7752 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7753 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7754 if (head_ref_name) {
7755 s->head_ref_name = strdup(head_ref_name);
7756 if (s->head_ref_name == NULL) {
7757 err = got_error_from_errno("strdup");
7758 goto done;
7761 s->repo = repo;
7763 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7764 err = add_color(&s->colors, "\\$$",
7765 TOG_COLOR_TREE_SUBMODULE,
7766 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7767 if (err)
7768 goto done;
7769 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7770 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7771 if (err)
7772 goto done;
7773 err = add_color(&s->colors, "/$",
7774 TOG_COLOR_TREE_DIRECTORY,
7775 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7776 if (err)
7777 goto done;
7779 err = add_color(&s->colors, "\\*$",
7780 TOG_COLOR_TREE_EXECUTABLE,
7781 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7782 if (err)
7783 goto done;
7785 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7786 get_color_value("TOG_COLOR_COMMIT"));
7787 if (err)
7788 goto done;
7791 view->show = show_tree_view;
7792 view->input = input_tree_view;
7793 view->close = close_tree_view;
7794 view->search_start = search_start_tree_view;
7795 view->search_next = search_next_tree_view;
7796 done:
7797 free(commit_id_str);
7798 if (commit)
7799 got_object_commit_close(commit);
7800 if (err) {
7801 if (view->close == NULL)
7802 close_tree_view(view);
7803 view_close(view);
7805 return err;
7808 static const struct got_error *
7809 close_tree_view(struct tog_view *view)
7811 struct tog_tree_view_state *s = &view->state.tree;
7813 free_colors(&s->colors);
7814 free(s->tree_label);
7815 s->tree_label = NULL;
7816 free(s->commit_id);
7817 s->commit_id = NULL;
7818 free(s->head_ref_name);
7819 s->head_ref_name = NULL;
7820 while (!TAILQ_EMPTY(&s->parents)) {
7821 struct tog_parent_tree *parent;
7822 parent = TAILQ_FIRST(&s->parents);
7823 TAILQ_REMOVE(&s->parents, parent, entry);
7824 if (parent->tree != s->root)
7825 got_object_tree_close(parent->tree);
7826 free(parent);
7829 if (s->tree != NULL && s->tree != s->root)
7830 got_object_tree_close(s->tree);
7831 if (s->root)
7832 got_object_tree_close(s->root);
7833 return NULL;
7836 static const struct got_error *
7837 search_start_tree_view(struct tog_view *view)
7839 struct tog_tree_view_state *s = &view->state.tree;
7841 s->matched_entry = NULL;
7842 return NULL;
7845 static int
7846 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7848 regmatch_t regmatch;
7850 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7851 0) == 0;
7854 static const struct got_error *
7855 search_next_tree_view(struct tog_view *view)
7857 struct tog_tree_view_state *s = &view->state.tree;
7858 struct got_tree_entry *te = NULL;
7860 if (!view->searching) {
7861 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7862 return NULL;
7865 if (s->matched_entry) {
7866 if (view->searching == TOG_SEARCH_FORWARD) {
7867 if (s->selected_entry)
7868 te = got_tree_entry_get_next(s->tree,
7869 s->selected_entry);
7870 else
7871 te = got_object_tree_get_first_entry(s->tree);
7872 } else {
7873 if (s->selected_entry == NULL)
7874 te = got_object_tree_get_last_entry(s->tree);
7875 else
7876 te = got_tree_entry_get_prev(s->tree,
7877 s->selected_entry);
7879 } else {
7880 if (s->selected_entry)
7881 te = s->selected_entry;
7882 else if (view->searching == TOG_SEARCH_FORWARD)
7883 te = got_object_tree_get_first_entry(s->tree);
7884 else
7885 te = got_object_tree_get_last_entry(s->tree);
7888 while (1) {
7889 if (te == NULL) {
7890 if (s->matched_entry == NULL) {
7891 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7892 return NULL;
7894 if (view->searching == TOG_SEARCH_FORWARD)
7895 te = got_object_tree_get_first_entry(s->tree);
7896 else
7897 te = got_object_tree_get_last_entry(s->tree);
7900 if (match_tree_entry(te, &view->regex)) {
7901 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7902 s->matched_entry = te;
7903 break;
7906 if (view->searching == TOG_SEARCH_FORWARD)
7907 te = got_tree_entry_get_next(s->tree, te);
7908 else
7909 te = got_tree_entry_get_prev(s->tree, te);
7912 if (s->matched_entry) {
7913 s->first_displayed_entry = s->matched_entry;
7914 s->selected = 0;
7917 return NULL;
7920 static const struct got_error *
7921 show_tree_view(struct tog_view *view)
7923 const struct got_error *err = NULL;
7924 struct tog_tree_view_state *s = &view->state.tree;
7925 char *parent_path;
7927 err = tree_entry_path(&parent_path, &s->parents, NULL);
7928 if (err)
7929 return err;
7931 err = draw_tree_entries(view, parent_path);
7932 free(parent_path);
7934 view_border(view);
7935 return err;
7938 static const struct got_error *
7939 tree_goto_line(struct tog_view *view, int nlines)
7941 const struct got_error *err = NULL;
7942 struct tog_tree_view_state *s = &view->state.tree;
7943 struct got_tree_entry **fte, **lte, **ste;
7944 int g, last, first = 1, i = 1;
7945 int root = s->tree == s->root;
7946 int off = root ? 1 : 2;
7948 g = view->gline;
7949 view->gline = 0;
7951 if (g == 0)
7952 g = 1;
7953 else if (g > got_object_tree_get_nentries(s->tree))
7954 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7956 fte = &s->first_displayed_entry;
7957 lte = &s->last_displayed_entry;
7958 ste = &s->selected_entry;
7960 if (*fte != NULL) {
7961 first = got_tree_entry_get_index(*fte);
7962 first += off; /* account for ".." */
7964 last = got_tree_entry_get_index(*lte);
7965 last += off;
7967 if (g >= first && g <= last && g - first < nlines) {
7968 s->selected = g - first;
7969 return NULL; /* gline is on the current page */
7972 if (*ste != NULL) {
7973 i = got_tree_entry_get_index(*ste);
7974 i += off;
7977 if (i < g) {
7978 err = tree_scroll_down(view, g - i);
7979 if (err)
7980 return err;
7981 if (got_tree_entry_get_index(*lte) >=
7982 got_object_tree_get_nentries(s->tree) - 1 &&
7983 first + s->selected < g &&
7984 s->selected < s->ndisplayed - 1) {
7985 first = got_tree_entry_get_index(*fte);
7986 first += off;
7987 s->selected = g - first;
7989 } else if (i > g)
7990 tree_scroll_up(s, i - g);
7992 if (g < nlines &&
7993 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7994 s->selected = g - 1;
7996 return NULL;
7999 static const struct got_error *
8000 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
8002 const struct got_error *err = NULL;
8003 struct tog_tree_view_state *s = &view->state.tree;
8004 struct got_tree_entry *te;
8005 int n, nscroll = view->nlines - 3;
8007 if (view->gline)
8008 return tree_goto_line(view, nscroll);
8010 switch (ch) {
8011 case '0':
8012 case '$':
8013 case KEY_RIGHT:
8014 case 'l':
8015 case KEY_LEFT:
8016 case 'h':
8017 horizontal_scroll_input(view, ch);
8018 break;
8019 case 'i':
8020 s->show_ids = !s->show_ids;
8021 view->count = 0;
8022 break;
8023 case 'L':
8024 view->count = 0;
8025 if (!s->selected_entry)
8026 break;
8027 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8028 break;
8029 case 'R':
8030 view->count = 0;
8031 err = view_request_new(new_view, view, TOG_VIEW_REF);
8032 break;
8033 case 'g':
8034 case '=':
8035 case KEY_HOME:
8036 s->selected = 0;
8037 view->count = 0;
8038 if (s->tree == s->root)
8039 s->first_displayed_entry =
8040 got_object_tree_get_first_entry(s->tree);
8041 else
8042 s->first_displayed_entry = NULL;
8043 break;
8044 case 'G':
8045 case '*':
8046 case KEY_END: {
8047 int eos = view->nlines - 3;
8049 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8050 --eos; /* border */
8051 s->selected = 0;
8052 view->count = 0;
8053 te = got_object_tree_get_last_entry(s->tree);
8054 for (n = 0; n < eos; n++) {
8055 if (te == NULL) {
8056 if (s->tree != s->root) {
8057 s->first_displayed_entry = NULL;
8058 n++;
8060 break;
8062 s->first_displayed_entry = te;
8063 te = got_tree_entry_get_prev(s->tree, te);
8065 if (n > 0)
8066 s->selected = n - 1;
8067 break;
8069 case 'k':
8070 case KEY_UP:
8071 case CTRL('p'):
8072 if (s->selected > 0) {
8073 s->selected--;
8074 break;
8076 tree_scroll_up(s, 1);
8077 if (s->selected_entry == NULL ||
8078 (s->tree == s->root && s->selected_entry ==
8079 got_object_tree_get_first_entry(s->tree)))
8080 view->count = 0;
8081 break;