Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
24 #include <curses.h>
25 #include <panel.h>
26 #include <locale.h>
27 #include <sha1.h>
28 #include <sha2.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #include <string.h>
35 #include <err.h>
36 #include <unistd.h>
37 #include <limits.h>
38 #include <wchar.h>
39 #include <time.h>
40 #include <pthread.h>
41 #include <libgen.h>
42 #include <regex.h>
43 #include <sched.h>
45 #include "got_version.h"
46 #include "got_error.h"
47 #include "got_object.h"
48 #include "got_reference.h"
49 #include "got_repository.h"
50 #include "got_diff.h"
51 #include "got_opentemp.h"
52 #include "got_utf8.h"
53 #include "got_cancel.h"
54 #include "got_commit_graph.h"
55 #include "got_blame.h"
56 #include "got_privsep.h"
57 #include "got_path.h"
58 #include "got_worktree.h"
60 #ifndef MIN
61 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
62 #endif
64 #ifndef MAX
65 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
66 #endif
68 #define CTRL(x) ((x) & 0x1f)
70 #ifndef nitems
71 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
72 #endif
74 struct tog_cmd {
75 const char *name;
76 const struct got_error *(*cmd_main)(int, char *[]);
77 void (*cmd_usage)(void);
78 };
80 __dead static void usage(int, int);
81 __dead static void usage_log(void);
82 __dead static void usage_diff(void);
83 __dead static void usage_blame(void);
84 __dead static void usage_tree(void);
85 __dead static void usage_ref(void);
87 static const struct got_error* cmd_log(int, char *[]);
88 static const struct got_error* cmd_diff(int, char *[]);
89 static const struct got_error* cmd_blame(int, char *[]);
90 static const struct got_error* cmd_tree(int, char *[]);
91 static const struct got_error* cmd_ref(int, char *[]);
93 static const struct tog_cmd tog_commands[] = {
94 { "log", cmd_log, usage_log },
95 { "diff", cmd_diff, usage_diff },
96 { "blame", cmd_blame, usage_blame },
97 { "tree", cmd_tree, usage_tree },
98 { "ref", cmd_ref, usage_ref },
99 };
101 enum tog_view_type {
102 TOG_VIEW_DIFF,
103 TOG_VIEW_LOG,
104 TOG_VIEW_BLAME,
105 TOG_VIEW_TREE,
106 TOG_VIEW_REF,
107 TOG_VIEW_HELP
108 };
110 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
111 enum tog_keymap_type {
112 TOG_KEYMAP_KEYS = -2,
113 TOG_KEYMAP_GLOBAL,
114 TOG_KEYMAP_DIFF,
115 TOG_KEYMAP_LOG,
116 TOG_KEYMAP_BLAME,
117 TOG_KEYMAP_TREE,
118 TOG_KEYMAP_REF,
119 TOG_KEYMAP_HELP
120 };
122 enum tog_view_mode {
123 TOG_VIEW_SPLIT_NONE,
124 TOG_VIEW_SPLIT_VERT,
125 TOG_VIEW_SPLIT_HRZN
126 };
128 #define HSPLIT_SCALE 0.3f /* default horizontal split scale */
130 #define TOG_EOF_STRING "(END)"
132 struct commit_queue_entry {
133 TAILQ_ENTRY(commit_queue_entry) entry;
134 struct got_object_id *id;
135 struct got_commit_object *commit;
136 int idx;
137 };
138 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
139 struct commit_queue {
140 int ncommits;
141 struct commit_queue_head head;
142 };
144 struct tog_color {
145 STAILQ_ENTRY(tog_color) entry;
146 regex_t regex;
147 short colorpair;
148 };
149 STAILQ_HEAD(tog_colors, tog_color);
151 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
152 static struct got_reflist_object_id_map *tog_refs_idmap;
153 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
155 static const struct got_error *
156 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
157 struct got_reference* re2)
159 const char *name1 = got_ref_get_name(re1);
160 const char *name2 = got_ref_get_name(re2);
161 int isbackup1, isbackup2;
163 /* Sort backup refs towards the bottom of the list. */
164 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
165 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
166 if (!isbackup1 && isbackup2) {
167 *cmp = -1;
168 return NULL;
169 } else if (isbackup1 && !isbackup2) {
170 *cmp = 1;
171 return NULL;
174 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
175 return NULL;
178 static const struct got_error *
179 tog_load_refs(struct got_repository *repo, int sort_by_date)
181 const struct got_error *err;
183 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
184 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
185 repo);
186 if (err)
187 return err;
189 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
190 repo);
193 static void
194 tog_free_refs(void)
196 if (tog_refs_idmap) {
197 got_reflist_object_id_map_free(tog_refs_idmap);
198 tog_refs_idmap = NULL;
200 got_ref_list_free(&tog_refs);
203 static const struct got_error *
204 add_color(struct tog_colors *colors, const char *pattern,
205 int idx, short color)
207 const struct got_error *err = NULL;
208 struct tog_color *tc;
209 int regerr = 0;
211 if (idx < 1 || idx > COLOR_PAIRS - 1)
212 return NULL;
214 init_pair(idx, color, -1);
216 tc = calloc(1, sizeof(*tc));
217 if (tc == NULL)
218 return got_error_from_errno("calloc");
219 regerr = regcomp(&tc->regex, pattern,
220 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
221 if (regerr) {
222 static char regerr_msg[512];
223 static char err_msg[512];
224 regerror(regerr, &tc->regex, regerr_msg,
225 sizeof(regerr_msg));
226 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
227 regerr_msg);
228 err = got_error_msg(GOT_ERR_REGEX, err_msg);
229 free(tc);
230 return err;
232 tc->colorpair = idx;
233 STAILQ_INSERT_HEAD(colors, tc, entry);
234 return NULL;
237 static void
238 free_colors(struct tog_colors *colors)
240 struct tog_color *tc;
242 while (!STAILQ_EMPTY(colors)) {
243 tc = STAILQ_FIRST(colors);
244 STAILQ_REMOVE_HEAD(colors, entry);
245 regfree(&tc->regex);
246 free(tc);
250 static struct tog_color *
251 get_color(struct tog_colors *colors, int colorpair)
253 struct tog_color *tc = NULL;
255 STAILQ_FOREACH(tc, colors, entry) {
256 if (tc->colorpair == colorpair)
257 return tc;
260 return NULL;
263 static int
264 default_color_value(const char *envvar)
266 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
267 return COLOR_MAGENTA;
268 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
269 return COLOR_CYAN;
270 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
271 return COLOR_YELLOW;
272 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
273 return COLOR_GREEN;
274 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
275 return COLOR_MAGENTA;
276 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
277 return COLOR_MAGENTA;
278 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
279 return COLOR_CYAN;
280 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
281 return COLOR_GREEN;
282 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
283 return COLOR_GREEN;
284 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
285 return COLOR_CYAN;
286 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
287 return COLOR_YELLOW;
288 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
289 return COLOR_GREEN;
290 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
291 return COLOR_MAGENTA;
292 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
293 return COLOR_YELLOW;
294 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
295 return COLOR_CYAN;
297 return -1;
300 static int
301 get_color_value(const char *envvar)
303 const char *val = getenv(envvar);
305 if (val == NULL)
306 return default_color_value(envvar);
308 if (strcasecmp(val, "black") == 0)
309 return COLOR_BLACK;
310 if (strcasecmp(val, "red") == 0)
311 return COLOR_RED;
312 if (strcasecmp(val, "green") == 0)
313 return COLOR_GREEN;
314 if (strcasecmp(val, "yellow") == 0)
315 return COLOR_YELLOW;
316 if (strcasecmp(val, "blue") == 0)
317 return COLOR_BLUE;
318 if (strcasecmp(val, "magenta") == 0)
319 return COLOR_MAGENTA;
320 if (strcasecmp(val, "cyan") == 0)
321 return COLOR_CYAN;
322 if (strcasecmp(val, "white") == 0)
323 return COLOR_WHITE;
324 if (strcasecmp(val, "default") == 0)
325 return -1;
327 return default_color_value(envvar);
330 struct tog_diff_view_state {
331 struct got_object_id *id1, *id2;
332 const char *label1, *label2;
333 FILE *f, *f1, *f2;
334 int fd1, fd2;
335 int lineno;
336 int first_displayed_line;
337 int last_displayed_line;
338 int eof;
339 int diff_context;
340 int ignore_whitespace;
341 int force_text_diff;
342 struct got_repository *repo;
343 struct got_diff_line *lines;
344 size_t nlines;
345 int matched_line;
346 int selected_line;
348 /* passed from log or blame view; may be NULL */
349 struct tog_view *parent_view;
350 };
352 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
353 static volatile sig_atomic_t tog_thread_error;
355 struct tog_log_thread_args {
356 pthread_cond_t need_commits;
357 pthread_cond_t commit_loaded;
358 int commits_needed;
359 int load_all;
360 struct got_commit_graph *graph;
361 struct commit_queue *real_commits;
362 const char *in_repo_path;
363 struct got_object_id *start_id;
364 struct got_repository *repo;
365 int *pack_fds;
366 int log_complete;
367 sig_atomic_t *quit;
368 struct commit_queue_entry **first_displayed_entry;
369 struct commit_queue_entry **selected_entry;
370 int *searching;
371 int *search_next_done;
372 regex_t *regex;
373 int *limiting;
374 int limit_match;
375 regex_t *limit_regex;
376 struct commit_queue *limit_commits;
377 };
379 struct tog_log_view_state {
380 struct commit_queue *commits;
381 struct commit_queue_entry *first_displayed_entry;
382 struct commit_queue_entry *last_displayed_entry;
383 struct commit_queue_entry *selected_entry;
384 struct commit_queue real_commits;
385 int selected;
386 char *in_repo_path;
387 char *head_ref_name;
388 int log_branches;
389 struct got_repository *repo;
390 struct got_object_id *start_id;
391 sig_atomic_t quit;
392 pthread_t thread;
393 struct tog_log_thread_args thread_args;
394 struct commit_queue_entry *matched_entry;
395 struct commit_queue_entry *search_entry;
396 struct tog_colors colors;
397 int use_committer;
398 int limit_view;
399 regex_t limit_regex;
400 struct commit_queue limit_commits;
401 };
403 #define TOG_COLOR_DIFF_MINUS 1
404 #define TOG_COLOR_DIFF_PLUS 2
405 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
406 #define TOG_COLOR_DIFF_META 4
407 #define TOG_COLOR_TREE_SUBMODULE 5
408 #define TOG_COLOR_TREE_SYMLINK 6
409 #define TOG_COLOR_TREE_DIRECTORY 7
410 #define TOG_COLOR_TREE_EXECUTABLE 8
411 #define TOG_COLOR_COMMIT 9
412 #define TOG_COLOR_AUTHOR 10
413 #define TOG_COLOR_DATE 11
414 #define TOG_COLOR_REFS_HEADS 12
415 #define TOG_COLOR_REFS_TAGS 13
416 #define TOG_COLOR_REFS_REMOTES 14
417 #define TOG_COLOR_REFS_BACKUP 15
419 struct tog_blame_cb_args {
420 struct tog_blame_line *lines; /* one per line */
421 int nlines;
423 struct tog_view *view;
424 struct got_object_id *commit_id;
425 int *quit;
426 };
428 struct tog_blame_thread_args {
429 const char *path;
430 struct got_repository *repo;
431 struct tog_blame_cb_args *cb_args;
432 int *complete;
433 got_cancel_cb cancel_cb;
434 void *cancel_arg;
435 pthread_cond_t blame_complete;
436 };
438 struct tog_blame {
439 FILE *f;
440 off_t filesize;
441 struct tog_blame_line *lines;
442 int nlines;
443 off_t *line_offsets;
444 pthread_t thread;
445 struct tog_blame_thread_args thread_args;
446 struct tog_blame_cb_args cb_args;
447 const char *path;
448 int *pack_fds;
449 };
451 struct tog_blame_view_state {
452 int first_displayed_line;
453 int last_displayed_line;
454 int selected_line;
455 int last_diffed_line;
456 int blame_complete;
457 int eof;
458 int done;
459 struct got_object_id_queue blamed_commits;
460 struct got_object_qid *blamed_commit;
461 char *path;
462 struct got_repository *repo;
463 struct got_object_id *commit_id;
464 struct got_object_id *id_to_log;
465 struct tog_blame blame;
466 int matched_line;
467 struct tog_colors colors;
468 };
470 struct tog_parent_tree {
471 TAILQ_ENTRY(tog_parent_tree) entry;
472 struct got_tree_object *tree;
473 struct got_tree_entry *first_displayed_entry;
474 struct got_tree_entry *selected_entry;
475 int selected;
476 };
478 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
480 struct tog_tree_view_state {
481 char *tree_label;
482 struct got_object_id *commit_id;/* commit which this tree belongs to */
483 struct got_tree_object *root; /* the commit's root tree entry */
484 struct got_tree_object *tree; /* currently displayed (sub-)tree */
485 struct got_tree_entry *first_displayed_entry;
486 struct got_tree_entry *last_displayed_entry;
487 struct got_tree_entry *selected_entry;
488 int ndisplayed, selected, show_ids;
489 struct tog_parent_trees parents; /* parent trees of current sub-tree */
490 char *head_ref_name;
491 struct got_repository *repo;
492 struct got_tree_entry *matched_entry;
493 struct tog_colors colors;
494 };
496 struct tog_reflist_entry {
497 TAILQ_ENTRY(tog_reflist_entry) entry;
498 struct got_reference *ref;
499 int idx;
500 };
502 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
504 struct tog_ref_view_state {
505 struct tog_reflist_head refs;
506 struct tog_reflist_entry *first_displayed_entry;
507 struct tog_reflist_entry *last_displayed_entry;
508 struct tog_reflist_entry *selected_entry;
509 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
510 struct got_repository *repo;
511 struct tog_reflist_entry *matched_entry;
512 struct tog_colors colors;
513 };
515 struct tog_help_view_state {
516 FILE *f;
517 off_t *line_offsets;
518 size_t nlines;
519 int lineno;
520 int first_displayed_line;
521 int last_displayed_line;
522 int eof;
523 int matched_line;
524 int selected_line;
525 int all;
526 enum tog_keymap_type type;
527 };
529 #define GENERATE_HELP \
530 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
531 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
532 KEY_("k C-p Up", "Move cursor or page up one line"), \
533 KEY_("j C-n Down", "Move cursor or page down one line"), \
534 KEY_("C-b b PgUp", "Scroll the view up one page"), \
535 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
536 KEY_("C-u u", "Scroll the view up one half page"), \
537 KEY_("C-d d", "Scroll the view down one half page"), \
538 KEY_("g", "Go to line N (default: first line)"), \
539 KEY_("Home =", "Go to the first line"), \
540 KEY_("G", "Go to line N (default: last line)"), \
541 KEY_("End *", "Go to the last line"), \
542 KEY_("l Right", "Scroll the view right"), \
543 KEY_("h Left", "Scroll the view left"), \
544 KEY_("$", "Scroll view to the rightmost position"), \
545 KEY_("0", "Scroll view to the leftmost position"), \
546 KEY_("-", "Decrease size of the focussed split"), \
547 KEY_("+", "Increase size of the focussed split"), \
548 KEY_("Tab", "Switch focus between views"), \
549 KEY_("F", "Toggle fullscreen mode"), \
550 KEY_("S", "Switch split-screen layout"), \
551 KEY_("/", "Open prompt to enter search term"), \
552 KEY_("n", "Find next line/token matching the current search term"), \
553 KEY_("N", "Find previous line/token matching the current search term"),\
554 KEY_("q", "Quit the focussed view; Quit help screen"), \
555 KEY_("Q", "Quit tog"), \
557 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
558 KEY_("< ,", "Move cursor up one commit"), \
559 KEY_("> .", "Move cursor down one commit"), \
560 KEY_("Enter", "Open diff view of the selected commit"), \
561 KEY_("B", "Reload the log view and toggle display of merged commits"), \
562 KEY_("R", "Open ref view of all repository references"), \
563 KEY_("T", "Display tree view of the repository from the selected" \
564 " commit"), \
565 KEY_("@", "Toggle between displaying author and committer name"), \
566 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
567 KEY_("C-g Backspace", "Cancel current search or log operation"), \
568 KEY_("C-l", "Reload the log view with new commits in the repository"), \
570 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
571 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
572 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
573 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
574 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
575 " data"), \
576 KEY_("(", "Go to the previous file in the diff"), \
577 KEY_(")", "Go to the next file in the diff"), \
578 KEY_("{", "Go to the previous hunk in the diff"), \
579 KEY_("}", "Go to the next hunk in the diff"), \
580 KEY_("[", "Decrease the number of context lines"), \
581 KEY_("]", "Increase the number of context lines"), \
582 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
584 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
585 KEY_("Enter", "Display diff view of the selected line's commit"), \
586 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
587 KEY_("L", "Open log view for the currently selected annotated line"), \
588 KEY_("C", "Reload view with the previously blamed commit"), \
589 KEY_("c", "Reload view with the version of the file found in the" \
590 " selected line's commit"), \
591 KEY_("p", "Reload view with the version of the file found in the" \
592 " selected line's parent commit"), \
594 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
595 KEY_("Enter", "Enter selected directory or open blame view of the" \
596 " selected file"), \
597 KEY_("L", "Open log view for the selected entry"), \
598 KEY_("R", "Open ref view of all repository references"), \
599 KEY_("i", "Show object IDs for all tree entries"), \
600 KEY_("Backspace", "Return to the parent directory"), \
602 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
603 KEY_("Enter", "Display log view of the selected reference"), \
604 KEY_("T", "Display tree view of the selected reference"), \
605 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
606 KEY_("m", "Toggle display of last modified date for each reference"), \
607 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
608 KEY_("C-l", "Reload view with all repository references")
610 struct tog_key_map {
611 const char *keys;
612 const char *info;
613 enum tog_keymap_type type;
614 };
616 /* curses io for tog regress */
617 struct tog_io {
618 FILE *cin;
619 FILE *cout;
620 FILE *f;
621 FILE *sdump;
622 int wait_for_ui;
623 } tog_io;
624 static int using_mock_io;
626 #define TOG_KEY_SCRDUMP SHRT_MIN
628 /*
629 * We implement two types of views: parent views and child views.
631 * The 'Tab' key switches focus between a parent view and its child view.
632 * Child views are shown side-by-side to their parent view, provided
633 * there is enough screen estate.
635 * When a new view is opened from within a parent view, this new view
636 * becomes a child view of the parent view, replacing any existing child.
638 * When a new view is opened from within a child view, this new view
639 * becomes a parent view which will obscure the views below until the
640 * user quits the new parent view by typing 'q'.
642 * This list of views contains parent views only.
643 * Child views are only pointed to by their parent view.
644 */
645 TAILQ_HEAD(tog_view_list_head, tog_view);
647 struct tog_view {
648 TAILQ_ENTRY(tog_view) entry;
649 WINDOW *window;
650 PANEL *panel;
651 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
652 int resized_y, resized_x; /* begin_y/x based on user resizing */
653 int maxx, x; /* max column and current start column */
654 int lines, cols; /* copies of LINES and COLS */
655 int nscrolled, offset; /* lines scrolled and hsplit line offset */
656 int gline, hiline; /* navigate to and highlight this nG line */
657 int ch, count; /* current keymap and count prefix */
658 int resized; /* set when in a resize event */
659 int focussed; /* Only set on one parent or child view at a time. */
660 int dying;
661 struct tog_view *parent;
662 struct tog_view *child;
664 /*
665 * This flag is initially set on parent views when a new child view
666 * is created. It gets toggled when the 'Tab' key switches focus
667 * between parent and child.
668 * The flag indicates whether focus should be passed on to our child
669 * view if this parent view gets picked for focus after another parent
670 * view was closed. This prevents child views from losing focus in such
671 * situations.
672 */
673 int focus_child;
675 enum tog_view_mode mode;
676 /* type-specific state */
677 enum tog_view_type type;
678 union {
679 struct tog_diff_view_state diff;
680 struct tog_log_view_state log;
681 struct tog_blame_view_state blame;
682 struct tog_tree_view_state tree;
683 struct tog_ref_view_state ref;
684 struct tog_help_view_state help;
685 } state;
687 const struct got_error *(*show)(struct tog_view *);
688 const struct got_error *(*input)(struct tog_view **,
689 struct tog_view *, int);
690 const struct got_error *(*reset)(struct tog_view *);
691 const struct got_error *(*resize)(struct tog_view *, int);
692 const struct got_error *(*close)(struct tog_view *);
694 const struct got_error *(*search_start)(struct tog_view *);
695 const struct got_error *(*search_next)(struct tog_view *);
696 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
697 int **, int **, int **, int **);
698 int search_started;
699 int searching;
700 #define TOG_SEARCH_FORWARD 1
701 #define TOG_SEARCH_BACKWARD 2
702 int search_next_done;
703 #define TOG_SEARCH_HAVE_MORE 1
704 #define TOG_SEARCH_NO_MORE 2
705 #define TOG_SEARCH_HAVE_NONE 3
706 regex_t regex;
707 regmatch_t regmatch;
708 const char *action;
709 };
711 static const struct got_error *open_diff_view(struct tog_view *,
712 struct got_object_id *, struct got_object_id *,
713 const char *, const char *, int, int, int, struct tog_view *,
714 struct got_repository *);
715 static const struct got_error *show_diff_view(struct tog_view *);
716 static const struct got_error *input_diff_view(struct tog_view **,
717 struct tog_view *, int);
718 static const struct got_error *reset_diff_view(struct tog_view *);
719 static const struct got_error* close_diff_view(struct tog_view *);
720 static const struct got_error *search_start_diff_view(struct tog_view *);
721 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
722 size_t *, int **, int **, int **, int **);
723 static const struct got_error *search_next_view_match(struct tog_view *);
725 static const struct got_error *open_log_view(struct tog_view *,
726 struct got_object_id *, struct got_repository *,
727 const char *, const char *, int);
728 static const struct got_error * show_log_view(struct tog_view *);
729 static const struct got_error *input_log_view(struct tog_view **,
730 struct tog_view *, int);
731 static const struct got_error *resize_log_view(struct tog_view *, int);
732 static const struct got_error *close_log_view(struct tog_view *);
733 static const struct got_error *search_start_log_view(struct tog_view *);
734 static const struct got_error *search_next_log_view(struct tog_view *);
736 static const struct got_error *open_blame_view(struct tog_view *, char *,
737 struct got_object_id *, struct got_repository *);
738 static const struct got_error *show_blame_view(struct tog_view *);
739 static const struct got_error *input_blame_view(struct tog_view **,
740 struct tog_view *, int);
741 static const struct got_error *reset_blame_view(struct tog_view *);
742 static const struct got_error *close_blame_view(struct tog_view *);
743 static const struct got_error *search_start_blame_view(struct tog_view *);
744 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
745 size_t *, int **, int **, int **, int **);
747 static const struct got_error *open_tree_view(struct tog_view *,
748 struct got_object_id *, const char *, struct got_repository *);
749 static const struct got_error *show_tree_view(struct tog_view *);
750 static const struct got_error *input_tree_view(struct tog_view **,
751 struct tog_view *, int);
752 static const struct got_error *close_tree_view(struct tog_view *);
753 static const struct got_error *search_start_tree_view(struct tog_view *);
754 static const struct got_error *search_next_tree_view(struct tog_view *);
756 static const struct got_error *open_ref_view(struct tog_view *,
757 struct got_repository *);
758 static const struct got_error *show_ref_view(struct tog_view *);
759 static const struct got_error *input_ref_view(struct tog_view **,
760 struct tog_view *, int);
761 static const struct got_error *close_ref_view(struct tog_view *);
762 static const struct got_error *search_start_ref_view(struct tog_view *);
763 static const struct got_error *search_next_ref_view(struct tog_view *);
765 static const struct got_error *open_help_view(struct tog_view *,
766 struct tog_view *);
767 static const struct got_error *show_help_view(struct tog_view *);
768 static const struct got_error *input_help_view(struct tog_view **,
769 struct tog_view *, int);
770 static const struct got_error *reset_help_view(struct tog_view *);
771 static const struct got_error* close_help_view(struct tog_view *);
772 static const struct got_error *search_start_help_view(struct tog_view *);
773 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
774 size_t *, int **, int **, int **, int **);
776 static volatile sig_atomic_t tog_sigwinch_received;
777 static volatile sig_atomic_t tog_sigpipe_received;
778 static volatile sig_atomic_t tog_sigcont_received;
779 static volatile sig_atomic_t tog_sigint_received;
780 static volatile sig_atomic_t tog_sigterm_received;
782 static void
783 tog_sigwinch(int signo)
785 tog_sigwinch_received = 1;
788 static void
789 tog_sigpipe(int signo)
791 tog_sigpipe_received = 1;
794 static void
795 tog_sigcont(int signo)
797 tog_sigcont_received = 1;
800 static void
801 tog_sigint(int signo)
803 tog_sigint_received = 1;
806 static void
807 tog_sigterm(int signo)
809 tog_sigterm_received = 1;
812 static int
813 tog_fatal_signal_received(void)
815 return (tog_sigpipe_received ||
816 tog_sigint_received || tog_sigterm_received);
819 static const struct got_error *
820 view_close(struct tog_view *view)
822 const struct got_error *err = NULL, *child_err = NULL;
824 if (view->child) {
825 child_err = view_close(view->child);
826 view->child = NULL;
828 if (view->close)
829 err = view->close(view);
830 if (view->panel)
831 del_panel(view->panel);
832 if (view->window)
833 delwin(view->window);
834 free(view);
835 return err ? err : child_err;
838 static struct tog_view *
839 view_open(int nlines, int ncols, int begin_y, int begin_x,
840 enum tog_view_type type)
842 struct tog_view *view = calloc(1, sizeof(*view));
844 if (view == NULL)
845 return NULL;
847 view->type = type;
848 view->lines = LINES;
849 view->cols = COLS;
850 view->nlines = nlines ? nlines : LINES - begin_y;
851 view->ncols = ncols ? ncols : COLS - begin_x;
852 view->begin_y = begin_y;
853 view->begin_x = begin_x;
854 view->window = newwin(nlines, ncols, begin_y, begin_x);
855 if (view->window == NULL) {
856 view_close(view);
857 return NULL;
859 view->panel = new_panel(view->window);
860 if (view->panel == NULL ||
861 set_panel_userptr(view->panel, view) != OK) {
862 view_close(view);
863 return NULL;
866 keypad(view->window, TRUE);
867 return view;
870 static int
871 view_split_begin_x(int begin_x)
873 if (begin_x > 0 || COLS < 120)
874 return 0;
875 return (COLS - MAX(COLS / 2, 80));
878 /* XXX Stub till we decide what to do. */
879 static int
880 view_split_begin_y(int lines)
882 return lines * HSPLIT_SCALE;
885 static const struct got_error *view_resize(struct tog_view *);
887 static const struct got_error *
888 view_splitscreen(struct tog_view *view)
890 const struct got_error *err = NULL;
892 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
893 if (view->resized_y && view->resized_y < view->lines)
894 view->begin_y = view->resized_y;
895 else
896 view->begin_y = view_split_begin_y(view->nlines);
897 view->begin_x = 0;
898 } else if (!view->resized) {
899 if (view->resized_x && view->resized_x < view->cols - 1 &&
900 view->cols > 119)
901 view->begin_x = view->resized_x;
902 else
903 view->begin_x = view_split_begin_x(0);
904 view->begin_y = 0;
906 view->nlines = LINES - view->begin_y;
907 view->ncols = COLS - view->begin_x;
908 view->lines = LINES;
909 view->cols = COLS;
910 err = view_resize(view);
911 if (err)
912 return err;
914 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
915 view->parent->nlines = view->begin_y;
917 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
918 return got_error_from_errno("mvwin");
920 return NULL;
923 static const struct got_error *
924 view_fullscreen(struct tog_view *view)
926 const struct got_error *err = NULL;
928 view->begin_x = 0;
929 view->begin_y = view->resized ? view->begin_y : 0;
930 view->nlines = view->resized ? view->nlines : LINES;
931 view->ncols = COLS;
932 view->lines = LINES;
933 view->cols = COLS;
934 err = view_resize(view);
935 if (err)
936 return err;
938 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
939 return got_error_from_errno("mvwin");
941 return NULL;
944 static int
945 view_is_parent_view(struct tog_view *view)
947 return view->parent == NULL;
950 static int
951 view_is_splitscreen(struct tog_view *view)
953 return view->begin_x > 0 || view->begin_y > 0;
956 static int
957 view_is_fullscreen(struct tog_view *view)
959 return view->nlines == LINES && view->ncols == COLS;
962 static int
963 view_is_hsplit_top(struct tog_view *view)
965 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
966 view_is_splitscreen(view->child);
969 static void
970 view_border(struct tog_view *view)
972 PANEL *panel;
973 const struct tog_view *view_above;
975 if (view->parent)
976 return view_border(view->parent);
978 panel = panel_above(view->panel);
979 if (panel == NULL)
980 return;
982 view_above = panel_userptr(panel);
983 if (view->mode == TOG_VIEW_SPLIT_HRZN)
984 mvwhline(view->window, view_above->begin_y - 1,
985 view->begin_x, ACS_HLINE, view->ncols);
986 else
987 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
988 ACS_VLINE, view->nlines);
991 static const struct got_error *view_init_hsplit(struct tog_view *, int);
992 static const struct got_error *request_log_commits(struct tog_view *);
993 static const struct got_error *offset_selection_down(struct tog_view *);
994 static void offset_selection_up(struct tog_view *);
995 static void view_get_split(struct tog_view *, int *, int *);
997 static const struct got_error *
998 view_resize(struct tog_view *view)
1000 const struct got_error *err = NULL;
1001 int dif, nlines, ncols;
1003 dif = LINES - view->lines; /* line difference */
1005 if (view->lines > LINES)
1006 nlines = view->nlines - (view->lines - LINES);
1007 else
1008 nlines = view->nlines + (LINES - view->lines);
1009 if (view->cols > COLS)
1010 ncols = view->ncols - (view->cols - COLS);
1011 else
1012 ncols = view->ncols + (COLS - view->cols);
1014 if (view->child) {
1015 int hs = view->child->begin_y;
1017 if (!view_is_fullscreen(view))
1018 view->child->begin_x = view_split_begin_x(view->begin_x);
1019 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1020 view->child->begin_x == 0) {
1021 ncols = COLS;
1023 view_fullscreen(view->child);
1024 if (view->child->focussed)
1025 show_panel(view->child->panel);
1026 else
1027 show_panel(view->panel);
1028 } else {
1029 ncols = view->child->begin_x;
1031 view_splitscreen(view->child);
1032 show_panel(view->child->panel);
1035 * XXX This is ugly and needs to be moved into the above
1036 * logic but "works" for now and my attempts at moving it
1037 * break either 'tab' or 'F' key maps in horizontal splits.
1039 if (hs) {
1040 err = view_splitscreen(view->child);
1041 if (err)
1042 return err;
1043 if (dif < 0) { /* top split decreased */
1044 err = offset_selection_down(view);
1045 if (err)
1046 return err;
1048 view_border(view);
1049 update_panels();
1050 doupdate();
1051 show_panel(view->child->panel);
1052 nlines = view->nlines;
1054 } else if (view->parent == NULL)
1055 ncols = COLS;
1057 if (view->resize && dif > 0) {
1058 err = view->resize(view, dif);
1059 if (err)
1060 return err;
1063 if (wresize(view->window, nlines, ncols) == ERR)
1064 return got_error_from_errno("wresize");
1065 if (replace_panel(view->panel, view->window) == ERR)
1066 return got_error_from_errno("replace_panel");
1067 wclear(view->window);
1069 view->nlines = nlines;
1070 view->ncols = ncols;
1071 view->lines = LINES;
1072 view->cols = COLS;
1074 return NULL;
1077 static const struct got_error *
1078 resize_log_view(struct tog_view *view, int increase)
1080 struct tog_log_view_state *s = &view->state.log;
1081 const struct got_error *err = NULL;
1082 int n = 0;
1084 if (s->selected_entry)
1085 n = s->selected_entry->idx + view->lines - s->selected;
1088 * Request commits to account for the increased
1089 * height so we have enough to populate the view.
1091 if (s->commits->ncommits < n) {
1092 view->nscrolled = n - s->commits->ncommits + increase + 1;
1093 err = request_log_commits(view);
1096 return err;
1099 static void
1100 view_adjust_offset(struct tog_view *view, int n)
1102 if (n == 0)
1103 return;
1105 if (view->parent && view->parent->offset) {
1106 if (view->parent->offset + n >= 0)
1107 view->parent->offset += n;
1108 else
1109 view->parent->offset = 0;
1110 } else if (view->offset) {
1111 if (view->offset - n >= 0)
1112 view->offset -= n;
1113 else
1114 view->offset = 0;
1118 static const struct got_error *
1119 view_resize_split(struct tog_view *view, int resize)
1121 const struct got_error *err = NULL;
1122 struct tog_view *v = NULL;
1124 if (view->parent)
1125 v = view->parent;
1126 else
1127 v = view;
1129 if (!v->child || !view_is_splitscreen(v->child))
1130 return NULL;
1132 v->resized = v->child->resized = resize; /* lock for resize event */
1134 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1135 if (v->child->resized_y)
1136 v->child->begin_y = v->child->resized_y;
1137 if (view->parent)
1138 v->child->begin_y -= resize;
1139 else
1140 v->child->begin_y += resize;
1141 if (v->child->begin_y < 3) {
1142 view->count = 0;
1143 v->child->begin_y = 3;
1144 } else if (v->child->begin_y > LINES - 1) {
1145 view->count = 0;
1146 v->child->begin_y = LINES - 1;
1148 v->ncols = COLS;
1149 v->child->ncols = COLS;
1150 view_adjust_offset(view, resize);
1151 err = view_init_hsplit(v, v->child->begin_y);
1152 if (err)
1153 return err;
1154 v->child->resized_y = v->child->begin_y;
1155 } else {
1156 if (v->child->resized_x)
1157 v->child->begin_x = v->child->resized_x;
1158 if (view->parent)
1159 v->child->begin_x -= resize;
1160 else
1161 v->child->begin_x += resize;
1162 if (v->child->begin_x < 11) {
1163 view->count = 0;
1164 v->child->begin_x = 11;
1165 } else if (v->child->begin_x > COLS - 1) {
1166 view->count = 0;
1167 v->child->begin_x = COLS - 1;
1169 v->child->resized_x = v->child->begin_x;
1172 v->child->mode = v->mode;
1173 v->child->nlines = v->lines - v->child->begin_y;
1174 v->child->ncols = v->cols - v->child->begin_x;
1175 v->focus_child = 1;
1177 err = view_fullscreen(v);
1178 if (err)
1179 return err;
1180 err = view_splitscreen(v->child);
1181 if (err)
1182 return err;
1184 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1185 err = offset_selection_down(v->child);
1186 if (err)
1187 return err;
1190 if (v->resize)
1191 err = v->resize(v, 0);
1192 else if (v->child->resize)
1193 err = v->child->resize(v->child, 0);
1195 v->resized = v->child->resized = 0;
1197 return err;
1200 static void
1201 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1203 struct tog_view *v = src->child ? src->child : src;
1205 dst->resized_x = v->resized_x;
1206 dst->resized_y = v->resized_y;
1209 static const struct got_error *
1210 view_close_child(struct tog_view *view)
1212 const struct got_error *err = NULL;
1214 if (view->child == NULL)
1215 return NULL;
1217 err = view_close(view->child);
1218 view->child = NULL;
1219 return err;
1222 static const struct got_error *
1223 view_set_child(struct tog_view *view, struct tog_view *child)
1225 const struct got_error *err = NULL;
1227 view->child = child;
1228 child->parent = view;
1230 err = view_resize(view);
1231 if (err)
1232 return err;
1234 if (view->child->resized_x || view->child->resized_y)
1235 err = view_resize_split(view, 0);
1237 return err;
1240 static const struct got_error *view_dispatch_request(struct tog_view **,
1241 struct tog_view *, enum tog_view_type, int, int);
1243 static const struct got_error *
1244 view_request_new(struct tog_view **requested, struct tog_view *view,
1245 enum tog_view_type request)
1247 struct tog_view *new_view = NULL;
1248 const struct got_error *err;
1249 int y = 0, x = 0;
1251 *requested = NULL;
1253 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1254 view_get_split(view, &y, &x);
1256 err = view_dispatch_request(&new_view, view, request, y, x);
1257 if (err)
1258 return err;
1260 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1261 request != TOG_VIEW_HELP) {
1262 err = view_init_hsplit(view, y);
1263 if (err)
1264 return err;
1267 view->focussed = 0;
1268 new_view->focussed = 1;
1269 new_view->mode = view->mode;
1270 new_view->nlines = request == TOG_VIEW_HELP ?
1271 view->lines : view->lines - y;
1273 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1274 view_transfer_size(new_view, view);
1275 err = view_close_child(view);
1276 if (err)
1277 return err;
1278 err = view_set_child(view, new_view);
1279 if (err)
1280 return err;
1281 view->focus_child = 1;
1282 } else
1283 *requested = new_view;
1285 return NULL;
1288 static void
1289 tog_resizeterm(void)
1291 int cols, lines;
1292 struct winsize size;
1294 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1295 cols = 80; /* Default */
1296 lines = 24;
1297 } else {
1298 cols = size.ws_col;
1299 lines = size.ws_row;
1301 resize_term(lines, cols);
1304 static const struct got_error *
1305 view_search_start(struct tog_view *view, int fast_refresh)
1307 const struct got_error *err = NULL;
1308 struct tog_view *v = view;
1309 char pattern[1024];
1310 int ret;
1312 if (view->search_started) {
1313 regfree(&view->regex);
1314 view->searching = 0;
1315 memset(&view->regmatch, 0, sizeof(view->regmatch));
1317 view->search_started = 0;
1319 if (view->nlines < 1)
1320 return NULL;
1322 if (view_is_hsplit_top(view))
1323 v = view->child;
1324 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1325 v = view->parent;
1327 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1328 wclrtoeol(v->window);
1330 nodelay(v->window, FALSE); /* block for search term input */
1331 nocbreak();
1332 echo();
1333 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1334 wrefresh(v->window);
1335 cbreak();
1336 noecho();
1337 nodelay(v->window, TRUE);
1338 if (!fast_refresh && !using_mock_io)
1339 halfdelay(10);
1340 if (ret == ERR)
1341 return NULL;
1343 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1344 err = view->search_start(view);
1345 if (err) {
1346 regfree(&view->regex);
1347 return err;
1349 view->search_started = 1;
1350 view->searching = TOG_SEARCH_FORWARD;
1351 view->search_next_done = 0;
1352 view->search_next(view);
1355 return NULL;
1358 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1359 static const struct got_error *
1360 switch_split(struct tog_view *view)
1362 const struct got_error *err = NULL;
1363 struct tog_view *v = NULL;
1365 if (view->parent)
1366 v = view->parent;
1367 else
1368 v = view;
1370 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1371 v->mode = TOG_VIEW_SPLIT_VERT;
1372 else
1373 v->mode = TOG_VIEW_SPLIT_HRZN;
1375 if (!v->child)
1376 return NULL;
1377 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1378 v->mode = TOG_VIEW_SPLIT_NONE;
1380 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1381 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1382 v->child->begin_y = v->child->resized_y;
1383 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1384 v->child->begin_x = v->child->resized_x;
1387 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1388 v->ncols = COLS;
1389 v->child->ncols = COLS;
1390 v->child->nscrolled = LINES - v->child->nlines;
1392 err = view_init_hsplit(v, v->child->begin_y);
1393 if (err)
1394 return err;
1396 v->child->mode = v->mode;
1397 v->child->nlines = v->lines - v->child->begin_y;
1398 v->focus_child = 1;
1400 err = view_fullscreen(v);
1401 if (err)
1402 return err;
1403 err = view_splitscreen(v->child);
1404 if (err)
1405 return err;
1407 if (v->mode == TOG_VIEW_SPLIT_NONE)
1408 v->mode = TOG_VIEW_SPLIT_VERT;
1409 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1410 err = offset_selection_down(v);
1411 if (err)
1412 return err;
1413 err = offset_selection_down(v->child);
1414 if (err)
1415 return err;
1416 } else {
1417 offset_selection_up(v);
1418 offset_selection_up(v->child);
1420 if (v->resize)
1421 err = v->resize(v, 0);
1422 else if (v->child->resize)
1423 err = v->child->resize(v->child, 0);
1425 return err;
1429 * Strip trailing whitespace from str starting at byte *n;
1430 * if *n < 0, use strlen(str). Return new str length in *n.
1432 static void
1433 strip_trailing_ws(char *str, int *n)
1435 size_t x = *n;
1437 if (str == NULL || *str == '\0')
1438 return;
1440 if (x < 0)
1441 x = strlen(str);
1443 while (x-- > 0 && isspace((unsigned char)str[x]))
1444 str[x] = '\0';
1446 *n = x + 1;
1450 * Extract visible substring of line y from the curses screen
1451 * and strip trailing whitespace. If vline is set, overwrite
1452 * line[vline] with '|' because the ACS_VLINE character is
1453 * written out as 'x'. Write the line to file f.
1455 static const struct got_error *
1456 view_write_line(FILE *f, int y, int vline)
1458 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1459 int r, w;
1461 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1462 if (r == ERR)
1463 return got_error_fmt(GOT_ERR_RANGE,
1464 "failed to extract line %d", y);
1467 * In some views, lines are padded with blanks to COLS width.
1468 * Strip them so we can diff without the -b flag when testing.
1470 strip_trailing_ws(line, &r);
1472 if (vline > 0)
1473 line[vline] = '|';
1475 w = fprintf(f, "%s\n", line);
1476 if (w != r + 1) /* \n */
1477 return got_ferror(f, GOT_ERR_IO);
1479 return NULL;
1483 * Capture the visible curses screen by writing each line to the
1484 * file at the path set via the TOG_SCR_DUMP environment variable.
1486 static const struct got_error *
1487 screendump(struct tog_view *view)
1489 const struct got_error *err;
1490 int i;
1492 err = got_opentemp_truncate(tog_io.sdump);
1493 if (err)
1494 return err;
1496 if ((view->child && view->child->begin_x) ||
1497 (view->parent && view->begin_x)) {
1498 int ncols = view->child ? view->ncols : view->parent->ncols;
1500 /* vertical splitscreen */
1501 for (i = 0; i < view->nlines; ++i) {
1502 err = view_write_line(tog_io.sdump, i, ncols - 1);
1503 if (err)
1504 goto done;
1506 } else {
1507 int hline = 0;
1509 /* fullscreen or horizontal splitscreen */
1510 if ((view->child && view->child->begin_y) ||
1511 (view->parent && view->begin_y)) /* hsplit */
1512 hline = view->child ?
1513 view->child->begin_y : view->begin_y;
1515 for (i = 0; i < view->lines; i++) {
1516 if (hline && i == hline - 1) {
1517 int c;
1519 /* ACS_HLINE writes out as 'q', overwrite it */
1520 for (c = 0; c < view->cols; ++c)
1521 fputc('-', tog_io.sdump);
1522 fputc('\n', tog_io.sdump);
1523 continue;
1526 err = view_write_line(tog_io.sdump, i, 0);
1527 if (err)
1528 goto done;
1532 done:
1533 return err;
1537 * Compute view->count from numeric input. Assign total to view->count and
1538 * return first non-numeric key entered.
1540 static int
1541 get_compound_key(struct tog_view *view, int c)
1543 struct tog_view *v = view;
1544 int x, n = 0;
1546 if (view_is_hsplit_top(view))
1547 v = view->child;
1548 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1549 v = view->parent;
1551 view->count = 0;
1552 cbreak(); /* block for input */
1553 nodelay(view->window, FALSE);
1554 wmove(v->window, v->nlines - 1, 0);
1555 wclrtoeol(v->window);
1556 waddch(v->window, ':');
1558 do {
1559 x = getcurx(v->window);
1560 if (x != ERR && x < view->ncols) {
1561 waddch(v->window, c);
1562 wrefresh(v->window);
1566 * Don't overflow. Max valid request should be the greatest
1567 * between the longest and total lines; cap at 10 million.
1569 if (n >= 9999999)
1570 n = 9999999;
1571 else
1572 n = n * 10 + (c - '0');
1573 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1575 if (c == 'G' || c == 'g') { /* nG key map */
1576 view->gline = view->hiline = n;
1577 n = 0;
1578 c = 0;
1581 /* Massage excessive or inapplicable values at the input handler. */
1582 view->count = n;
1584 return c;
1587 static void
1588 action_report(struct tog_view *view)
1590 struct tog_view *v = view;
1592 if (view_is_hsplit_top(view))
1593 v = view->child;
1594 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1595 v = view->parent;
1597 wmove(v->window, v->nlines - 1, 0);
1598 wclrtoeol(v->window);
1599 wprintw(v->window, ":%s", view->action);
1600 wrefresh(v->window);
1603 * Clear action status report. Only clear in blame view
1604 * once annotating is complete, otherwise it's too fast.
1606 if (view->type == TOG_VIEW_BLAME) {
1607 if (view->state.blame.blame_complete)
1608 view->action = NULL;
1609 } else
1610 view->action = NULL;
1614 * Read the next line from the test script and assign
1615 * key instruction to *ch. If at EOF, set the *done flag.
1617 static const struct got_error *
1618 tog_read_script_key(FILE *script, struct tog_view *view, int *ch, int *done)
1620 const struct got_error *err = NULL;
1621 char *line = NULL;
1622 size_t linesz = 0;
1624 if (view->count && --view->count) {
1625 *ch = view->ch;
1626 return NULL;
1627 } else
1628 *ch = -1;
1630 if (getline(&line, &linesz, script) == -1) {
1631 if (feof(script)) {
1632 *done = 1;
1633 goto done;
1634 } else {
1635 err = got_ferror(script, GOT_ERR_IO);
1636 goto done;
1640 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1641 tog_io.wait_for_ui = 1;
1642 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1643 *ch = KEY_ENTER;
1644 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1645 *ch = KEY_RIGHT;
1646 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1647 *ch = KEY_LEFT;
1648 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1649 *ch = KEY_DOWN;
1650 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1651 *ch = KEY_UP;
1652 else if (strncasecmp(line, "TAB", 3) == 0)
1653 *ch = '\t';
1654 else if (strncasecmp(line, "SCREENDUMP", 10) == 0)
1655 *ch = TOG_KEY_SCRDUMP;
1656 else if (isdigit((unsigned char)*line)) {
1657 char *t = line;
1659 while (isdigit((unsigned char)*t))
1660 ++t;
1661 view->ch = *ch = *t;
1662 *t = '\0';
1663 /* ignore error, view->count is 0 if instruction is invalid */
1664 view->count = strtonum(line, 0, INT_MAX, NULL);
1665 } else
1666 *ch = *line;
1668 done:
1669 free(line);
1670 return err;
1673 static const struct got_error *
1674 view_input(struct tog_view **new, int *done, struct tog_view *view,
1675 struct tog_view_list_head *views, int fast_refresh)
1677 const struct got_error *err = NULL;
1678 struct tog_view *v;
1679 int ch, errcode;
1681 *new = NULL;
1683 if (view->action)
1684 action_report(view);
1686 /* Clear "no matches" indicator. */
1687 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1688 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1689 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1690 view->count = 0;
1693 if (view->searching && !view->search_next_done) {
1694 errcode = pthread_mutex_unlock(&tog_mutex);
1695 if (errcode)
1696 return got_error_set_errno(errcode,
1697 "pthread_mutex_unlock");
1698 sched_yield();
1699 errcode = pthread_mutex_lock(&tog_mutex);
1700 if (errcode)
1701 return got_error_set_errno(errcode,
1702 "pthread_mutex_lock");
1703 view->search_next(view);
1704 return NULL;
1707 /* Allow threads to make progress while we are waiting for input. */
1708 errcode = pthread_mutex_unlock(&tog_mutex);
1709 if (errcode)
1710 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1712 if (using_mock_io) {
1713 err = tog_read_script_key(tog_io.f, view, &ch, done);
1714 if (err) {
1715 errcode = pthread_mutex_lock(&tog_mutex);
1716 return err;
1718 } else if (view->count && --view->count) {
1719 cbreak();
1720 nodelay(view->window, TRUE);
1721 ch = wgetch(view->window);
1722 /* let C-g or backspace abort unfinished count */
1723 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1724 view->count = 0;
1725 else
1726 ch = view->ch;
1727 } else {
1728 ch = wgetch(view->window);
1729 if (ch >= '1' && ch <= '9')
1730 view->ch = ch = get_compound_key(view, ch);
1732 if (view->hiline && ch != ERR && ch != 0)
1733 view->hiline = 0; /* key pressed, clear line highlight */
1734 nodelay(view->window, TRUE);
1735 errcode = pthread_mutex_lock(&tog_mutex);
1736 if (errcode)
1737 return got_error_set_errno(errcode, "pthread_mutex_lock");
1739 if (tog_sigwinch_received || tog_sigcont_received) {
1740 tog_resizeterm();
1741 tog_sigwinch_received = 0;
1742 tog_sigcont_received = 0;
1743 TAILQ_FOREACH(v, views, entry) {
1744 err = view_resize(v);
1745 if (err)
1746 return err;
1747 err = v->input(new, v, KEY_RESIZE);
1748 if (err)
1749 return err;
1750 if (v->child) {
1751 err = view_resize(v->child);
1752 if (err)
1753 return err;
1754 err = v->child->input(new, v->child,
1755 KEY_RESIZE);
1756 if (err)
1757 return err;
1758 if (v->child->resized_x || v->child->resized_y) {
1759 err = view_resize_split(v, 0);
1760 if (err)
1761 return err;
1767 switch (ch) {
1768 case '?':
1769 case 'H':
1770 case KEY_F(1):
1771 if (view->type == TOG_VIEW_HELP)
1772 err = view->reset(view);
1773 else
1774 err = view_request_new(new, view, TOG_VIEW_HELP);
1775 break;
1776 case '\t':
1777 view->count = 0;
1778 if (view->child) {
1779 view->focussed = 0;
1780 view->child->focussed = 1;
1781 view->focus_child = 1;
1782 } else if (view->parent) {
1783 view->focussed = 0;
1784 view->parent->focussed = 1;
1785 view->parent->focus_child = 0;
1786 if (!view_is_splitscreen(view)) {
1787 if (view->parent->resize) {
1788 err = view->parent->resize(view->parent,
1789 0);
1790 if (err)
1791 return err;
1793 offset_selection_up(view->parent);
1794 err = view_fullscreen(view->parent);
1795 if (err)
1796 return err;
1799 break;
1800 case 'q':
1801 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1802 if (view->parent->resize) {
1803 /* might need more commits to fill fullscreen */
1804 err = view->parent->resize(view->parent, 0);
1805 if (err)
1806 break;
1808 offset_selection_up(view->parent);
1810 err = view->input(new, view, ch);
1811 view->dying = 1;
1812 break;
1813 case 'Q':
1814 *done = 1;
1815 break;
1816 case 'F':
1817 view->count = 0;
1818 if (view_is_parent_view(view)) {
1819 if (view->child == NULL)
1820 break;
1821 if (view_is_splitscreen(view->child)) {
1822 view->focussed = 0;
1823 view->child->focussed = 1;
1824 err = view_fullscreen(view->child);
1825 } else {
1826 err = view_splitscreen(view->child);
1827 if (!err)
1828 err = view_resize_split(view, 0);
1830 if (err)
1831 break;
1832 err = view->child->input(new, view->child,
1833 KEY_RESIZE);
1834 } else {
1835 if (view_is_splitscreen(view)) {
1836 view->parent->focussed = 0;
1837 view->focussed = 1;
1838 err = view_fullscreen(view);
1839 } else {
1840 err = view_splitscreen(view);
1841 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1842 err = view_resize(view->parent);
1843 if (!err)
1844 err = view_resize_split(view, 0);
1846 if (err)
1847 break;
1848 err = view->input(new, view, KEY_RESIZE);
1850 if (err)
1851 break;
1852 if (view->resize) {
1853 err = view->resize(view, 0);
1854 if (err)
1855 break;
1857 if (view->parent) {
1858 if (view->parent->resize) {
1859 err = view->parent->resize(view->parent, 0);
1860 if (err != NULL)
1861 break;
1863 err = offset_selection_down(view->parent);
1864 if (err != NULL)
1865 break;
1867 err = offset_selection_down(view);
1868 break;
1869 case 'S':
1870 view->count = 0;
1871 err = switch_split(view);
1872 break;
1873 case '-':
1874 err = view_resize_split(view, -1);
1875 break;
1876 case '+':
1877 err = view_resize_split(view, 1);
1878 break;
1879 case KEY_RESIZE:
1880 break;
1881 case '/':
1882 view->count = 0;
1883 if (view->search_start)
1884 view_search_start(view, fast_refresh);
1885 else
1886 err = view->input(new, view, ch);
1887 break;
1888 case 'N':
1889 case 'n':
1890 if (view->search_started && view->search_next) {
1891 view->searching = (ch == 'n' ?
1892 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1893 view->search_next_done = 0;
1894 view->search_next(view);
1895 } else
1896 err = view->input(new, view, ch);
1897 break;
1898 case 'A':
1899 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1900 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1901 view->action = "Patience diff algorithm";
1902 } else {
1903 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1904 view->action = "Myers diff algorithm";
1906 TAILQ_FOREACH(v, views, entry) {
1907 if (v->reset) {
1908 err = v->reset(v);
1909 if (err)
1910 return err;
1912 if (v->child && v->child->reset) {
1913 err = v->child->reset(v->child);
1914 if (err)
1915 return err;
1918 break;
1919 case TOG_KEY_SCRDUMP:
1920 err = screendump(view);
1921 break;
1922 default:
1923 err = view->input(new, view, ch);
1924 break;
1927 return err;
1930 static int
1931 view_needs_focus_indication(struct tog_view *view)
1933 if (view_is_parent_view(view)) {
1934 if (view->child == NULL || view->child->focussed)
1935 return 0;
1936 if (!view_is_splitscreen(view->child))
1937 return 0;
1938 } else if (!view_is_splitscreen(view))
1939 return 0;
1941 return view->focussed;
1944 static const struct got_error *
1945 tog_io_close(void)
1947 const struct got_error *err = NULL;
1949 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1950 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1951 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1952 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1953 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1954 err = got_ferror(tog_io.f, GOT_ERR_IO);
1955 if (tog_io.sdump && fclose(tog_io.sdump) == EOF && err == NULL)
1956 err = got_ferror(tog_io.sdump, GOT_ERR_IO);
1958 return err;
1961 static const struct got_error *
1962 view_loop(struct tog_view *view)
1964 const struct got_error *err = NULL;
1965 struct tog_view_list_head views;
1966 struct tog_view *new_view;
1967 char *mode;
1968 int fast_refresh = 10;
1969 int done = 0, errcode;
1971 mode = getenv("TOG_VIEW_SPLIT_MODE");
1972 if (!mode || !(*mode == 'h' || *mode == 'H'))
1973 view->mode = TOG_VIEW_SPLIT_VERT;
1974 else
1975 view->mode = TOG_VIEW_SPLIT_HRZN;
1977 errcode = pthread_mutex_lock(&tog_mutex);
1978 if (errcode)
1979 return got_error_set_errno(errcode, "pthread_mutex_lock");
1981 TAILQ_INIT(&views);
1982 TAILQ_INSERT_HEAD(&views, view, entry);
1984 view->focussed = 1;
1985 err = view->show(view);
1986 if (err)
1987 return err;
1988 update_panels();
1989 doupdate();
1990 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1991 !tog_fatal_signal_received()) {
1992 /* Refresh fast during initialization, then become slower. */
1993 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
1994 halfdelay(10); /* switch to once per second */
1996 err = view_input(&new_view, &done, view, &views, fast_refresh);
1997 if (err)
1998 break;
2000 if (view->dying && view == TAILQ_FIRST(&views) &&
2001 TAILQ_NEXT(view, entry) == NULL)
2002 done = 1;
2003 if (done) {
2004 struct tog_view *v;
2007 * When we quit, scroll the screen up a single line
2008 * so we don't lose any information.
2010 TAILQ_FOREACH(v, &views, entry) {
2011 wmove(v->window, 0, 0);
2012 wdeleteln(v->window);
2013 wnoutrefresh(v->window);
2014 if (v->child && !view_is_fullscreen(v)) {
2015 wmove(v->child->window, 0, 0);
2016 wdeleteln(v->child->window);
2017 wnoutrefresh(v->child->window);
2020 doupdate();
2023 if (view->dying) {
2024 struct tog_view *v, *prev = NULL;
2026 if (view_is_parent_view(view))
2027 prev = TAILQ_PREV(view, tog_view_list_head,
2028 entry);
2029 else if (view->parent)
2030 prev = view->parent;
2032 if (view->parent) {
2033 view->parent->child = NULL;
2034 view->parent->focus_child = 0;
2035 /* Restore fullscreen line height. */
2036 view->parent->nlines = view->parent->lines;
2037 err = view_resize(view->parent);
2038 if (err)
2039 break;
2040 /* Make resized splits persist. */
2041 view_transfer_size(view->parent, view);
2042 } else
2043 TAILQ_REMOVE(&views, view, entry);
2045 err = view_close(view);
2046 if (err)
2047 goto done;
2049 view = NULL;
2050 TAILQ_FOREACH(v, &views, entry) {
2051 if (v->focussed)
2052 break;
2054 if (view == NULL && new_view == NULL) {
2055 /* No view has focus. Try to pick one. */
2056 if (prev)
2057 view = prev;
2058 else if (!TAILQ_EMPTY(&views)) {
2059 view = TAILQ_LAST(&views,
2060 tog_view_list_head);
2062 if (view) {
2063 if (view->focus_child) {
2064 view->child->focussed = 1;
2065 view = view->child;
2066 } else
2067 view->focussed = 1;
2071 if (new_view) {
2072 struct tog_view *v, *t;
2073 /* Only allow one parent view per type. */
2074 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2075 if (v->type != new_view->type)
2076 continue;
2077 TAILQ_REMOVE(&views, v, entry);
2078 err = view_close(v);
2079 if (err)
2080 goto done;
2081 break;
2083 TAILQ_INSERT_TAIL(&views, new_view, entry);
2084 view = new_view;
2086 if (view && !done) {
2087 if (view_is_parent_view(view)) {
2088 if (view->child && view->child->focussed)
2089 view = view->child;
2090 } else {
2091 if (view->parent && view->parent->focussed)
2092 view = view->parent;
2094 show_panel(view->panel);
2095 if (view->child && view_is_splitscreen(view->child))
2096 show_panel(view->child->panel);
2097 if (view->parent && view_is_splitscreen(view)) {
2098 err = view->parent->show(view->parent);
2099 if (err)
2100 goto done;
2102 err = view->show(view);
2103 if (err)
2104 goto done;
2105 if (view->child) {
2106 err = view->child->show(view->child);
2107 if (err)
2108 goto done;
2110 update_panels();
2111 doupdate();
2114 done:
2115 while (!TAILQ_EMPTY(&views)) {
2116 const struct got_error *close_err;
2117 view = TAILQ_FIRST(&views);
2118 TAILQ_REMOVE(&views, view, entry);
2119 close_err = view_close(view);
2120 if (close_err && err == NULL)
2121 err = close_err;
2124 errcode = pthread_mutex_unlock(&tog_mutex);
2125 if (errcode && err == NULL)
2126 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2128 return err;
2131 __dead static void
2132 usage_log(void)
2134 endwin();
2135 fprintf(stderr,
2136 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2137 getprogname());
2138 exit(1);
2141 /* Create newly allocated wide-character string equivalent to a byte string. */
2142 static const struct got_error *
2143 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2145 char *vis = NULL;
2146 const struct got_error *err = NULL;
2148 *ws = NULL;
2149 *wlen = mbstowcs(NULL, s, 0);
2150 if (*wlen == (size_t)-1) {
2151 int vislen;
2152 if (errno != EILSEQ)
2153 return got_error_from_errno("mbstowcs");
2155 /* byte string invalid in current encoding; try to "fix" it */
2156 err = got_mbsavis(&vis, &vislen, s);
2157 if (err)
2158 return err;
2159 *wlen = mbstowcs(NULL, vis, 0);
2160 if (*wlen == (size_t)-1) {
2161 err = got_error_from_errno("mbstowcs"); /* give up */
2162 goto done;
2166 *ws = calloc(*wlen + 1, sizeof(**ws));
2167 if (*ws == NULL) {
2168 err = got_error_from_errno("calloc");
2169 goto done;
2172 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2173 err = got_error_from_errno("mbstowcs");
2174 done:
2175 free(vis);
2176 if (err) {
2177 free(*ws);
2178 *ws = NULL;
2179 *wlen = 0;
2181 return err;
2184 static const struct got_error *
2185 expand_tab(char **ptr, const char *src)
2187 char *dst;
2188 size_t len, n, idx = 0, sz = 0;
2190 *ptr = NULL;
2191 n = len = strlen(src);
2192 dst = malloc(n + 1);
2193 if (dst == NULL)
2194 return got_error_from_errno("malloc");
2196 while (idx < len && src[idx]) {
2197 const char c = src[idx];
2199 if (c == '\t') {
2200 size_t nb = TABSIZE - sz % TABSIZE;
2201 char *p;
2203 p = realloc(dst, n + nb);
2204 if (p == NULL) {
2205 free(dst);
2206 return got_error_from_errno("realloc");
2209 dst = p;
2210 n += nb;
2211 memset(dst + sz, ' ', nb);
2212 sz += nb;
2213 } else
2214 dst[sz++] = src[idx];
2215 ++idx;
2218 dst[sz] = '\0';
2219 *ptr = dst;
2220 return NULL;
2224 * Advance at most n columns from wline starting at offset off.
2225 * Return the index to the first character after the span operation.
2226 * Return the combined column width of all spanned wide characters in
2227 * *rcol.
2229 static int
2230 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2232 int width, i, cols = 0;
2234 if (n == 0) {
2235 *rcol = cols;
2236 return off;
2239 for (i = off; wline[i] != L'\0'; ++i) {
2240 if (wline[i] == L'\t')
2241 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2242 else
2243 width = wcwidth(wline[i]);
2245 if (width == -1) {
2246 width = 1;
2247 wline[i] = L'.';
2250 if (cols + width > n)
2251 break;
2252 cols += width;
2255 *rcol = cols;
2256 return i;
2260 * Format a line for display, ensuring that it won't overflow a width limit.
2261 * With scrolling, the width returned refers to the scrolled version of the
2262 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2264 static const struct got_error *
2265 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2266 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2268 const struct got_error *err = NULL;
2269 int cols;
2270 wchar_t *wline = NULL;
2271 char *exstr = NULL;
2272 size_t wlen;
2273 int i, scrollx;
2275 *wlinep = NULL;
2276 *widthp = 0;
2278 if (expand) {
2279 err = expand_tab(&exstr, line);
2280 if (err)
2281 return err;
2284 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2285 free(exstr);
2286 if (err)
2287 return err;
2289 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2291 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2292 wline[wlen - 1] = L'\0';
2293 wlen--;
2295 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2296 wline[wlen - 1] = L'\0';
2297 wlen--;
2300 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2301 wline[i] = L'\0';
2303 if (widthp)
2304 *widthp = cols;
2305 if (scrollxp)
2306 *scrollxp = scrollx;
2307 if (err)
2308 free(wline);
2309 else
2310 *wlinep = wline;
2311 return err;
2314 static const struct got_error*
2315 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2316 struct got_object_id *id, struct got_repository *repo)
2318 static const struct got_error *err = NULL;
2319 struct got_reflist_entry *re;
2320 char *s;
2321 const char *name;
2323 *refs_str = NULL;
2325 if (refs == NULL)
2326 return NULL;
2328 TAILQ_FOREACH(re, refs, entry) {
2329 struct got_tag_object *tag = NULL;
2330 struct got_object_id *ref_id;
2331 int cmp;
2333 name = got_ref_get_name(re->ref);
2334 if (strcmp(name, GOT_REF_HEAD) == 0)
2335 continue;
2336 if (strncmp(name, "refs/", 5) == 0)
2337 name += 5;
2338 if (strncmp(name, "got/", 4) == 0)
2339 continue;
2340 if (strncmp(name, "heads/", 6) == 0)
2341 name += 6;
2342 if (strncmp(name, "remotes/", 8) == 0) {
2343 name += 8;
2344 s = strstr(name, "/" GOT_REF_HEAD);
2345 if (s != NULL && s[strlen(s)] == '\0')
2346 continue;
2348 err = got_ref_resolve(&ref_id, repo, re->ref);
2349 if (err)
2350 break;
2351 if (strncmp(name, "tags/", 5) == 0) {
2352 err = got_object_open_as_tag(&tag, repo, ref_id);
2353 if (err) {
2354 if (err->code != GOT_ERR_OBJ_TYPE) {
2355 free(ref_id);
2356 break;
2358 /* Ref points at something other than a tag. */
2359 err = NULL;
2360 tag = NULL;
2363 cmp = got_object_id_cmp(tag ?
2364 got_object_tag_get_object_id(tag) : ref_id, id);
2365 free(ref_id);
2366 if (tag)
2367 got_object_tag_close(tag);
2368 if (cmp != 0)
2369 continue;
2370 s = *refs_str;
2371 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2372 s ? ", " : "", name) == -1) {
2373 err = got_error_from_errno("asprintf");
2374 free(s);
2375 *refs_str = NULL;
2376 break;
2378 free(s);
2381 return err;
2384 static const struct got_error *
2385 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2386 int col_tab_align)
2388 char *smallerthan;
2390 smallerthan = strchr(author, '<');
2391 if (smallerthan && smallerthan[1] != '\0')
2392 author = smallerthan + 1;
2393 author[strcspn(author, "@>")] = '\0';
2394 return format_line(wauthor, author_width, NULL, author, 0, limit,
2395 col_tab_align, 0);
2398 static const struct got_error *
2399 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2400 struct got_object_id *id, const size_t date_display_cols,
2401 int author_display_cols)
2403 struct tog_log_view_state *s = &view->state.log;
2404 const struct got_error *err = NULL;
2405 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2406 char *refs_str = NULL;
2407 char *logmsg0 = NULL, *logmsg = NULL;
2408 char *author = NULL;
2409 wchar_t *wrefstr = NULL, *wlogmsg = NULL, *wauthor = NULL;
2410 int author_width, refstr_width, logmsg_width;
2411 char *newline, *line = NULL;
2412 int col, limit, scrollx, logmsg_x;
2413 const int avail = view->ncols;
2414 struct tm tm;
2415 time_t committer_time;
2416 struct tog_color *tc;
2417 struct got_reflist_head *refs;
2419 committer_time = got_object_commit_get_committer_time(commit);
2420 if (gmtime_r(&committer_time, &tm) == NULL)
2421 return got_error_from_errno("gmtime_r");
2422 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2423 return got_error(GOT_ERR_NO_SPACE);
2425 if (avail <= date_display_cols)
2426 limit = MIN(sizeof(datebuf) - 1, avail);
2427 else
2428 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2429 tc = get_color(&s->colors, TOG_COLOR_DATE);
2430 if (tc)
2431 wattr_on(view->window,
2432 COLOR_PAIR(tc->colorpair), NULL);
2433 waddnstr(view->window, datebuf, limit);
2434 if (tc)
2435 wattr_off(view->window,
2436 COLOR_PAIR(tc->colorpair), NULL);
2437 col = limit;
2438 if (col > avail)
2439 goto done;
2441 if (avail >= 120) {
2442 char *id_str;
2443 err = got_object_id_str(&id_str, id);
2444 if (err)
2445 goto done;
2446 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2447 if (tc)
2448 wattr_on(view->window,
2449 COLOR_PAIR(tc->colorpair), NULL);
2450 wprintw(view->window, "%.8s ", id_str);
2451 if (tc)
2452 wattr_off(view->window,
2453 COLOR_PAIR(tc->colorpair), NULL);
2454 free(id_str);
2455 col += 9;
2456 if (col > avail)
2457 goto done;
2460 if (s->use_committer)
2461 author = strdup(got_object_commit_get_committer(commit));
2462 else
2463 author = strdup(got_object_commit_get_author(commit));
2464 if (author == NULL) {
2465 err = got_error_from_errno("strdup");
2466 goto done;
2468 err = format_author(&wauthor, &author_width, author, avail - col, col);
2469 if (err)
2470 goto done;
2471 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2472 if (tc)
2473 wattr_on(view->window,
2474 COLOR_PAIR(tc->colorpair), NULL);
2475 waddwstr(view->window, wauthor);
2476 col += author_width;
2477 while (col < avail && author_width < author_display_cols + 2) {
2478 waddch(view->window, ' ');
2479 col++;
2480 author_width++;
2482 if (tc)
2483 wattr_off(view->window,
2484 COLOR_PAIR(tc->colorpair), NULL);
2485 if (col > avail)
2486 goto done;
2488 err = got_object_commit_get_logmsg(&logmsg0, commit);
2489 if (err)
2490 goto done;
2491 logmsg = logmsg0;
2492 while (*logmsg == '\n')
2493 logmsg++;
2494 newline = strchr(logmsg, '\n');
2495 if (newline)
2496 *newline = '\0';
2498 limit = avail - col;
2499 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2500 limit--; /* for the border */
2502 /* Prepend reference labels to log message if possible .*/
2503 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, id);
2504 err = build_refs_str(&refs_str, refs, id, s->repo);
2505 if (err)
2506 goto done;
2507 if (refs_str) {
2508 char *rs;
2510 if (asprintf(&rs, "[%s]", refs_str) == -1) {
2511 err = got_error_from_errno("asprintf");
2512 goto done;
2514 err = format_line(&wrefstr, &refstr_width,
2515 &scrollx, rs, view->x, limit, col, 1);
2516 free(rs);
2517 if (err)
2518 goto done;
2519 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2520 if (tc)
2521 wattr_on(view->window,
2522 COLOR_PAIR(tc->colorpair), NULL);
2523 waddwstr(view->window, &wrefstr[scrollx]);
2524 if (tc)
2525 wattr_off(view->window,
2526 COLOR_PAIR(tc->colorpair), NULL);
2527 col += MAX(refstr_width, 0);
2528 if (col > avail)
2529 goto done;
2531 if (col < avail) {
2532 waddch(view->window, ' ');
2533 col++;
2536 if (refstr_width > 0)
2537 logmsg_x = 0;
2538 else {
2539 int unscrolled_refstr_width;
2540 size_t len = wcslen(wrefstr);
2543 * No need to check for -1 return value here since
2544 * unprintables have been replaced by span_wline().
2546 unscrolled_refstr_width = wcswidth(wrefstr, len);
2547 unscrolled_refstr_width += 1; /* trailing space */
2548 logmsg_x = view->x - unscrolled_refstr_width;
2551 limit = avail - col;
2552 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2553 limit--; /* for the border */
2554 } else
2555 logmsg_x = view->x;
2557 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, logmsg_x,
2558 limit, col, 1);
2559 if (err)
2560 goto done;
2561 waddwstr(view->window, &wlogmsg[scrollx]);
2562 col += MAX(logmsg_width, 0);
2563 while (col < avail) {
2564 waddch(view->window, ' ');
2565 col++;
2567 done:
2568 free(logmsg0);
2569 free(wlogmsg);
2570 free(wrefstr);
2571 free(refs_str);
2572 free(author);
2573 free(wauthor);
2574 free(line);
2575 return err;
2578 static struct commit_queue_entry *
2579 alloc_commit_queue_entry(struct got_commit_object *commit,
2580 struct got_object_id *id)
2582 struct commit_queue_entry *entry;
2583 struct got_object_id *dup;
2585 entry = calloc(1, sizeof(*entry));
2586 if (entry == NULL)
2587 return NULL;
2589 dup = got_object_id_dup(id);
2590 if (dup == NULL) {
2591 free(entry);
2592 return NULL;
2595 entry->id = dup;
2596 entry->commit = commit;
2597 return entry;
2600 static void
2601 pop_commit(struct commit_queue *commits)
2603 struct commit_queue_entry *entry;
2605 entry = TAILQ_FIRST(&commits->head);
2606 TAILQ_REMOVE(&commits->head, entry, entry);
2607 got_object_commit_close(entry->commit);
2608 commits->ncommits--;
2609 free(entry->id);
2610 free(entry);
2613 static void
2614 free_commits(struct commit_queue *commits)
2616 while (!TAILQ_EMPTY(&commits->head))
2617 pop_commit(commits);
2620 static const struct got_error *
2621 match_commit(int *have_match, struct got_object_id *id,
2622 struct got_commit_object *commit, regex_t *regex)
2624 const struct got_error *err = NULL;
2625 regmatch_t regmatch;
2626 char *id_str = NULL, *logmsg = NULL;
2628 *have_match = 0;
2630 err = got_object_id_str(&id_str, id);
2631 if (err)
2632 return err;
2634 err = got_object_commit_get_logmsg(&logmsg, commit);
2635 if (err)
2636 goto done;
2638 if (regexec(regex, got_object_commit_get_author(commit), 1,
2639 &regmatch, 0) == 0 ||
2640 regexec(regex, got_object_commit_get_committer(commit), 1,
2641 &regmatch, 0) == 0 ||
2642 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2643 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2644 *have_match = 1;
2645 done:
2646 free(id_str);
2647 free(logmsg);
2648 return err;
2651 static const struct got_error *
2652 queue_commits(struct tog_log_thread_args *a)
2654 const struct got_error *err = NULL;
2657 * We keep all commits open throughout the lifetime of the log
2658 * view in order to avoid having to re-fetch commits from disk
2659 * while updating the display.
2661 do {
2662 struct got_object_id id;
2663 struct got_commit_object *commit;
2664 struct commit_queue_entry *entry;
2665 int limit_match = 0;
2666 int errcode;
2668 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2669 NULL, NULL);
2670 if (err)
2671 break;
2673 err = got_object_open_as_commit(&commit, a->repo, &id);
2674 if (err)
2675 break;
2676 entry = alloc_commit_queue_entry(commit, &id);
2677 if (entry == NULL) {
2678 err = got_error_from_errno("alloc_commit_queue_entry");
2679 break;
2682 errcode = pthread_mutex_lock(&tog_mutex);
2683 if (errcode) {
2684 err = got_error_set_errno(errcode,
2685 "pthread_mutex_lock");
2686 break;
2689 entry->idx = a->real_commits->ncommits;
2690 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2691 a->real_commits->ncommits++;
2693 if (*a->limiting) {
2694 err = match_commit(&limit_match, &id, commit,
2695 a->limit_regex);
2696 if (err)
2697 break;
2699 if (limit_match) {
2700 struct commit_queue_entry *matched;
2702 matched = alloc_commit_queue_entry(
2703 entry->commit, entry->id);
2704 if (matched == NULL) {
2705 err = got_error_from_errno(
2706 "alloc_commit_queue_entry");
2707 break;
2709 matched->commit = entry->commit;
2710 got_object_commit_retain(entry->commit);
2712 matched->idx = a->limit_commits->ncommits;
2713 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2714 matched, entry);
2715 a->limit_commits->ncommits++;
2719 * This is how we signal log_thread() that we
2720 * have found a match, and that it should be
2721 * counted as a new entry for the view.
2723 a->limit_match = limit_match;
2726 if (*a->searching == TOG_SEARCH_FORWARD &&
2727 !*a->search_next_done) {
2728 int have_match;
2729 err = match_commit(&have_match, &id, commit, a->regex);
2730 if (err)
2731 break;
2733 if (*a->limiting) {
2734 if (limit_match && have_match)
2735 *a->search_next_done =
2736 TOG_SEARCH_HAVE_MORE;
2737 } else if (have_match)
2738 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2741 errcode = pthread_mutex_unlock(&tog_mutex);
2742 if (errcode && err == NULL)
2743 err = got_error_set_errno(errcode,
2744 "pthread_mutex_unlock");
2745 if (err)
2746 break;
2747 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2749 return err;
2752 static void
2753 select_commit(struct tog_log_view_state *s)
2755 struct commit_queue_entry *entry;
2756 int ncommits = 0;
2758 entry = s->first_displayed_entry;
2759 while (entry) {
2760 if (ncommits == s->selected) {
2761 s->selected_entry = entry;
2762 break;
2764 entry = TAILQ_NEXT(entry, entry);
2765 ncommits++;
2769 static const struct got_error *
2770 draw_commits(struct tog_view *view)
2772 const struct got_error *err = NULL;
2773 struct tog_log_view_state *s = &view->state.log;
2774 struct commit_queue_entry *entry = s->selected_entry;
2775 int limit = view->nlines;
2776 int width;
2777 int ncommits, author_cols = 4, refstr_cols;
2778 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2779 char *refs_str = NULL;
2780 wchar_t *wline;
2781 struct tog_color *tc;
2782 static const size_t date_display_cols = 12;
2783 struct got_reflist_head *refs;
2785 if (view_is_hsplit_top(view))
2786 --limit; /* account for border */
2788 if (s->selected_entry &&
2789 !(view->searching && view->search_next_done == 0)) {
2790 err = got_object_id_str(&id_str, s->selected_entry->id);
2791 if (err)
2792 return err;
2793 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2794 s->selected_entry->id);
2795 err = build_refs_str(&refs_str, refs, s->selected_entry->id,
2796 s->repo);
2797 if (err)
2798 goto done;
2801 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2802 halfdelay(10); /* disable fast refresh */
2804 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2805 if (asprintf(&ncommits_str, " [%d/%d] %s",
2806 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2807 (view->searching && !view->search_next_done) ?
2808 "searching..." : "loading...") == -1) {
2809 err = got_error_from_errno("asprintf");
2810 goto done;
2812 } else {
2813 const char *search_str = NULL;
2814 const char *limit_str = NULL;
2816 if (view->searching) {
2817 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2818 search_str = "no more matches";
2819 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2820 search_str = "no matches found";
2821 else if (!view->search_next_done)
2822 search_str = "searching...";
2825 if (s->limit_view && s->commits->ncommits == 0)
2826 limit_str = "no matches found";
2828 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2829 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2830 search_str ? search_str : (refs_str ? refs_str : ""),
2831 limit_str ? limit_str : "") == -1) {
2832 err = got_error_from_errno("asprintf");
2833 goto done;
2837 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2838 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2839 "........................................",
2840 s->in_repo_path, ncommits_str) == -1) {
2841 err = got_error_from_errno("asprintf");
2842 header = NULL;
2843 goto done;
2845 } else if (asprintf(&header, "commit %s%s",
2846 id_str ? id_str : "........................................",
2847 ncommits_str) == -1) {
2848 err = got_error_from_errno("asprintf");
2849 header = NULL;
2850 goto done;
2852 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2853 if (err)
2854 goto done;
2856 werase(view->window);
2858 if (view_needs_focus_indication(view))
2859 wstandout(view->window);
2860 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2861 if (tc)
2862 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2863 waddwstr(view->window, wline);
2864 while (width < view->ncols) {
2865 waddch(view->window, ' ');
2866 width++;
2868 if (tc)
2869 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2870 if (view_needs_focus_indication(view))
2871 wstandend(view->window);
2872 free(wline);
2873 if (limit <= 1)
2874 goto done;
2876 /* Grow author column size if necessary, and set view->maxx. */
2877 entry = s->first_displayed_entry;
2878 ncommits = 0;
2879 view->maxx = 0;
2880 while (entry) {
2881 struct got_commit_object *c = entry->commit;
2882 char *author, *eol, *msg, *msg0;
2883 wchar_t *wauthor, *wmsg;
2884 int width;
2885 if (ncommits >= limit - 1)
2886 break;
2887 if (s->use_committer)
2888 author = strdup(got_object_commit_get_committer(c));
2889 else
2890 author = strdup(got_object_commit_get_author(c));
2891 if (author == NULL) {
2892 err = got_error_from_errno("strdup");
2893 goto done;
2895 err = format_author(&wauthor, &width, author, COLS,
2896 date_display_cols);
2897 if (author_cols < width)
2898 author_cols = width;
2899 free(wauthor);
2900 free(author);
2901 if (err)
2902 goto done;
2903 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2904 entry->id);
2905 err = build_refs_str(&refs_str, refs, entry->id, s->repo);
2906 if (err)
2907 goto done;
2908 if (refs_str) {
2909 wchar_t *ws;
2910 err = format_line(&ws, &width, NULL, refs_str,
2911 0, INT_MAX, date_display_cols + author_cols, 0);
2912 free(ws);
2913 if (err)
2914 goto done;
2915 refstr_cols = width + 3; /* account for [ ] + space */
2916 } else
2917 refstr_cols = 0;
2918 err = got_object_commit_get_logmsg(&msg0, c);
2919 if (err)
2920 goto done;
2921 msg = msg0;
2922 while (*msg == '\n')
2923 ++msg;
2924 if ((eol = strchr(msg, '\n')))
2925 *eol = '\0';
2926 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2927 date_display_cols + author_cols + refstr_cols, 0);
2928 if (err)
2929 goto done;
2930 view->maxx = MAX(view->maxx, width + refstr_cols);
2931 free(msg0);
2932 free(wmsg);
2933 ncommits++;
2934 entry = TAILQ_NEXT(entry, entry);
2937 entry = s->first_displayed_entry;
2938 s->last_displayed_entry = s->first_displayed_entry;
2939 ncommits = 0;
2940 while (entry) {
2941 if (ncommits >= limit - 1)
2942 break;
2943 if (ncommits == s->selected)
2944 wstandout(view->window);
2945 err = draw_commit(view, entry->commit, entry->id,
2946 date_display_cols, author_cols);
2947 if (ncommits == s->selected)
2948 wstandend(view->window);
2949 if (err)
2950 goto done;
2951 ncommits++;
2952 s->last_displayed_entry = entry;
2953 entry = TAILQ_NEXT(entry, entry);
2956 view_border(view);
2957 done:
2958 free(id_str);
2959 free(refs_str);
2960 free(ncommits_str);
2961 free(header);
2962 return err;
2965 static void
2966 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2968 struct commit_queue_entry *entry;
2969 int nscrolled = 0;
2971 entry = TAILQ_FIRST(&s->commits->head);
2972 if (s->first_displayed_entry == entry)
2973 return;
2975 entry = s->first_displayed_entry;
2976 while (entry && nscrolled < maxscroll) {
2977 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2978 if (entry) {
2979 s->first_displayed_entry = entry;
2980 nscrolled++;
2985 static const struct got_error *
2986 trigger_log_thread(struct tog_view *view, int wait)
2988 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2989 int errcode;
2991 if (!using_mock_io)
2992 halfdelay(1); /* fast refresh while loading commits */
2994 while (!ta->log_complete && !tog_thread_error &&
2995 (ta->commits_needed > 0 || ta->load_all)) {
2996 /* Wake the log thread. */
2997 errcode = pthread_cond_signal(&ta->need_commits);
2998 if (errcode)
2999 return got_error_set_errno(errcode,
3000 "pthread_cond_signal");
3003 * The mutex will be released while the view loop waits
3004 * in wgetch(), at which time the log thread will run.
3006 if (!wait)
3007 break;
3009 /* Display progress update in log view. */
3010 show_log_view(view);
3011 update_panels();
3012 doupdate();
3014 /* Wait right here while next commit is being loaded. */
3015 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
3016 if (errcode)
3017 return got_error_set_errno(errcode,
3018 "pthread_cond_wait");
3020 /* Display progress update in log view. */
3021 show_log_view(view);
3022 update_panels();
3023 doupdate();
3026 return NULL;
3029 static const struct got_error *
3030 request_log_commits(struct tog_view *view)
3032 struct tog_log_view_state *state = &view->state.log;
3033 const struct got_error *err = NULL;
3035 if (state->thread_args.log_complete)
3036 return NULL;
3038 state->thread_args.commits_needed += view->nscrolled;
3039 err = trigger_log_thread(view, 1);
3040 view->nscrolled = 0;
3042 return err;
3045 static const struct got_error *
3046 log_scroll_down(struct tog_view *view, int maxscroll)
3048 struct tog_log_view_state *s = &view->state.log;
3049 const struct got_error *err = NULL;
3050 struct commit_queue_entry *pentry;
3051 int nscrolled = 0, ncommits_needed;
3053 if (s->last_displayed_entry == NULL)
3054 return NULL;
3056 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
3057 if (s->commits->ncommits < ncommits_needed &&
3058 !s->thread_args.log_complete) {
3060 * Ask the log thread for required amount of commits.
3062 s->thread_args.commits_needed +=
3063 ncommits_needed - s->commits->ncommits;
3064 err = trigger_log_thread(view, 1);
3065 if (err)
3066 return err;
3069 do {
3070 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
3071 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
3072 break;
3074 s->last_displayed_entry = pentry ?
3075 pentry : s->last_displayed_entry;
3077 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3078 if (pentry == NULL)
3079 break;
3080 s->first_displayed_entry = pentry;
3081 } while (++nscrolled < maxscroll);
3083 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3084 view->nscrolled += nscrolled;
3085 else
3086 view->nscrolled = 0;
3088 return err;
3091 static const struct got_error *
3092 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3093 struct got_commit_object *commit, struct got_object_id *commit_id,
3094 struct tog_view *log_view, struct got_repository *repo)
3096 const struct got_error *err;
3097 struct got_object_qid *parent_id;
3098 struct tog_view *diff_view;
3100 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3101 if (diff_view == NULL)
3102 return got_error_from_errno("view_open");
3104 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3105 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3106 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3107 if (err == NULL)
3108 *new_view = diff_view;
3109 return err;
3112 static const struct got_error *
3113 tree_view_visit_subtree(struct tog_tree_view_state *s,
3114 struct got_tree_object *subtree)
3116 struct tog_parent_tree *parent;
3118 parent = calloc(1, sizeof(*parent));
3119 if (parent == NULL)
3120 return got_error_from_errno("calloc");
3122 parent->tree = s->tree;
3123 parent->first_displayed_entry = s->first_displayed_entry;
3124 parent->selected_entry = s->selected_entry;
3125 parent->selected = s->selected;
3126 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3127 s->tree = subtree;
3128 s->selected = 0;
3129 s->first_displayed_entry = NULL;
3130 return NULL;
3133 static const struct got_error *
3134 tree_view_walk_path(struct tog_tree_view_state *s,
3135 struct got_commit_object *commit, const char *path)
3137 const struct got_error *err = NULL;
3138 struct got_tree_object *tree = NULL;
3139 const char *p;
3140 char *slash, *subpath = NULL;
3142 /* Walk the path and open corresponding tree objects. */
3143 p = path;
3144 while (*p) {
3145 struct got_tree_entry *te;
3146 struct got_object_id *tree_id;
3147 char *te_name;
3149 while (p[0] == '/')
3150 p++;
3152 /* Ensure the correct subtree entry is selected. */
3153 slash = strchr(p, '/');
3154 if (slash == NULL)
3155 te_name = strdup(p);
3156 else
3157 te_name = strndup(p, slash - p);
3158 if (te_name == NULL) {
3159 err = got_error_from_errno("strndup");
3160 break;
3162 te = got_object_tree_find_entry(s->tree, te_name);
3163 if (te == NULL) {
3164 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3165 free(te_name);
3166 break;
3168 free(te_name);
3169 s->first_displayed_entry = s->selected_entry = te;
3171 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3172 break; /* jump to this file's entry */
3174 slash = strchr(p, '/');
3175 if (slash)
3176 subpath = strndup(path, slash - path);
3177 else
3178 subpath = strdup(path);
3179 if (subpath == NULL) {
3180 err = got_error_from_errno("strdup");
3181 break;
3184 err = got_object_id_by_path(&tree_id, s->repo, commit,
3185 subpath);
3186 if (err)
3187 break;
3189 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3190 free(tree_id);
3191 if (err)
3192 break;
3194 err = tree_view_visit_subtree(s, tree);
3195 if (err) {
3196 got_object_tree_close(tree);
3197 break;
3199 if (slash == NULL)
3200 break;
3201 free(subpath);
3202 subpath = NULL;
3203 p = slash;
3206 free(subpath);
3207 return err;
3210 static const struct got_error *
3211 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3212 struct commit_queue_entry *entry, const char *path,
3213 const char *head_ref_name, struct got_repository *repo)
3215 const struct got_error *err = NULL;
3216 struct tog_tree_view_state *s;
3217 struct tog_view *tree_view;
3219 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3220 if (tree_view == NULL)
3221 return got_error_from_errno("view_open");
3223 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3224 if (err)
3225 return err;
3226 s = &tree_view->state.tree;
3228 *new_view = tree_view;
3230 if (got_path_is_root_dir(path))
3231 return NULL;
3233 return tree_view_walk_path(s, entry->commit, path);
3236 static const struct got_error *
3237 block_signals_used_by_main_thread(void)
3239 sigset_t sigset;
3240 int errcode;
3242 if (sigemptyset(&sigset) == -1)
3243 return got_error_from_errno("sigemptyset");
3245 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3246 if (sigaddset(&sigset, SIGWINCH) == -1)
3247 return got_error_from_errno("sigaddset");
3248 if (sigaddset(&sigset, SIGCONT) == -1)
3249 return got_error_from_errno("sigaddset");
3250 if (sigaddset(&sigset, SIGINT) == -1)
3251 return got_error_from_errno("sigaddset");
3252 if (sigaddset(&sigset, SIGTERM) == -1)
3253 return got_error_from_errno("sigaddset");
3255 /* ncurses handles SIGTSTP */
3256 if (sigaddset(&sigset, SIGTSTP) == -1)
3257 return got_error_from_errno("sigaddset");
3259 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3260 if (errcode)
3261 return got_error_set_errno(errcode, "pthread_sigmask");
3263 return NULL;
3266 static void *
3267 log_thread(void *arg)
3269 const struct got_error *err = NULL;
3270 int errcode = 0;
3271 struct tog_log_thread_args *a = arg;
3272 int done = 0;
3275 * Sync startup with main thread such that we begin our
3276 * work once view_input() has released the mutex.
3278 errcode = pthread_mutex_lock(&tog_mutex);
3279 if (errcode) {
3280 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3281 return (void *)err;
3284 err = block_signals_used_by_main_thread();
3285 if (err) {
3286 pthread_mutex_unlock(&tog_mutex);
3287 goto done;
3290 while (!done && !err && !tog_fatal_signal_received()) {
3291 errcode = pthread_mutex_unlock(&tog_mutex);
3292 if (errcode) {
3293 err = got_error_set_errno(errcode,
3294 "pthread_mutex_unlock");
3295 goto done;
3297 err = queue_commits(a);
3298 if (err) {
3299 if (err->code != GOT_ERR_ITER_COMPLETED)
3300 goto done;
3301 err = NULL;
3302 done = 1;
3303 } else if (a->commits_needed > 0 && !a->load_all) {
3304 if (*a->limiting) {
3305 if (a->limit_match)
3306 a->commits_needed--;
3307 } else
3308 a->commits_needed--;
3311 errcode = pthread_mutex_lock(&tog_mutex);
3312 if (errcode) {
3313 err = got_error_set_errno(errcode,
3314 "pthread_mutex_lock");
3315 goto done;
3316 } else if (*a->quit)
3317 done = 1;
3318 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3319 *a->first_displayed_entry =
3320 TAILQ_FIRST(&a->limit_commits->head);
3321 *a->selected_entry = *a->first_displayed_entry;
3322 } else if (*a->first_displayed_entry == NULL) {
3323 *a->first_displayed_entry =
3324 TAILQ_FIRST(&a->real_commits->head);
3325 *a->selected_entry = *a->first_displayed_entry;
3328 errcode = pthread_cond_signal(&a->commit_loaded);
3329 if (errcode) {
3330 err = got_error_set_errno(errcode,
3331 "pthread_cond_signal");
3332 pthread_mutex_unlock(&tog_mutex);
3333 goto done;
3336 if (done)
3337 a->commits_needed = 0;
3338 else {
3339 if (a->commits_needed == 0 && !a->load_all) {
3340 errcode = pthread_cond_wait(&a->need_commits,
3341 &tog_mutex);
3342 if (errcode) {
3343 err = got_error_set_errno(errcode,
3344 "pthread_cond_wait");
3345 pthread_mutex_unlock(&tog_mutex);
3346 goto done;
3348 if (*a->quit)
3349 done = 1;
3353 a->log_complete = 1;
3354 errcode = pthread_mutex_unlock(&tog_mutex);
3355 if (errcode)
3356 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3357 done:
3358 if (err) {
3359 tog_thread_error = 1;
3360 pthread_cond_signal(&a->commit_loaded);
3362 return (void *)err;
3365 static const struct got_error *
3366 stop_log_thread(struct tog_log_view_state *s)
3368 const struct got_error *err = NULL, *thread_err = NULL;
3369 int errcode;
3371 if (s->thread) {
3372 s->quit = 1;
3373 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3374 if (errcode)
3375 return got_error_set_errno(errcode,
3376 "pthread_cond_signal");
3377 errcode = pthread_mutex_unlock(&tog_mutex);
3378 if (errcode)
3379 return got_error_set_errno(errcode,
3380 "pthread_mutex_unlock");
3381 errcode = pthread_join(s->thread, (void **)&thread_err);
3382 if (errcode)
3383 return got_error_set_errno(errcode, "pthread_join");
3384 errcode = pthread_mutex_lock(&tog_mutex);
3385 if (errcode)
3386 return got_error_set_errno(errcode,
3387 "pthread_mutex_lock");
3388 s->thread = NULL;
3391 if (s->thread_args.repo) {
3392 err = got_repo_close(s->thread_args.repo);
3393 s->thread_args.repo = NULL;
3396 if (s->thread_args.pack_fds) {
3397 const struct got_error *pack_err =
3398 got_repo_pack_fds_close(s->thread_args.pack_fds);
3399 if (err == NULL)
3400 err = pack_err;
3401 s->thread_args.pack_fds = NULL;
3404 if (s->thread_args.graph) {
3405 got_commit_graph_close(s->thread_args.graph);
3406 s->thread_args.graph = NULL;
3409 return err ? err : thread_err;
3412 static const struct got_error *
3413 close_log_view(struct tog_view *view)
3415 const struct got_error *err = NULL;
3416 struct tog_log_view_state *s = &view->state.log;
3417 int errcode;
3419 err = stop_log_thread(s);
3421 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3422 if (errcode && err == NULL)
3423 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3425 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3426 if (errcode && err == NULL)
3427 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3429 free_commits(&s->limit_commits);
3430 free_commits(&s->real_commits);
3431 free(s->in_repo_path);
3432 s->in_repo_path = NULL;
3433 free(s->start_id);
3434 s->start_id = NULL;
3435 free(s->head_ref_name);
3436 s->head_ref_name = NULL;
3437 return err;
3441 * We use two queues to implement the limit feature: first consists of
3442 * commits matching the current limit_regex; second is the real queue
3443 * of all known commits (real_commits). When the user starts limiting,
3444 * we swap queues such that all movement and displaying functionality
3445 * works with very slight change.
3447 static const struct got_error *
3448 limit_log_view(struct tog_view *view)
3450 struct tog_log_view_state *s = &view->state.log;
3451 struct commit_queue_entry *entry;
3452 struct tog_view *v = view;
3453 const struct got_error *err = NULL;
3454 char pattern[1024];
3455 int ret;
3457 if (view_is_hsplit_top(view))
3458 v = view->child;
3459 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3460 v = view->parent;
3462 /* Get the pattern */
3463 wmove(v->window, v->nlines - 1, 0);
3464 wclrtoeol(v->window);
3465 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3466 nodelay(v->window, FALSE);
3467 nocbreak();
3468 echo();
3469 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3470 cbreak();
3471 noecho();
3472 nodelay(v->window, TRUE);
3473 if (ret == ERR)
3474 return NULL;
3476 if (*pattern == '\0') {
3478 * Safety measure for the situation where the user
3479 * resets limit without previously limiting anything.
3481 if (!s->limit_view)
3482 return NULL;
3485 * User could have pressed Ctrl+L, which refreshed the
3486 * commit queues, it means we can't save previously
3487 * (before limit took place) displayed entries,
3488 * because they would point to already free'ed memory,
3489 * so we are forced to always select first entry of
3490 * the queue.
3492 s->commits = &s->real_commits;
3493 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3494 s->selected_entry = s->first_displayed_entry;
3495 s->selected = 0;
3496 s->limit_view = 0;
3498 return NULL;
3501 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3502 return NULL;
3504 s->limit_view = 1;
3506 /* Clear the screen while loading limit view */
3507 s->first_displayed_entry = NULL;
3508 s->last_displayed_entry = NULL;
3509 s->selected_entry = NULL;
3510 s->commits = &s->limit_commits;
3512 /* Prepare limit queue for new search */
3513 free_commits(&s->limit_commits);
3514 s->limit_commits.ncommits = 0;
3516 /* First process commits, which are in queue already */
3517 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3518 int have_match = 0;
3520 err = match_commit(&have_match, entry->id,
3521 entry->commit, &s->limit_regex);
3522 if (err)
3523 return err;
3525 if (have_match) {
3526 struct commit_queue_entry *matched;
3528 matched = alloc_commit_queue_entry(entry->commit,
3529 entry->id);
3530 if (matched == NULL) {
3531 err = got_error_from_errno(
3532 "alloc_commit_queue_entry");
3533 break;
3535 matched->commit = entry->commit;
3536 got_object_commit_retain(entry->commit);
3538 matched->idx = s->limit_commits.ncommits;
3539 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3540 matched, entry);
3541 s->limit_commits.ncommits++;
3545 /* Second process all the commits, until we fill the screen */
3546 if (s->limit_commits.ncommits < view->nlines - 1 &&
3547 !s->thread_args.log_complete) {
3548 s->thread_args.commits_needed +=
3549 view->nlines - s->limit_commits.ncommits - 1;
3550 err = trigger_log_thread(view, 1);
3551 if (err)
3552 return err;
3555 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3556 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3557 s->selected = 0;
3559 return NULL;
3562 static const struct got_error *
3563 search_start_log_view(struct tog_view *view)
3565 struct tog_log_view_state *s = &view->state.log;
3567 s->matched_entry = NULL;
3568 s->search_entry = NULL;
3569 return NULL;
3572 static const struct got_error *
3573 search_next_log_view(struct tog_view *view)
3575 const struct got_error *err = NULL;
3576 struct tog_log_view_state *s = &view->state.log;
3577 struct commit_queue_entry *entry;
3579 /* Display progress update in log view. */
3580 show_log_view(view);
3581 update_panels();
3582 doupdate();
3584 if (s->search_entry) {
3585 int errcode, ch;
3586 errcode = pthread_mutex_unlock(&tog_mutex);
3587 if (errcode)
3588 return got_error_set_errno(errcode,
3589 "pthread_mutex_unlock");
3590 ch = wgetch(view->window);
3591 errcode = pthread_mutex_lock(&tog_mutex);
3592 if (errcode)
3593 return got_error_set_errno(errcode,
3594 "pthread_mutex_lock");
3595 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3596 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3597 return NULL;
3599 if (view->searching == TOG_SEARCH_FORWARD)
3600 entry = TAILQ_NEXT(s->search_entry, entry);
3601 else
3602 entry = TAILQ_PREV(s->search_entry,
3603 commit_queue_head, entry);
3604 } else if (s->matched_entry) {
3606 * If the user has moved the cursor after we hit a match,
3607 * the position from where we should continue searching
3608 * might have changed.
3610 if (view->searching == TOG_SEARCH_FORWARD)
3611 entry = TAILQ_NEXT(s->selected_entry, entry);
3612 else
3613 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3614 entry);
3615 } else {
3616 entry = s->selected_entry;
3619 while (1) {
3620 int have_match = 0;
3622 if (entry == NULL) {
3623 if (s->thread_args.log_complete ||
3624 view->searching == TOG_SEARCH_BACKWARD) {
3625 view->search_next_done =
3626 (s->matched_entry == NULL ?
3627 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3628 s->search_entry = NULL;
3629 return NULL;
3632 * Poke the log thread for more commits and return,
3633 * allowing the main loop to make progress. Search
3634 * will resume at s->search_entry once we come back.
3636 s->thread_args.commits_needed++;
3637 return trigger_log_thread(view, 0);
3640 err = match_commit(&have_match, entry->id, entry->commit,
3641 &view->regex);
3642 if (err)
3643 break;
3644 if (have_match) {
3645 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3646 s->matched_entry = entry;
3647 break;
3650 s->search_entry = entry;
3651 if (view->searching == TOG_SEARCH_FORWARD)
3652 entry = TAILQ_NEXT(entry, entry);
3653 else
3654 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3657 if (s->matched_entry) {
3658 int cur = s->selected_entry->idx;
3659 while (cur < s->matched_entry->idx) {
3660 err = input_log_view(NULL, view, KEY_DOWN);
3661 if (err)
3662 return err;
3663 cur++;
3665 while (cur > s->matched_entry->idx) {
3666 err = input_log_view(NULL, view, KEY_UP);
3667 if (err)
3668 return err;
3669 cur--;
3673 s->search_entry = NULL;
3675 return NULL;
3678 static const struct got_error *
3679 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3680 struct got_repository *repo, const char *head_ref_name,
3681 const char *in_repo_path, int log_branches)
3683 const struct got_error *err = NULL;
3684 struct tog_log_view_state *s = &view->state.log;
3685 struct got_repository *thread_repo = NULL;
3686 struct got_commit_graph *thread_graph = NULL;
3687 int errcode;
3689 if (in_repo_path != s->in_repo_path) {
3690 free(s->in_repo_path);
3691 s->in_repo_path = strdup(in_repo_path);
3692 if (s->in_repo_path == NULL) {
3693 err = got_error_from_errno("strdup");
3694 goto done;
3698 /* The commit queue only contains commits being displayed. */
3699 TAILQ_INIT(&s->real_commits.head);
3700 s->real_commits.ncommits = 0;
3701 s->commits = &s->real_commits;
3703 TAILQ_INIT(&s->limit_commits.head);
3704 s->limit_view = 0;
3705 s->limit_commits.ncommits = 0;
3707 s->repo = repo;
3708 if (head_ref_name) {
3709 s->head_ref_name = strdup(head_ref_name);
3710 if (s->head_ref_name == NULL) {
3711 err = got_error_from_errno("strdup");
3712 goto done;
3715 s->start_id = got_object_id_dup(start_id);
3716 if (s->start_id == NULL) {
3717 err = got_error_from_errno("got_object_id_dup");
3718 goto done;
3720 s->log_branches = log_branches;
3721 s->use_committer = 1;
3723 STAILQ_INIT(&s->colors);
3724 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3725 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3726 get_color_value("TOG_COLOR_COMMIT"));
3727 if (err)
3728 goto done;
3729 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3730 get_color_value("TOG_COLOR_AUTHOR"));
3731 if (err) {
3732 free_colors(&s->colors);
3733 goto done;
3735 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3736 get_color_value("TOG_COLOR_DATE"));
3737 if (err) {
3738 free_colors(&s->colors);
3739 goto done;
3743 view->show = show_log_view;
3744 view->input = input_log_view;
3745 view->resize = resize_log_view;
3746 view->close = close_log_view;
3747 view->search_start = search_start_log_view;
3748 view->search_next = search_next_log_view;
3750 if (s->thread_args.pack_fds == NULL) {
3751 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3752 if (err)
3753 goto done;
3755 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3756 s->thread_args.pack_fds);
3757 if (err)
3758 goto done;
3759 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3760 !s->log_branches);
3761 if (err)
3762 goto done;
3763 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3764 s->repo, NULL, NULL);
3765 if (err)
3766 goto done;
3768 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3769 if (errcode) {
3770 err = got_error_set_errno(errcode, "pthread_cond_init");
3771 goto done;
3773 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3774 if (errcode) {
3775 err = got_error_set_errno(errcode, "pthread_cond_init");
3776 goto done;
3779 s->thread_args.commits_needed = view->nlines;
3780 s->thread_args.graph = thread_graph;
3781 s->thread_args.real_commits = &s->real_commits;
3782 s->thread_args.limit_commits = &s->limit_commits;
3783 s->thread_args.in_repo_path = s->in_repo_path;
3784 s->thread_args.start_id = s->start_id;
3785 s->thread_args.repo = thread_repo;
3786 s->thread_args.log_complete = 0;
3787 s->thread_args.quit = &s->quit;
3788 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3789 s->thread_args.selected_entry = &s->selected_entry;
3790 s->thread_args.searching = &view->searching;
3791 s->thread_args.search_next_done = &view->search_next_done;
3792 s->thread_args.regex = &view->regex;
3793 s->thread_args.limiting = &s->limit_view;
3794 s->thread_args.limit_regex = &s->limit_regex;
3795 s->thread_args.limit_commits = &s->limit_commits;
3796 done:
3797 if (err) {
3798 if (view->close == NULL)
3799 close_log_view(view);
3800 view_close(view);
3802 return err;
3805 static const struct got_error *
3806 show_log_view(struct tog_view *view)
3808 const struct got_error *err;
3809 struct tog_log_view_state *s = &view->state.log;
3811 if (s->thread == NULL) {
3812 int errcode = pthread_create(&s->thread, NULL, log_thread,
3813 &s->thread_args);
3814 if (errcode)
3815 return got_error_set_errno(errcode, "pthread_create");
3816 if (s->thread_args.commits_needed > 0) {
3817 err = trigger_log_thread(view, 1);
3818 if (err)
3819 return err;
3823 return draw_commits(view);
3826 static void
3827 log_move_cursor_up(struct tog_view *view, int page, int home)
3829 struct tog_log_view_state *s = &view->state.log;
3831 if (s->first_displayed_entry == NULL)
3832 return;
3833 if (s->selected_entry->idx == 0)
3834 view->count = 0;
3836 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3837 || home)
3838 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3840 if (!page && !home && s->selected > 0)
3841 --s->selected;
3842 else
3843 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3845 select_commit(s);
3846 return;
3849 static const struct got_error *
3850 log_move_cursor_down(struct tog_view *view, int page)
3852 struct tog_log_view_state *s = &view->state.log;
3853 const struct got_error *err = NULL;
3854 int eos = view->nlines - 2;
3856 if (s->first_displayed_entry == NULL)
3857 return NULL;
3859 if (s->thread_args.log_complete &&
3860 s->selected_entry->idx >= s->commits->ncommits - 1)
3861 return NULL;
3863 if (view_is_hsplit_top(view))
3864 --eos; /* border consumes the last line */
3866 if (!page) {
3867 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3868 ++s->selected;
3869 else
3870 err = log_scroll_down(view, 1);
3871 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3872 struct commit_queue_entry *entry;
3873 int n;
3875 s->selected = 0;
3876 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3877 s->last_displayed_entry = entry;
3878 for (n = 0; n <= eos; n++) {
3879 if (entry == NULL)
3880 break;
3881 s->first_displayed_entry = entry;
3882 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3884 if (n > 0)
3885 s->selected = n - 1;
3886 } else {
3887 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3888 s->thread_args.log_complete)
3889 s->selected += MIN(page,
3890 s->commits->ncommits - s->selected_entry->idx - 1);
3891 else
3892 err = log_scroll_down(view, page);
3894 if (err)
3895 return err;
3898 * We might necessarily overshoot in horizontal
3899 * splits; if so, select the last displayed commit.
3901 if (s->first_displayed_entry && s->last_displayed_entry) {
3902 s->selected = MIN(s->selected,
3903 s->last_displayed_entry->idx -
3904 s->first_displayed_entry->idx);
3907 select_commit(s);
3909 if (s->thread_args.log_complete &&
3910 s->selected_entry->idx == s->commits->ncommits - 1)
3911 view->count = 0;
3913 return NULL;
3916 static void
3917 view_get_split(struct tog_view *view, int *y, int *x)
3919 *x = 0;
3920 *y = 0;
3922 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3923 if (view->child && view->child->resized_y)
3924 *y = view->child->resized_y;
3925 else if (view->resized_y)
3926 *y = view->resized_y;
3927 else
3928 *y = view_split_begin_y(view->lines);
3929 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3930 if (view->child && view->child->resized_x)
3931 *x = view->child->resized_x;
3932 else if (view->resized_x)
3933 *x = view->resized_x;
3934 else
3935 *x = view_split_begin_x(view->begin_x);
3939 /* Split view horizontally at y and offset view->state->selected line. */
3940 static const struct got_error *
3941 view_init_hsplit(struct tog_view *view, int y)
3943 const struct got_error *err = NULL;
3945 view->nlines = y;
3946 view->ncols = COLS;
3947 err = view_resize(view);
3948 if (err)
3949 return err;
3951 err = offset_selection_down(view);
3953 return err;
3956 static const struct got_error *
3957 log_goto_line(struct tog_view *view, int nlines)
3959 const struct got_error *err = NULL;
3960 struct tog_log_view_state *s = &view->state.log;
3961 int g, idx = s->selected_entry->idx;
3963 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3964 return NULL;
3966 g = view->gline;
3967 view->gline = 0;
3969 if (g >= s->first_displayed_entry->idx + 1 &&
3970 g <= s->last_displayed_entry->idx + 1 &&
3971 g - s->first_displayed_entry->idx - 1 < nlines) {
3972 s->selected = g - s->first_displayed_entry->idx - 1;
3973 select_commit(s);
3974 return NULL;
3977 if (idx + 1 < g) {
3978 err = log_move_cursor_down(view, g - idx - 1);
3979 if (!err && g > s->selected_entry->idx + 1)
3980 err = log_move_cursor_down(view,
3981 g - s->first_displayed_entry->idx - 1);
3982 if (err)
3983 return err;
3984 } else if (idx + 1 > g)
3985 log_move_cursor_up(view, idx - g + 1, 0);
3987 if (g < nlines && s->first_displayed_entry->idx == 0)
3988 s->selected = g - 1;
3990 select_commit(s);
3991 return NULL;
3995 static void
3996 horizontal_scroll_input(struct tog_view *view, int ch)
3999 switch (ch) {
4000 case KEY_LEFT:
4001 case 'h':
4002 view->x -= MIN(view->x, 2);
4003 if (view->x <= 0)
4004 view->count = 0;
4005 break;
4006 case KEY_RIGHT:
4007 case 'l':
4008 if (view->x + view->ncols / 2 < view->maxx)
4009 view->x += 2;
4010 else
4011 view->count = 0;
4012 break;
4013 case '0':
4014 view->x = 0;
4015 break;
4016 case '$':
4017 view->x = MAX(view->maxx - view->ncols / 2, 0);
4018 view->count = 0;
4019 break;
4020 default:
4021 break;
4025 static const struct got_error *
4026 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
4028 const struct got_error *err = NULL;
4029 struct tog_log_view_state *s = &view->state.log;
4030 int eos, nscroll;
4032 if (s->thread_args.load_all) {
4033 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
4034 s->thread_args.load_all = 0;
4035 else if (s->thread_args.log_complete) {
4036 err = log_move_cursor_down(view, s->commits->ncommits);
4037 s->thread_args.load_all = 0;
4039 if (err)
4040 return err;
4043 eos = nscroll = view->nlines - 1;
4044 if (view_is_hsplit_top(view))
4045 --eos; /* border */
4047 if (view->gline)
4048 return log_goto_line(view, eos);
4050 switch (ch) {
4051 case '&':
4052 err = limit_log_view(view);
4053 break;
4054 case 'q':
4055 s->quit = 1;
4056 break;
4057 case '0':
4058 case '$':
4059 case KEY_RIGHT:
4060 case 'l':
4061 case KEY_LEFT:
4062 case 'h':
4063 horizontal_scroll_input(view, ch);
4064 break;
4065 case 'k':
4066 case KEY_UP:
4067 case '<':
4068 case ',':
4069 case CTRL('p'):
4070 log_move_cursor_up(view, 0, 0);
4071 break;
4072 case 'g':
4073 case '=':
4074 case KEY_HOME:
4075 log_move_cursor_up(view, 0, 1);
4076 view->count = 0;
4077 break;
4078 case CTRL('u'):
4079 case 'u':
4080 nscroll /= 2;
4081 /* FALL THROUGH */
4082 case KEY_PPAGE:
4083 case CTRL('b'):
4084 case 'b':
4085 log_move_cursor_up(view, nscroll, 0);
4086 break;
4087 case 'j':
4088 case KEY_DOWN:
4089 case '>':
4090 case '.':
4091 case CTRL('n'):
4092 err = log_move_cursor_down(view, 0);
4093 break;
4094 case '@':
4095 s->use_committer = !s->use_committer;
4096 view->action = s->use_committer ?
4097 "show committer" : "show commit author";
4098 break;
4099 case 'G':
4100 case '*':
4101 case KEY_END: {
4102 /* We don't know yet how many commits, so we're forced to
4103 * traverse them all. */
4104 view->count = 0;
4105 s->thread_args.load_all = 1;
4106 if (!s->thread_args.log_complete)
4107 return trigger_log_thread(view, 0);
4108 err = log_move_cursor_down(view, s->commits->ncommits);
4109 s->thread_args.load_all = 0;
4110 break;
4112 case CTRL('d'):
4113 case 'd':
4114 nscroll /= 2;
4115 /* FALL THROUGH */
4116 case KEY_NPAGE:
4117 case CTRL('f'):
4118 case 'f':
4119 case ' ':
4120 err = log_move_cursor_down(view, nscroll);
4121 break;
4122 case KEY_RESIZE:
4123 if (s->selected > view->nlines - 2)
4124 s->selected = view->nlines - 2;
4125 if (s->selected > s->commits->ncommits - 1)
4126 s->selected = s->commits->ncommits - 1;
4127 select_commit(s);
4128 if (s->commits->ncommits < view->nlines - 1 &&
4129 !s->thread_args.log_complete) {
4130 s->thread_args.commits_needed += (view->nlines - 1) -
4131 s->commits->ncommits;
4132 err = trigger_log_thread(view, 1);
4134 break;
4135 case KEY_ENTER:
4136 case '\r':
4137 view->count = 0;
4138 if (s->selected_entry == NULL)
4139 break;
4140 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4141 break;
4142 case 'T':
4143 view->count = 0;
4144 if (s->selected_entry == NULL)
4145 break;
4146 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4147 break;
4148 case KEY_BACKSPACE:
4149 case CTRL('l'):
4150 case 'B':
4151 view->count = 0;
4152 if (ch == KEY_BACKSPACE &&
4153 got_path_is_root_dir(s->in_repo_path))
4154 break;
4155 err = stop_log_thread(s);
4156 if (err)
4157 return err;
4158 if (ch == KEY_BACKSPACE) {
4159 char *parent_path;
4160 err = got_path_dirname(&parent_path, s->in_repo_path);
4161 if (err)
4162 return err;
4163 free(s->in_repo_path);
4164 s->in_repo_path = parent_path;
4165 s->thread_args.in_repo_path = s->in_repo_path;
4166 } else if (ch == CTRL('l')) {
4167 struct got_object_id *start_id;
4168 err = got_repo_match_object_id(&start_id, NULL,
4169 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4170 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4171 if (err) {
4172 if (s->head_ref_name == NULL ||
4173 err->code != GOT_ERR_NOT_REF)
4174 return err;
4175 /* Try to cope with deleted references. */
4176 free(s->head_ref_name);
4177 s->head_ref_name = NULL;
4178 err = got_repo_match_object_id(&start_id,
4179 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4180 &tog_refs, s->repo);
4181 if (err)
4182 return err;
4184 free(s->start_id);
4185 s->start_id = start_id;
4186 s->thread_args.start_id = s->start_id;
4187 } else /* 'B' */
4188 s->log_branches = !s->log_branches;
4190 if (s->thread_args.pack_fds == NULL) {
4191 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4192 if (err)
4193 return err;
4195 err = got_repo_open(&s->thread_args.repo,
4196 got_repo_get_path(s->repo), NULL,
4197 s->thread_args.pack_fds);
4198 if (err)
4199 return err;
4200 tog_free_refs();
4201 err = tog_load_refs(s->repo, 0);
4202 if (err)
4203 return err;
4204 err = got_commit_graph_open(&s->thread_args.graph,
4205 s->in_repo_path, !s->log_branches);
4206 if (err)
4207 return err;
4208 err = got_commit_graph_iter_start(s->thread_args.graph,
4209 s->start_id, s->repo, NULL, NULL);
4210 if (err)
4211 return err;
4212 free_commits(&s->real_commits);
4213 free_commits(&s->limit_commits);
4214 s->first_displayed_entry = NULL;
4215 s->last_displayed_entry = NULL;
4216 s->selected_entry = NULL;
4217 s->selected = 0;
4218 s->thread_args.log_complete = 0;
4219 s->quit = 0;
4220 s->thread_args.commits_needed = view->lines;
4221 s->matched_entry = NULL;
4222 s->search_entry = NULL;
4223 view->offset = 0;
4224 break;
4225 case 'R':
4226 view->count = 0;
4227 err = view_request_new(new_view, view, TOG_VIEW_REF);
4228 break;
4229 default:
4230 view->count = 0;
4231 break;
4234 return err;
4237 static const struct got_error *
4238 apply_unveil(const char *repo_path, const char *worktree_path)
4240 const struct got_error *error;
4242 #ifdef PROFILE
4243 if (unveil("gmon.out", "rwc") != 0)
4244 return got_error_from_errno2("unveil", "gmon.out");
4245 #endif
4246 if (repo_path && unveil(repo_path, "r") != 0)
4247 return got_error_from_errno2("unveil", repo_path);
4249 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4250 return got_error_from_errno2("unveil", worktree_path);
4252 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4253 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4255 error = got_privsep_unveil_exec_helpers();
4256 if (error != NULL)
4257 return error;
4259 if (unveil(NULL, NULL) != 0)
4260 return got_error_from_errno("unveil");
4262 return NULL;
4265 static const struct got_error *
4266 init_mock_term(const char *test_script_path)
4268 const struct got_error *err = NULL;
4269 const char *screen_dump_path;
4270 int in;
4272 if (test_script_path == NULL || *test_script_path == '\0')
4273 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4275 tog_io.f = fopen(test_script_path, "re");
4276 if (tog_io.f == NULL) {
4277 err = got_error_from_errno_fmt("fopen: %s",
4278 test_script_path);
4279 goto done;
4282 /* test mode, we don't want any output */
4283 tog_io.cout = fopen("/dev/null", "w+");
4284 if (tog_io.cout == NULL) {
4285 err = got_error_from_errno2("fopen", "/dev/null");
4286 goto done;
4289 in = dup(fileno(tog_io.cout));
4290 if (in == -1) {
4291 err = got_error_from_errno("dup");
4292 goto done;
4294 tog_io.cin = fdopen(in, "r");
4295 if (tog_io.cin == NULL) {
4296 err = got_error_from_errno("fdopen");
4297 close(in);
4298 goto done;
4301 screen_dump_path = getenv("TOG_SCR_DUMP");
4302 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4303 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4304 tog_io.sdump = fopen(screen_dump_path, "wex");
4305 if (tog_io.sdump == NULL) {
4306 err = got_error_from_errno2("fopen", screen_dump_path);
4307 goto done;
4310 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4311 err = got_error_from_errno("fseeko");
4312 goto done;
4315 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4316 err = got_error_msg(GOT_ERR_IO,
4317 "newterm: failed to initialise curses");
4319 using_mock_io = 1;
4321 done:
4322 if (err)
4323 tog_io_close();
4324 return err;
4327 static void
4328 init_curses(void)
4331 * Override default signal handlers before starting ncurses.
4332 * This should prevent ncurses from installing its own
4333 * broken cleanup() signal handler.
4335 signal(SIGWINCH, tog_sigwinch);
4336 signal(SIGPIPE, tog_sigpipe);
4337 signal(SIGCONT, tog_sigcont);
4338 signal(SIGINT, tog_sigint);
4339 signal(SIGTERM, tog_sigterm);
4341 if (using_mock_io) /* In test mode we use a fake terminal */
4342 return;
4344 initscr();
4346 cbreak();
4347 halfdelay(1); /* Fast refresh while initial view is loading. */
4348 noecho();
4349 nonl();
4350 intrflush(stdscr, FALSE);
4351 keypad(stdscr, TRUE);
4352 curs_set(0);
4353 if (getenv("TOG_COLORS") != NULL) {
4354 start_color();
4355 use_default_colors();
4358 return;
4361 static const struct got_error *
4362 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4363 struct got_repository *repo, struct got_worktree *worktree)
4365 const struct got_error *err = NULL;
4367 if (argc == 0) {
4368 *in_repo_path = strdup("/");
4369 if (*in_repo_path == NULL)
4370 return got_error_from_errno("strdup");
4371 return NULL;
4374 if (worktree) {
4375 const char *prefix = got_worktree_get_path_prefix(worktree);
4376 char *p;
4378 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4379 if (err)
4380 return err;
4381 if (asprintf(in_repo_path, "%s%s%s", prefix,
4382 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4383 p) == -1) {
4384 err = got_error_from_errno("asprintf");
4385 *in_repo_path = NULL;
4387 free(p);
4388 } else
4389 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4391 return err;
4394 static const struct got_error *
4395 cmd_log(int argc, char *argv[])
4397 const struct got_error *error;
4398 struct got_repository *repo = NULL;
4399 struct got_worktree *worktree = NULL;
4400 struct got_object_id *start_id = NULL;
4401 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4402 char *start_commit = NULL, *label = NULL;
4403 struct got_reference *ref = NULL;
4404 const char *head_ref_name = NULL;
4405 int ch, log_branches = 0;
4406 struct tog_view *view;
4407 int *pack_fds = NULL;
4409 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4410 switch (ch) {
4411 case 'b':
4412 log_branches = 1;
4413 break;
4414 case 'c':
4415 start_commit = optarg;
4416 break;
4417 case 'r':
4418 repo_path = realpath(optarg, NULL);
4419 if (repo_path == NULL)
4420 return got_error_from_errno2("realpath",
4421 optarg);
4422 break;
4423 default:
4424 usage_log();
4425 /* NOTREACHED */
4429 argc -= optind;
4430 argv += optind;
4432 if (argc > 1)
4433 usage_log();
4435 error = got_repo_pack_fds_open(&pack_fds);
4436 if (error != NULL)
4437 goto done;
4439 if (repo_path == NULL) {
4440 cwd = getcwd(NULL, 0);
4441 if (cwd == NULL)
4442 return got_error_from_errno("getcwd");
4443 error = got_worktree_open(&worktree, cwd);
4444 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4445 goto done;
4446 if (worktree)
4447 repo_path =
4448 strdup(got_worktree_get_repo_path(worktree));
4449 else
4450 repo_path = strdup(cwd);
4451 if (repo_path == NULL) {
4452 error = got_error_from_errno("strdup");
4453 goto done;
4457 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4458 if (error != NULL)
4459 goto done;
4461 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4462 repo, worktree);
4463 if (error)
4464 goto done;
4466 init_curses();
4468 error = apply_unveil(got_repo_get_path(repo),
4469 worktree ? got_worktree_get_root_path(worktree) : NULL);
4470 if (error)
4471 goto done;
4473 /* already loaded by tog_log_with_path()? */
4474 if (TAILQ_EMPTY(&tog_refs)) {
4475 error = tog_load_refs(repo, 0);
4476 if (error)
4477 goto done;
4480 if (start_commit == NULL) {
4481 error = got_repo_match_object_id(&start_id, &label,
4482 worktree ? got_worktree_get_head_ref_name(worktree) :
4483 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4484 if (error)
4485 goto done;
4486 head_ref_name = label;
4487 } else {
4488 error = got_ref_open(&ref, repo, start_commit, 0);
4489 if (error == NULL)
4490 head_ref_name = got_ref_get_name(ref);
4491 else if (error->code != GOT_ERR_NOT_REF)
4492 goto done;
4493 error = got_repo_match_object_id(&start_id, NULL,
4494 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4495 if (error)
4496 goto done;
4499 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4500 if (view == NULL) {
4501 error = got_error_from_errno("view_open");
4502 goto done;
4504 error = open_log_view(view, start_id, repo, head_ref_name,
4505 in_repo_path, log_branches);
4506 if (error)
4507 goto done;
4508 if (worktree) {
4509 /* Release work tree lock. */
4510 got_worktree_close(worktree);
4511 worktree = NULL;
4513 error = view_loop(view);
4514 done:
4515 free(in_repo_path);
4516 free(repo_path);
4517 free(cwd);
4518 free(start_id);
4519 free(label);
4520 if (ref)
4521 got_ref_close(ref);
4522 if (repo) {
4523 const struct got_error *close_err = got_repo_close(repo);
4524 if (error == NULL)
4525 error = close_err;
4527 if (worktree)
4528 got_worktree_close(worktree);
4529 if (pack_fds) {
4530 const struct got_error *pack_err =
4531 got_repo_pack_fds_close(pack_fds);
4532 if (error == NULL)
4533 error = pack_err;
4535 tog_free_refs();
4536 return error;
4539 __dead static void
4540 usage_diff(void)
4542 endwin();
4543 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4544 "object1 object2\n", getprogname());
4545 exit(1);
4548 static int
4549 match_line(const char *line, regex_t *regex, size_t nmatch,
4550 regmatch_t *regmatch)
4552 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4555 static struct tog_color *
4556 match_color(struct tog_colors *colors, const char *line)
4558 struct tog_color *tc = NULL;
4560 STAILQ_FOREACH(tc, colors, entry) {
4561 if (match_line(line, &tc->regex, 0, NULL))
4562 return tc;
4565 return NULL;
4568 static const struct got_error *
4569 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4570 WINDOW *window, int skipcol, regmatch_t *regmatch)
4572 const struct got_error *err = NULL;
4573 char *exstr = NULL;
4574 wchar_t *wline = NULL;
4575 int rme, rms, n, width, scrollx;
4576 int width0 = 0, width1 = 0, width2 = 0;
4577 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4579 *wtotal = 0;
4581 rms = regmatch->rm_so;
4582 rme = regmatch->rm_eo;
4584 err = expand_tab(&exstr, line);
4585 if (err)
4586 return err;
4588 /* Split the line into 3 segments, according to match offsets. */
4589 seg0 = strndup(exstr, rms);
4590 if (seg0 == NULL) {
4591 err = got_error_from_errno("strndup");
4592 goto done;
4594 seg1 = strndup(exstr + rms, rme - rms);
4595 if (seg1 == NULL) {
4596 err = got_error_from_errno("strndup");
4597 goto done;
4599 seg2 = strdup(exstr + rme);
4600 if (seg2 == NULL) {
4601 err = got_error_from_errno("strndup");
4602 goto done;
4605 /* draw up to matched token if we haven't scrolled past it */
4606 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4607 col_tab_align, 1);
4608 if (err)
4609 goto done;
4610 n = MAX(width0 - skipcol, 0);
4611 if (n) {
4612 free(wline);
4613 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4614 wlimit, col_tab_align, 1);
4615 if (err)
4616 goto done;
4617 waddwstr(window, &wline[scrollx]);
4618 wlimit -= width;
4619 *wtotal += width;
4622 if (wlimit > 0) {
4623 int i = 0, w = 0;
4624 size_t wlen;
4626 free(wline);
4627 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4628 col_tab_align, 1);
4629 if (err)
4630 goto done;
4631 wlen = wcslen(wline);
4632 while (i < wlen) {
4633 width = wcwidth(wline[i]);
4634 if (width == -1) {
4635 /* should not happen, tabs are expanded */
4636 err = got_error(GOT_ERR_RANGE);
4637 goto done;
4639 if (width0 + w + width > skipcol)
4640 break;
4641 w += width;
4642 i++;
4644 /* draw (visible part of) matched token (if scrolled into it) */
4645 if (width1 - w > 0) {
4646 wattron(window, A_STANDOUT);
4647 waddwstr(window, &wline[i]);
4648 wattroff(window, A_STANDOUT);
4649 wlimit -= (width1 - w);
4650 *wtotal += (width1 - w);
4654 if (wlimit > 0) { /* draw rest of line */
4655 free(wline);
4656 if (skipcol > width0 + width1) {
4657 err = format_line(&wline, &width2, &scrollx, seg2,
4658 skipcol - (width0 + width1), wlimit,
4659 col_tab_align, 1);
4660 if (err)
4661 goto done;
4662 waddwstr(window, &wline[scrollx]);
4663 } else {
4664 err = format_line(&wline, &width2, NULL, seg2, 0,
4665 wlimit, col_tab_align, 1);
4666 if (err)
4667 goto done;
4668 waddwstr(window, wline);
4670 *wtotal += width2;
4672 done:
4673 free(wline);
4674 free(exstr);
4675 free(seg0);
4676 free(seg1);
4677 free(seg2);
4678 return err;
4681 static int
4682 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4684 FILE *f = NULL;
4685 int *eof, *first, *selected;
4687 if (view->type == TOG_VIEW_DIFF) {
4688 struct tog_diff_view_state *s = &view->state.diff;
4690 first = &s->first_displayed_line;
4691 selected = first;
4692 eof = &s->eof;
4693 f = s->f;
4694 } else if (view->type == TOG_VIEW_HELP) {
4695 struct tog_help_view_state *s = &view->state.help;
4697 first = &s->first_displayed_line;
4698 selected = first;
4699 eof = &s->eof;
4700 f = s->f;
4701 } else if (view->type == TOG_VIEW_BLAME) {
4702 struct tog_blame_view_state *s = &view->state.blame;
4704 first = &s->first_displayed_line;
4705 selected = &s->selected_line;
4706 eof = &s->eof;
4707 f = s->blame.f;
4708 } else
4709 return 0;
4711 /* Center gline in the middle of the page like vi(1). */
4712 if (*lineno < view->gline - (view->nlines - 3) / 2)
4713 return 0;
4714 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4715 rewind(f);
4716 *eof = 0;
4717 *first = 1;
4718 *lineno = 0;
4719 *nprinted = 0;
4720 return 0;
4723 *selected = view->gline <= (view->nlines - 3) / 2 ?
4724 view->gline : (view->nlines - 3) / 2 + 1;
4725 view->gline = 0;
4727 return 1;
4730 static const struct got_error *
4731 draw_file(struct tog_view *view, const char *header)
4733 struct tog_diff_view_state *s = &view->state.diff;
4734 regmatch_t *regmatch = &view->regmatch;
4735 const struct got_error *err;
4736 int nprinted = 0;
4737 char *line;
4738 size_t linesize = 0;
4739 ssize_t linelen;
4740 wchar_t *wline;
4741 int width;
4742 int max_lines = view->nlines;
4743 int nlines = s->nlines;
4744 off_t line_offset;
4746 s->lineno = s->first_displayed_line - 1;
4747 line_offset = s->lines[s->first_displayed_line - 1].offset;
4748 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4749 return got_error_from_errno("fseek");
4751 werase(view->window);
4753 if (view->gline > s->nlines - 1)
4754 view->gline = s->nlines - 1;
4756 if (header) {
4757 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4758 1 : view->gline - (view->nlines - 3) / 2 :
4759 s->lineno + s->selected_line;
4761 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4762 return got_error_from_errno("asprintf");
4763 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4764 0, 0);
4765 free(line);
4766 if (err)
4767 return err;
4769 if (view_needs_focus_indication(view))
4770 wstandout(view->window);
4771 waddwstr(view->window, wline);
4772 free(wline);
4773 wline = NULL;
4774 while (width++ < view->ncols)
4775 waddch(view->window, ' ');
4776 if (view_needs_focus_indication(view))
4777 wstandend(view->window);
4779 if (max_lines <= 1)
4780 return NULL;
4781 max_lines--;
4784 s->eof = 0;
4785 view->maxx = 0;
4786 line = NULL;
4787 while (max_lines > 0 && nprinted < max_lines) {
4788 enum got_diff_line_type linetype;
4789 attr_t attr = 0;
4791 linelen = getline(&line, &linesize, s->f);
4792 if (linelen == -1) {
4793 if (feof(s->f)) {
4794 s->eof = 1;
4795 break;
4797 free(line);
4798 return got_ferror(s->f, GOT_ERR_IO);
4801 if (++s->lineno < s->first_displayed_line)
4802 continue;
4803 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4804 continue;
4805 if (s->lineno == view->hiline)
4806 attr = A_STANDOUT;
4808 /* Set view->maxx based on full line length. */
4809 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4810 view->x ? 1 : 0);
4811 if (err) {
4812 free(line);
4813 return err;
4815 view->maxx = MAX(view->maxx, width);
4816 free(wline);
4817 wline = NULL;
4819 linetype = s->lines[s->lineno].type;
4820 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4821 linetype < GOT_DIFF_LINE_CONTEXT)
4822 attr |= COLOR_PAIR(linetype);
4823 if (attr)
4824 wattron(view->window, attr);
4825 if (s->first_displayed_line + nprinted == s->matched_line &&
4826 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4827 err = add_matched_line(&width, line, view->ncols, 0,
4828 view->window, view->x, regmatch);
4829 if (err) {
4830 free(line);
4831 return err;
4833 } else {
4834 int skip;
4835 err = format_line(&wline, &width, &skip, line,
4836 view->x, view->ncols, 0, view->x ? 1 : 0);
4837 if (err) {
4838 free(line);
4839 return err;
4841 waddwstr(view->window, &wline[skip]);
4842 free(wline);
4843 wline = NULL;
4845 if (s->lineno == view->hiline) {
4846 /* highlight full gline length */
4847 while (width++ < view->ncols)
4848 waddch(view->window, ' ');
4849 } else {
4850 if (width <= view->ncols - 1)
4851 waddch(view->window, '\n');
4853 if (attr)
4854 wattroff(view->window, attr);
4855 if (++nprinted == 1)
4856 s->first_displayed_line = s->lineno;
4858 free(line);
4859 if (nprinted >= 1)
4860 s->last_displayed_line = s->first_displayed_line +
4861 (nprinted - 1);
4862 else
4863 s->last_displayed_line = s->first_displayed_line;
4865 view_border(view);
4867 if (s->eof) {
4868 while (nprinted < view->nlines) {
4869 waddch(view->window, '\n');
4870 nprinted++;
4873 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4874 view->ncols, 0, 0);
4875 if (err) {
4876 return err;
4879 wstandout(view->window);
4880 waddwstr(view->window, wline);
4881 free(wline);
4882 wline = NULL;
4883 wstandend(view->window);
4886 return NULL;
4889 static char *
4890 get_datestr(time_t *time, char *datebuf)
4892 struct tm mytm, *tm;
4893 char *p, *s;
4895 tm = gmtime_r(time, &mytm);
4896 if (tm == NULL)
4897 return NULL;
4898 s = asctime_r(tm, datebuf);
4899 if (s == NULL)
4900 return NULL;
4901 p = strchr(s, '\n');
4902 if (p)
4903 *p = '\0';
4904 return s;
4907 static const struct got_error *
4908 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4909 off_t off, uint8_t type)
4911 struct got_diff_line *p;
4913 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4914 if (p == NULL)
4915 return got_error_from_errno("reallocarray");
4916 *lines = p;
4917 (*lines)[*nlines].offset = off;
4918 (*lines)[*nlines].type = type;
4919 (*nlines)++;
4921 return NULL;
4924 static const struct got_error *
4925 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4926 struct got_diff_line *s_lines, size_t s_nlines)
4928 struct got_diff_line *p;
4929 char buf[BUFSIZ];
4930 size_t i, r;
4932 if (fseeko(src, 0L, SEEK_SET) == -1)
4933 return got_error_from_errno("fseeko");
4935 for (;;) {
4936 r = fread(buf, 1, sizeof(buf), src);
4937 if (r == 0) {
4938 if (ferror(src))
4939 return got_error_from_errno("fread");
4940 if (feof(src))
4941 break;
4943 if (fwrite(buf, 1, r, dst) != r)
4944 return got_ferror(dst, GOT_ERR_IO);
4947 if (s_nlines == 0 && *d_nlines == 0)
4948 return NULL;
4951 * If commit info was in dst, increment line offsets
4952 * of the appended diff content, but skip s_lines[0]
4953 * because offset zero is already in *d_lines.
4955 if (*d_nlines > 0) {
4956 for (i = 1; i < s_nlines; ++i)
4957 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4959 if (s_nlines > 0) {
4960 --s_nlines;
4961 ++s_lines;
4965 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4966 if (p == NULL) {
4967 /* d_lines is freed in close_diff_view() */
4968 return got_error_from_errno("reallocarray");
4971 *d_lines = p;
4973 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4974 *d_nlines += s_nlines;
4976 return NULL;
4979 static const struct got_error *
4980 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4981 struct got_object_id *commit_id, struct got_reflist_head *refs,
4982 struct got_repository *repo, int ignore_ws, int force_text_diff,
4983 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4985 const struct got_error *err = NULL;
4986 char datebuf[26], *datestr;
4987 struct got_commit_object *commit;
4988 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4989 time_t committer_time;
4990 const char *author, *committer;
4991 char *refs_str = NULL;
4992 struct got_pathlist_entry *pe;
4993 off_t outoff = 0;
4994 int n;
4996 err = build_refs_str(&refs_str, refs, commit_id, repo);
4997 if (err)
4998 return err;
5000 err = got_object_open_as_commit(&commit, repo, commit_id);
5001 if (err)
5002 return err;
5004 err = got_object_id_str(&id_str, commit_id);
5005 if (err) {
5006 err = got_error_from_errno("got_object_id_str");
5007 goto done;
5010 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
5011 if (err)
5012 goto done;
5014 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
5015 refs_str ? refs_str : "", refs_str ? ")" : "");
5016 if (n < 0) {
5017 err = got_error_from_errno("fprintf");
5018 goto done;
5020 outoff += n;
5021 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
5022 if (err)
5023 goto done;
5025 n = fprintf(outfile, "from: %s\n",
5026 got_object_commit_get_author(commit));
5027 if (n < 0) {
5028 err = got_error_from_errno("fprintf");
5029 goto done;
5031 outoff += n;
5032 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
5033 if (err)
5034 goto done;
5036 author = got_object_commit_get_author(commit);
5037 committer = got_object_commit_get_committer(commit);
5038 if (strcmp(author, committer) != 0) {
5039 n = fprintf(outfile, "via: %s\n", committer);
5040 if (n < 0) {
5041 err = got_error_from_errno("fprintf");
5042 goto done;
5044 outoff += n;
5045 err = add_line_metadata(lines, nlines, outoff,
5046 GOT_DIFF_LINE_AUTHOR);
5047 if (err)
5048 goto done;
5050 committer_time = got_object_commit_get_committer_time(commit);
5051 datestr = get_datestr(&committer_time, datebuf);
5052 if (datestr) {
5053 n = fprintf(outfile, "date: %s UTC\n", datestr);
5054 if (n < 0) {
5055 err = got_error_from_errno("fprintf");
5056 goto done;
5058 outoff += n;
5059 err = add_line_metadata(lines, nlines, outoff,
5060 GOT_DIFF_LINE_DATE);
5061 if (err)
5062 goto done;
5064 if (got_object_commit_get_nparents(commit) > 1) {
5065 const struct got_object_id_queue *parent_ids;
5066 struct got_object_qid *qid;
5067 int pn = 1;
5068 parent_ids = got_object_commit_get_parent_ids(commit);
5069 STAILQ_FOREACH(qid, parent_ids, entry) {
5070 err = got_object_id_str(&id_str, &qid->id);
5071 if (err)
5072 goto done;
5073 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5074 if (n < 0) {
5075 err = got_error_from_errno("fprintf");
5076 goto done;
5078 outoff += n;
5079 err = add_line_metadata(lines, nlines, outoff,
5080 GOT_DIFF_LINE_META);
5081 if (err)
5082 goto done;
5083 free(id_str);
5084 id_str = NULL;
5088 err = got_object_commit_get_logmsg(&logmsg, commit);
5089 if (err)
5090 goto done;
5091 s = logmsg;
5092 while ((line = strsep(&s, "\n")) != NULL) {
5093 n = fprintf(outfile, "%s\n", line);
5094 if (n < 0) {
5095 err = got_error_from_errno("fprintf");
5096 goto done;
5098 outoff += n;
5099 err = add_line_metadata(lines, nlines, outoff,
5100 GOT_DIFF_LINE_LOGMSG);
5101 if (err)
5102 goto done;
5105 TAILQ_FOREACH(pe, dsa->paths, entry) {
5106 struct got_diff_changed_path *cp = pe->data;
5107 int pad = dsa->max_path_len - pe->path_len + 1;
5109 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5110 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5111 dsa->rm_cols + 1, cp->rm);
5112 if (n < 0) {
5113 err = got_error_from_errno("fprintf");
5114 goto done;
5116 outoff += n;
5117 err = add_line_metadata(lines, nlines, outoff,
5118 GOT_DIFF_LINE_CHANGES);
5119 if (err)
5120 goto done;
5123 fputc('\n', outfile);
5124 outoff++;
5125 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5126 if (err)
5127 goto done;
5129 n = fprintf(outfile,
5130 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5131 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5132 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5133 if (n < 0) {
5134 err = got_error_from_errno("fprintf");
5135 goto done;
5137 outoff += n;
5138 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5139 if (err)
5140 goto done;
5142 fputc('\n', outfile);
5143 outoff++;
5144 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5145 done:
5146 free(id_str);
5147 free(logmsg);
5148 free(refs_str);
5149 got_object_commit_close(commit);
5150 if (err) {
5151 free(*lines);
5152 *lines = NULL;
5153 *nlines = 0;
5155 return err;
5158 static const struct got_error *
5159 create_diff(struct tog_diff_view_state *s)
5161 const struct got_error *err = NULL;
5162 FILE *f = NULL, *tmp_diff_file = NULL;
5163 int obj_type;
5164 struct got_diff_line *lines = NULL;
5165 struct got_pathlist_head changed_paths;
5167 TAILQ_INIT(&changed_paths);
5169 free(s->lines);
5170 s->lines = malloc(sizeof(*s->lines));
5171 if (s->lines == NULL)
5172 return got_error_from_errno("malloc");
5173 s->nlines = 0;
5175 f = got_opentemp();
5176 if (f == NULL) {
5177 err = got_error_from_errno("got_opentemp");
5178 goto done;
5180 tmp_diff_file = got_opentemp();
5181 if (tmp_diff_file == NULL) {
5182 err = got_error_from_errno("got_opentemp");
5183 goto done;
5185 if (s->f && fclose(s->f) == EOF) {
5186 err = got_error_from_errno("fclose");
5187 goto done;
5189 s->f = f;
5191 if (s->id1)
5192 err = got_object_get_type(&obj_type, s->repo, s->id1);
5193 else
5194 err = got_object_get_type(&obj_type, s->repo, s->id2);
5195 if (err)
5196 goto done;
5198 switch (obj_type) {
5199 case GOT_OBJ_TYPE_BLOB:
5200 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5201 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5202 s->label1, s->label2, tog_diff_algo, s->diff_context,
5203 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5204 s->f);
5205 break;
5206 case GOT_OBJ_TYPE_TREE:
5207 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5208 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5209 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5210 s->force_text_diff, NULL, s->repo, s->f);
5211 break;
5212 case GOT_OBJ_TYPE_COMMIT: {
5213 const struct got_object_id_queue *parent_ids;
5214 struct got_object_qid *pid;
5215 struct got_commit_object *commit2;
5216 struct got_reflist_head *refs;
5217 size_t nlines = 0;
5218 struct got_diffstat_cb_arg dsa = {
5219 0, 0, 0, 0, 0, 0,
5220 &changed_paths,
5221 s->ignore_whitespace,
5222 s->force_text_diff,
5223 tog_diff_algo
5226 lines = malloc(sizeof(*lines));
5227 if (lines == NULL) {
5228 err = got_error_from_errno("malloc");
5229 goto done;
5232 /* build diff first in tmp file then append to commit info */
5233 err = got_diff_objects_as_commits(&lines, &nlines,
5234 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5235 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5236 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5237 if (err)
5238 break;
5240 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5241 if (err)
5242 goto done;
5243 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5244 /* Show commit info if we're diffing to a parent/root commit. */
5245 if (s->id1 == NULL) {
5246 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5247 refs, s->repo, s->ignore_whitespace,
5248 s->force_text_diff, &dsa, s->f);
5249 if (err)
5250 goto done;
5251 } else {
5252 parent_ids = got_object_commit_get_parent_ids(commit2);
5253 STAILQ_FOREACH(pid, parent_ids, entry) {
5254 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5255 err = write_commit_info(&s->lines,
5256 &s->nlines, s->id2, refs, s->repo,
5257 s->ignore_whitespace,
5258 s->force_text_diff, &dsa, s->f);
5259 if (err)
5260 goto done;
5261 break;
5265 got_object_commit_close(commit2);
5267 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5268 lines, nlines);
5269 break;
5271 default:
5272 err = got_error(GOT_ERR_OBJ_TYPE);
5273 break;
5275 done:
5276 free(lines);
5277 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5278 if (s->f && fflush(s->f) != 0 && err == NULL)
5279 err = got_error_from_errno("fflush");
5280 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5281 err = got_error_from_errno("fclose");
5282 return err;
5285 static void
5286 diff_view_indicate_progress(struct tog_view *view)
5288 mvwaddstr(view->window, 0, 0, "diffing...");
5289 update_panels();
5290 doupdate();
5293 static const struct got_error *
5294 search_start_diff_view(struct tog_view *view)
5296 struct tog_diff_view_state *s = &view->state.diff;
5298 s->matched_line = 0;
5299 return NULL;
5302 static void
5303 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5304 size_t *nlines, int **first, int **last, int **match, int **selected)
5306 struct tog_diff_view_state *s = &view->state.diff;
5308 *f = s->f;
5309 *nlines = s->nlines;
5310 *line_offsets = NULL;
5311 *match = &s->matched_line;
5312 *first = &s->first_displayed_line;
5313 *last = &s->last_displayed_line;
5314 *selected = &s->selected_line;
5317 static const struct got_error *
5318 search_next_view_match(struct tog_view *view)
5320 const struct got_error *err = NULL;
5321 FILE *f;
5322 int lineno;
5323 char *line = NULL;
5324 size_t linesize = 0;
5325 ssize_t linelen;
5326 off_t *line_offsets;
5327 size_t nlines = 0;
5328 int *first, *last, *match, *selected;
5330 if (!view->search_setup)
5331 return got_error_msg(GOT_ERR_NOT_IMPL,
5332 "view search not supported");
5333 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5334 &match, &selected);
5336 if (!view->searching) {
5337 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5338 return NULL;
5341 if (*match) {
5342 if (view->searching == TOG_SEARCH_FORWARD)
5343 lineno = *first + 1;
5344 else
5345 lineno = *first - 1;
5346 } else
5347 lineno = *first - 1 + *selected;
5349 while (1) {
5350 off_t offset;
5352 if (lineno <= 0 || lineno > nlines) {
5353 if (*match == 0) {
5354 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5355 break;
5358 if (view->searching == TOG_SEARCH_FORWARD)
5359 lineno = 1;
5360 else
5361 lineno = nlines;
5364 offset = view->type == TOG_VIEW_DIFF ?
5365 view->state.diff.lines[lineno - 1].offset :
5366 line_offsets[lineno - 1];
5367 if (fseeko(f, offset, SEEK_SET) != 0) {
5368 free(line);
5369 return got_error_from_errno("fseeko");
5371 linelen = getline(&line, &linesize, f);
5372 if (linelen != -1) {
5373 char *exstr;
5374 err = expand_tab(&exstr, line);
5375 if (err)
5376 break;
5377 if (match_line(exstr, &view->regex, 1,
5378 &view->regmatch)) {
5379 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5380 *match = lineno;
5381 free(exstr);
5382 break;
5384 free(exstr);
5386 if (view->searching == TOG_SEARCH_FORWARD)
5387 lineno++;
5388 else
5389 lineno--;
5391 free(line);
5393 if (*match) {
5394 *first = *match;
5395 *selected = 1;
5398 return err;
5401 static const struct got_error *
5402 close_diff_view(struct tog_view *view)
5404 const struct got_error *err = NULL;
5405 struct tog_diff_view_state *s = &view->state.diff;
5407 free(s->id1);
5408 s->id1 = NULL;
5409 free(s->id2);
5410 s->id2 = NULL;
5411 if (s->f && fclose(s->f) == EOF)
5412 err = got_error_from_errno("fclose");
5413 s->f = NULL;
5414 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5415 err = got_error_from_errno("fclose");
5416 s->f1 = NULL;
5417 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5418 err = got_error_from_errno("fclose");
5419 s->f2 = NULL;
5420 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5421 err = got_error_from_errno("close");
5422 s->fd1 = -1;
5423 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5424 err = got_error_from_errno("close");
5425 s->fd2 = -1;
5426 free(s->lines);
5427 s->lines = NULL;
5428 s->nlines = 0;
5429 return err;
5432 static const struct got_error *
5433 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5434 struct got_object_id *id2, const char *label1, const char *label2,
5435 int diff_context, int ignore_whitespace, int force_text_diff,
5436 struct tog_view *parent_view, struct got_repository *repo)
5438 const struct got_error *err;
5439 struct tog_diff_view_state *s = &view->state.diff;
5441 memset(s, 0, sizeof(*s));
5442 s->fd1 = -1;
5443 s->fd2 = -1;
5445 if (id1 != NULL && id2 != NULL) {
5446 int type1, type2;
5448 err = got_object_get_type(&type1, repo, id1);
5449 if (err)
5450 goto done;
5451 err = got_object_get_type(&type2, repo, id2);
5452 if (err)
5453 goto done;
5455 if (type1 != type2) {
5456 err = got_error(GOT_ERR_OBJ_TYPE);
5457 goto done;
5460 s->first_displayed_line = 1;
5461 s->last_displayed_line = view->nlines;
5462 s->selected_line = 1;
5463 s->repo = repo;
5464 s->id1 = id1;
5465 s->id2 = id2;
5466 s->label1 = label1;
5467 s->label2 = label2;
5469 if (id1) {
5470 s->id1 = got_object_id_dup(id1);
5471 if (s->id1 == NULL) {
5472 err = got_error_from_errno("got_object_id_dup");
5473 goto done;
5475 } else
5476 s->id1 = NULL;
5478 s->id2 = got_object_id_dup(id2);
5479 if (s->id2 == NULL) {
5480 err = got_error_from_errno("got_object_id_dup");
5481 goto done;
5484 s->f1 = got_opentemp();
5485 if (s->f1 == NULL) {
5486 err = got_error_from_errno("got_opentemp");
5487 goto done;
5490 s->f2 = got_opentemp();
5491 if (s->f2 == NULL) {
5492 err = got_error_from_errno("got_opentemp");
5493 goto done;
5496 s->fd1 = got_opentempfd();
5497 if (s->fd1 == -1) {
5498 err = got_error_from_errno("got_opentempfd");
5499 goto done;
5502 s->fd2 = got_opentempfd();
5503 if (s->fd2 == -1) {
5504 err = got_error_from_errno("got_opentempfd");
5505 goto done;
5508 s->diff_context = diff_context;
5509 s->ignore_whitespace = ignore_whitespace;
5510 s->force_text_diff = force_text_diff;
5511 s->parent_view = parent_view;
5512 s->repo = repo;
5514 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5515 int rc;
5517 rc = init_pair(GOT_DIFF_LINE_MINUS,
5518 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5519 if (rc != ERR)
5520 rc = init_pair(GOT_DIFF_LINE_PLUS,
5521 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5522 if (rc != ERR)
5523 rc = init_pair(GOT_DIFF_LINE_HUNK,
5524 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5525 if (rc != ERR)
5526 rc = init_pair(GOT_DIFF_LINE_META,
5527 get_color_value("TOG_COLOR_DIFF_META"), -1);
5528 if (rc != ERR)
5529 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5530 get_color_value("TOG_COLOR_DIFF_META"), -1);
5531 if (rc != ERR)
5532 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5533 get_color_value("TOG_COLOR_DIFF_META"), -1);
5534 if (rc != ERR)
5535 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5536 get_color_value("TOG_COLOR_DIFF_META"), -1);
5537 if (rc != ERR)
5538 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5539 get_color_value("TOG_COLOR_AUTHOR"), -1);
5540 if (rc != ERR)
5541 rc = init_pair(GOT_DIFF_LINE_DATE,
5542 get_color_value("TOG_COLOR_DATE"), -1);
5543 if (rc == ERR) {
5544 err = got_error(GOT_ERR_RANGE);
5545 goto done;
5549 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5550 view_is_splitscreen(view))
5551 show_log_view(parent_view); /* draw border */
5552 diff_view_indicate_progress(view);
5554 err = create_diff(s);
5556 view->show = show_diff_view;
5557 view->input = input_diff_view;
5558 view->reset = reset_diff_view;
5559 view->close = close_diff_view;
5560 view->search_start = search_start_diff_view;
5561 view->search_setup = search_setup_diff_view;
5562 view->search_next = search_next_view_match;
5563 done:
5564 if (err) {
5565 if (view->close == NULL)
5566 close_diff_view(view);
5567 view_close(view);
5569 return err;
5572 static const struct got_error *
5573 show_diff_view(struct tog_view *view)
5575 const struct got_error *err;
5576 struct tog_diff_view_state *s = &view->state.diff;
5577 char *id_str1 = NULL, *id_str2, *header;
5578 const char *label1, *label2;
5580 if (s->id1) {
5581 err = got_object_id_str(&id_str1, s->id1);
5582 if (err)
5583 return err;
5584 label1 = s->label1 ? s->label1 : id_str1;
5585 } else
5586 label1 = "/dev/null";
5588 err = got_object_id_str(&id_str2, s->id2);
5589 if (err)
5590 return err;
5591 label2 = s->label2 ? s->label2 : id_str2;
5593 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5594 err = got_error_from_errno("asprintf");
5595 free(id_str1);
5596 free(id_str2);
5597 return err;
5599 free(id_str1);
5600 free(id_str2);
5602 err = draw_file(view, header);
5603 free(header);
5604 return err;
5607 static const struct got_error *
5608 set_selected_commit(struct tog_diff_view_state *s,
5609 struct commit_queue_entry *entry)
5611 const struct got_error *err;
5612 const struct got_object_id_queue *parent_ids;
5613 struct got_commit_object *selected_commit;
5614 struct got_object_qid *pid;
5616 free(s->id2);
5617 s->id2 = got_object_id_dup(entry->id);
5618 if (s->id2 == NULL)
5619 return got_error_from_errno("got_object_id_dup");
5621 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5622 if (err)
5623 return err;
5624 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5625 free(s->id1);
5626 pid = STAILQ_FIRST(parent_ids);
5627 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5628 got_object_commit_close(selected_commit);
5629 return NULL;
5632 static const struct got_error *
5633 reset_diff_view(struct tog_view *view)
5635 struct tog_diff_view_state *s = &view->state.diff;
5637 view->count = 0;
5638 wclear(view->window);
5639 s->first_displayed_line = 1;
5640 s->last_displayed_line = view->nlines;
5641 s->matched_line = 0;
5642 diff_view_indicate_progress(view);
5643 return create_diff(s);
5646 static void
5647 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5649 int start, i;
5651 i = start = s->first_displayed_line - 1;
5653 while (s->lines[i].type != type) {
5654 if (i == 0)
5655 i = s->nlines - 1;
5656 if (--i == start)
5657 return; /* do nothing, requested type not in file */
5660 s->selected_line = 1;
5661 s->first_displayed_line = i;
5664 static void
5665 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5667 int start, i;
5669 i = start = s->first_displayed_line + 1;
5671 while (s->lines[i].type != type) {
5672 if (i == s->nlines - 1)
5673 i = 0;
5674 if (++i == start)
5675 return; /* do nothing, requested type not in file */
5678 s->selected_line = 1;
5679 s->first_displayed_line = i;
5682 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5683 int, int, int);
5684 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5685 int, int);
5687 static const struct got_error *
5688 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5690 const struct got_error *err = NULL;
5691 struct tog_diff_view_state *s = &view->state.diff;
5692 struct tog_log_view_state *ls;
5693 struct commit_queue_entry *old_selected_entry;
5694 char *line = NULL;
5695 size_t linesize = 0;
5696 ssize_t linelen;
5697 int i, nscroll = view->nlines - 1, up = 0;
5699 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5701 switch (ch) {
5702 case '0':
5703 case '$':
5704 case KEY_RIGHT:
5705 case 'l':
5706 case KEY_LEFT:
5707 case 'h':
5708 horizontal_scroll_input(view, ch);
5709 break;
5710 case 'a':
5711 case 'w':
5712 if (ch == 'a') {
5713 s->force_text_diff = !s->force_text_diff;
5714 view->action = s->force_text_diff ?
5715 "force ASCII text enabled" :
5716 "force ASCII text disabled";
5718 else if (ch == 'w') {
5719 s->ignore_whitespace = !s->ignore_whitespace;
5720 view->action = s->ignore_whitespace ?
5721 "ignore whitespace enabled" :
5722 "ignore whitespace disabled";
5724 err = reset_diff_view(view);
5725 break;
5726 case 'g':
5727 case KEY_HOME:
5728 s->first_displayed_line = 1;
5729 view->count = 0;
5730 break;
5731 case 'G':
5732 case KEY_END:
5733 view->count = 0;
5734 if (s->eof)
5735 break;
5737 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5738 s->eof = 1;
5739 break;
5740 case 'k':
5741 case KEY_UP:
5742 case CTRL('p'):
5743 if (s->first_displayed_line > 1)
5744 s->first_displayed_line--;
5745 else
5746 view->count = 0;
5747 break;
5748 case CTRL('u'):
5749 case 'u':
5750 nscroll /= 2;
5751 /* FALL THROUGH */
5752 case KEY_PPAGE:
5753 case CTRL('b'):
5754 case 'b':
5755 if (s->first_displayed_line == 1) {
5756 view->count = 0;
5757 break;
5759 i = 0;
5760 while (i++ < nscroll && s->first_displayed_line > 1)
5761 s->first_displayed_line--;
5762 break;
5763 case 'j':
5764 case KEY_DOWN:
5765 case CTRL('n'):
5766 if (!s->eof)
5767 s->first_displayed_line++;
5768 else
5769 view->count = 0;
5770 break;
5771 case CTRL('d'):
5772 case 'd':
5773 nscroll /= 2;
5774 /* FALL THROUGH */
5775 case KEY_NPAGE:
5776 case CTRL('f'):
5777 case 'f':
5778 case ' ':
5779 if (s->eof) {
5780 view->count = 0;
5781 break;
5783 i = 0;
5784 while (!s->eof && i++ < nscroll) {
5785 linelen = getline(&line, &linesize, s->f);
5786 s->first_displayed_line++;
5787 if (linelen == -1) {
5788 if (feof(s->f)) {
5789 s->eof = 1;
5790 } else
5791 err = got_ferror(s->f, GOT_ERR_IO);
5792 break;
5795 free(line);
5796 break;
5797 case '(':
5798 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5799 break;
5800 case ')':
5801 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5802 break;
5803 case '{':
5804 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5805 break;
5806 case '}':
5807 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5808 break;
5809 case '[':
5810 if (s->diff_context > 0) {
5811 s->diff_context--;
5812 s->matched_line = 0;
5813 diff_view_indicate_progress(view);
5814 err = create_diff(s);
5815 if (s->first_displayed_line + view->nlines - 1 >
5816 s->nlines) {
5817 s->first_displayed_line = 1;
5818 s->last_displayed_line = view->nlines;
5820 } else
5821 view->count = 0;
5822 break;
5823 case ']':
5824 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5825 s->diff_context++;
5826 s->matched_line = 0;
5827 diff_view_indicate_progress(view);
5828 err = create_diff(s);
5829 } else
5830 view->count = 0;
5831 break;
5832 case '<':
5833 case ',':
5834 case 'K':
5835 up = 1;
5836 /* FALL THROUGH */
5837 case '>':
5838 case '.':
5839 case 'J':
5840 if (s->parent_view == NULL) {
5841 view->count = 0;
5842 break;
5844 s->parent_view->count = view->count;
5846 if (s->parent_view->type == TOG_VIEW_LOG) {
5847 ls = &s->parent_view->state.log;
5848 old_selected_entry = ls->selected_entry;
5850 err = input_log_view(NULL, s->parent_view,
5851 up ? KEY_UP : KEY_DOWN);
5852 if (err)
5853 break;
5854 view->count = s->parent_view->count;
5856 if (old_selected_entry == ls->selected_entry)
5857 break;
5859 err = set_selected_commit(s, ls->selected_entry);
5860 if (err)
5861 break;
5862 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5863 struct tog_blame_view_state *bs;
5864 struct got_object_id *id, *prev_id;
5866 bs = &s->parent_view->state.blame;
5867 prev_id = get_annotation_for_line(bs->blame.lines,
5868 bs->blame.nlines, bs->last_diffed_line);
5870 err = input_blame_view(&view, s->parent_view,
5871 up ? KEY_UP : KEY_DOWN);
5872 if (err)
5873 break;
5874 view->count = s->parent_view->count;
5876 if (prev_id == NULL)
5877 break;
5878 id = get_selected_commit_id(bs->blame.lines,
5879 bs->blame.nlines, bs->first_displayed_line,
5880 bs->selected_line);
5881 if (id == NULL)
5882 break;
5884 if (!got_object_id_cmp(prev_id, id))
5885 break;
5887 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5888 if (err)
5889 break;
5891 s->first_displayed_line = 1;
5892 s->last_displayed_line = view->nlines;
5893 s->matched_line = 0;
5894 view->x = 0;
5896 diff_view_indicate_progress(view);
5897 err = create_diff(s);
5898 break;
5899 default:
5900 view->count = 0;
5901 break;
5904 return err;
5907 static const struct got_error *
5908 cmd_diff(int argc, char *argv[])
5910 const struct got_error *error;
5911 struct got_repository *repo = NULL;
5912 struct got_worktree *worktree = NULL;
5913 struct got_object_id *id1 = NULL, *id2 = NULL;
5914 char *repo_path = NULL, *cwd = NULL;
5915 char *id_str1 = NULL, *id_str2 = NULL;
5916 char *label1 = NULL, *label2 = NULL;
5917 int diff_context = 3, ignore_whitespace = 0;
5918 int ch, force_text_diff = 0;
5919 const char *errstr;
5920 struct tog_view *view;
5921 int *pack_fds = NULL;
5923 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5924 switch (ch) {
5925 case 'a':
5926 force_text_diff = 1;
5927 break;
5928 case 'C':
5929 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5930 &errstr);
5931 if (errstr != NULL)
5932 errx(1, "number of context lines is %s: %s",
5933 errstr, errstr);
5934 break;
5935 case 'r':
5936 repo_path = realpath(optarg, NULL);
5937 if (repo_path == NULL)
5938 return got_error_from_errno2("realpath",
5939 optarg);
5940 got_path_strip_trailing_slashes(repo_path);
5941 break;
5942 case 'w':
5943 ignore_whitespace = 1;
5944 break;
5945 default:
5946 usage_diff();
5947 /* NOTREACHED */
5951 argc -= optind;
5952 argv += optind;
5954 if (argc == 0) {
5955 usage_diff(); /* TODO show local worktree changes */
5956 } else if (argc == 2) {
5957 id_str1 = argv[0];
5958 id_str2 = argv[1];
5959 } else
5960 usage_diff();
5962 error = got_repo_pack_fds_open(&pack_fds);
5963 if (error)
5964 goto done;
5966 if (repo_path == NULL) {
5967 cwd = getcwd(NULL, 0);
5968 if (cwd == NULL)
5969 return got_error_from_errno("getcwd");
5970 error = got_worktree_open(&worktree, cwd);
5971 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5972 goto done;
5973 if (worktree)
5974 repo_path =
5975 strdup(got_worktree_get_repo_path(worktree));
5976 else
5977 repo_path = strdup(cwd);
5978 if (repo_path == NULL) {
5979 error = got_error_from_errno("strdup");
5980 goto done;
5984 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5985 if (error)
5986 goto done;
5988 init_curses();
5990 error = apply_unveil(got_repo_get_path(repo), NULL);
5991 if (error)
5992 goto done;
5994 error = tog_load_refs(repo, 0);
5995 if (error)
5996 goto done;
5998 error = got_repo_match_object_id(&id1, &label1, id_str1,
5999 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6000 if (error)
6001 goto done;
6003 error = got_repo_match_object_id(&id2, &label2, id_str2,
6004 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6005 if (error)
6006 goto done;
6008 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
6009 if (view == NULL) {
6010 error = got_error_from_errno("view_open");
6011 goto done;
6013 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
6014 ignore_whitespace, force_text_diff, NULL, repo);
6015 if (error)
6016 goto done;
6017 error = view_loop(view);
6018 done:
6019 free(label1);
6020 free(label2);
6021 free(repo_path);
6022 free(cwd);
6023 if (repo) {
6024 const struct got_error *close_err = got_repo_close(repo);
6025 if (error == NULL)
6026 error = close_err;
6028 if (worktree)
6029 got_worktree_close(worktree);
6030 if (pack_fds) {
6031 const struct got_error *pack_err =
6032 got_repo_pack_fds_close(pack_fds);
6033 if (error == NULL)
6034 error = pack_err;
6036 tog_free_refs();
6037 return error;
6040 __dead static void
6041 usage_blame(void)
6043 endwin();
6044 fprintf(stderr,
6045 "usage: %s blame [-c commit] [-r repository-path] path\n",
6046 getprogname());
6047 exit(1);
6050 struct tog_blame_line {
6051 int annotated;
6052 struct got_object_id *id;
6055 static const struct got_error *
6056 draw_blame(struct tog_view *view)
6058 struct tog_blame_view_state *s = &view->state.blame;
6059 struct tog_blame *blame = &s->blame;
6060 regmatch_t *regmatch = &view->regmatch;
6061 const struct got_error *err;
6062 int lineno = 0, nprinted = 0;
6063 char *line = NULL;
6064 size_t linesize = 0;
6065 ssize_t linelen;
6066 wchar_t *wline;
6067 int width;
6068 struct tog_blame_line *blame_line;
6069 struct got_object_id *prev_id = NULL;
6070 char *id_str;
6071 struct tog_color *tc;
6073 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6074 if (err)
6075 return err;
6077 rewind(blame->f);
6078 werase(view->window);
6080 if (asprintf(&line, "commit %s", id_str) == -1) {
6081 err = got_error_from_errno("asprintf");
6082 free(id_str);
6083 return err;
6086 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6087 free(line);
6088 line = NULL;
6089 if (err)
6090 return err;
6091 if (view_needs_focus_indication(view))
6092 wstandout(view->window);
6093 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6094 if (tc)
6095 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6096 waddwstr(view->window, wline);
6097 while (width++ < view->ncols)
6098 waddch(view->window, ' ');
6099 if (tc)
6100 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6101 if (view_needs_focus_indication(view))
6102 wstandend(view->window);
6103 free(wline);
6104 wline = NULL;
6106 if (view->gline > blame->nlines)
6107 view->gline = blame->nlines;
6109 if (tog_io.wait_for_ui) {
6110 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6111 int rc;
6113 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6114 if (rc)
6115 return got_error_set_errno(rc, "pthread_cond_wait");
6116 tog_io.wait_for_ui = 0;
6119 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6120 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6121 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6122 free(id_str);
6123 return got_error_from_errno("asprintf");
6125 free(id_str);
6126 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6127 free(line);
6128 line = NULL;
6129 if (err)
6130 return err;
6131 waddwstr(view->window, wline);
6132 free(wline);
6133 wline = NULL;
6134 if (width < view->ncols - 1)
6135 waddch(view->window, '\n');
6137 s->eof = 0;
6138 view->maxx = 0;
6139 while (nprinted < view->nlines - 2) {
6140 linelen = getline(&line, &linesize, blame->f);
6141 if (linelen == -1) {
6142 if (feof(blame->f)) {
6143 s->eof = 1;
6144 break;
6146 free(line);
6147 return got_ferror(blame->f, GOT_ERR_IO);
6149 if (++lineno < s->first_displayed_line)
6150 continue;
6151 if (view->gline && !gotoline(view, &lineno, &nprinted))
6152 continue;
6154 /* Set view->maxx based on full line length. */
6155 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6156 if (err) {
6157 free(line);
6158 return err;
6160 free(wline);
6161 wline = NULL;
6162 view->maxx = MAX(view->maxx, width);
6164 if (nprinted == s->selected_line - 1)
6165 wstandout(view->window);
6167 if (blame->nlines > 0) {
6168 blame_line = &blame->lines[lineno - 1];
6169 if (blame_line->annotated && prev_id &&
6170 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6171 !(nprinted == s->selected_line - 1)) {
6172 waddstr(view->window, " ");
6173 } else if (blame_line->annotated) {
6174 char *id_str;
6175 err = got_object_id_str(&id_str,
6176 blame_line->id);
6177 if (err) {
6178 free(line);
6179 return err;
6181 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6182 if (tc)
6183 wattr_on(view->window,
6184 COLOR_PAIR(tc->colorpair), NULL);
6185 wprintw(view->window, "%.8s", id_str);
6186 if (tc)
6187 wattr_off(view->window,
6188 COLOR_PAIR(tc->colorpair), NULL);
6189 free(id_str);
6190 prev_id = blame_line->id;
6191 } else {
6192 waddstr(view->window, "........");
6193 prev_id = NULL;
6195 } else {
6196 waddstr(view->window, "........");
6197 prev_id = NULL;
6200 if (nprinted == s->selected_line - 1)
6201 wstandend(view->window);
6202 waddstr(view->window, " ");
6204 if (view->ncols <= 9) {
6205 width = 9;
6206 } else if (s->first_displayed_line + nprinted ==
6207 s->matched_line &&
6208 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6209 err = add_matched_line(&width, line, view->ncols - 9, 9,
6210 view->window, view->x, regmatch);
6211 if (err) {
6212 free(line);
6213 return err;
6215 width += 9;
6216 } else {
6217 int skip;
6218 err = format_line(&wline, &width, &skip, line,
6219 view->x, view->ncols - 9, 9, 1);
6220 if (err) {
6221 free(line);
6222 return err;
6224 waddwstr(view->window, &wline[skip]);
6225 width += 9;
6226 free(wline);
6227 wline = NULL;
6230 if (width <= view->ncols - 1)
6231 waddch(view->window, '\n');
6232 if (++nprinted == 1)
6233 s->first_displayed_line = lineno;
6235 free(line);
6236 s->last_displayed_line = lineno;
6238 view_border(view);
6240 return NULL;
6243 static const struct got_error *
6244 blame_cb(void *arg, int nlines, int lineno,
6245 struct got_commit_object *commit, struct got_object_id *id)
6247 const struct got_error *err = NULL;
6248 struct tog_blame_cb_args *a = arg;
6249 struct tog_blame_line *line;
6250 int errcode;
6252 if (nlines != a->nlines ||
6253 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6254 return got_error(GOT_ERR_RANGE);
6256 errcode = pthread_mutex_lock(&tog_mutex);
6257 if (errcode)
6258 return got_error_set_errno(errcode, "pthread_mutex_lock");
6260 if (*a->quit) { /* user has quit the blame view */
6261 err = got_error(GOT_ERR_ITER_COMPLETED);
6262 goto done;
6265 if (lineno == -1)
6266 goto done; /* no change in this commit */
6268 line = &a->lines[lineno - 1];
6269 if (line->annotated)
6270 goto done;
6272 line->id = got_object_id_dup(id);
6273 if (line->id == NULL) {
6274 err = got_error_from_errno("got_object_id_dup");
6275 goto done;
6277 line->annotated = 1;
6278 done:
6279 errcode = pthread_mutex_unlock(&tog_mutex);
6280 if (errcode)
6281 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6282 return err;
6285 static void *
6286 blame_thread(void *arg)
6288 const struct got_error *err, *close_err;
6289 struct tog_blame_thread_args *ta = arg;
6290 struct tog_blame_cb_args *a = ta->cb_args;
6291 int errcode, fd1 = -1, fd2 = -1;
6292 FILE *f1 = NULL, *f2 = NULL;
6294 fd1 = got_opentempfd();
6295 if (fd1 == -1)
6296 return (void *)got_error_from_errno("got_opentempfd");
6298 fd2 = got_opentempfd();
6299 if (fd2 == -1) {
6300 err = got_error_from_errno("got_opentempfd");
6301 goto done;
6304 f1 = got_opentemp();
6305 if (f1 == NULL) {
6306 err = (void *)got_error_from_errno("got_opentemp");
6307 goto done;
6309 f2 = got_opentemp();
6310 if (f2 == NULL) {
6311 err = (void *)got_error_from_errno("got_opentemp");
6312 goto done;
6315 err = block_signals_used_by_main_thread();
6316 if (err)
6317 goto done;
6319 err = got_blame(ta->path, a->commit_id, ta->repo,
6320 tog_diff_algo, blame_cb, ta->cb_args,
6321 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6322 if (err && err->code == GOT_ERR_CANCELLED)
6323 err = NULL;
6325 errcode = pthread_mutex_lock(&tog_mutex);
6326 if (errcode) {
6327 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6328 goto done;
6331 close_err = got_repo_close(ta->repo);
6332 if (err == NULL)
6333 err = close_err;
6334 ta->repo = NULL;
6335 *ta->complete = 1;
6337 if (tog_io.wait_for_ui) {
6338 errcode = pthread_cond_signal(&ta->blame_complete);
6339 if (errcode && err == NULL)
6340 err = got_error_set_errno(errcode,
6341 "pthread_cond_signal");
6344 errcode = pthread_mutex_unlock(&tog_mutex);
6345 if (errcode && err == NULL)
6346 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6348 done:
6349 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6350 err = got_error_from_errno("close");
6351 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6352 err = got_error_from_errno("close");
6353 if (f1 && fclose(f1) == EOF && err == NULL)
6354 err = got_error_from_errno("fclose");
6355 if (f2 && fclose(f2) == EOF && err == NULL)
6356 err = got_error_from_errno("fclose");
6358 return (void *)err;
6361 static struct got_object_id *
6362 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6363 int first_displayed_line, int selected_line)
6365 struct tog_blame_line *line;
6367 if (nlines <= 0)
6368 return NULL;
6370 line = &lines[first_displayed_line - 1 + selected_line - 1];
6371 if (!line->annotated)
6372 return NULL;
6374 return line->id;
6377 static struct got_object_id *
6378 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6379 int lineno)
6381 struct tog_blame_line *line;
6383 if (nlines <= 0 || lineno >= nlines)
6384 return NULL;
6386 line = &lines[lineno - 1];
6387 if (!line->annotated)
6388 return NULL;
6390 return line->id;
6393 static const struct got_error *
6394 stop_blame(struct tog_blame *blame)
6396 const struct got_error *err = NULL;
6397 int i;
6399 if (blame->thread) {
6400 int errcode;
6401 errcode = pthread_mutex_unlock(&tog_mutex);
6402 if (errcode)
6403 return got_error_set_errno(errcode,
6404 "pthread_mutex_unlock");
6405 errcode = pthread_join(blame->thread, (void **)&err);
6406 if (errcode)
6407 return got_error_set_errno(errcode, "pthread_join");
6408 errcode = pthread_mutex_lock(&tog_mutex);
6409 if (errcode)
6410 return got_error_set_errno(errcode,
6411 "pthread_mutex_lock");
6412 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6413 err = NULL;
6414 blame->thread = NULL;
6416 if (blame->thread_args.repo) {
6417 const struct got_error *close_err;
6418 close_err = got_repo_close(blame->thread_args.repo);
6419 if (err == NULL)
6420 err = close_err;
6421 blame->thread_args.repo = NULL;
6423 if (blame->f) {
6424 if (fclose(blame->f) == EOF && err == NULL)
6425 err = got_error_from_errno("fclose");
6426 blame->f = NULL;
6428 if (blame->lines) {
6429 for (i = 0; i < blame->nlines; i++)
6430 free(blame->lines[i].id);
6431 free(blame->lines);
6432 blame->lines = NULL;
6434 free(blame->cb_args.commit_id);
6435 blame->cb_args.commit_id = NULL;
6436 if (blame->pack_fds) {
6437 const struct got_error *pack_err =
6438 got_repo_pack_fds_close(blame->pack_fds);
6439 if (err == NULL)
6440 err = pack_err;
6441 blame->pack_fds = NULL;
6443 return err;
6446 static const struct got_error *
6447 cancel_blame_view(void *arg)
6449 const struct got_error *err = NULL;
6450 int *done = arg;
6451 int errcode;
6453 errcode = pthread_mutex_lock(&tog_mutex);
6454 if (errcode)
6455 return got_error_set_errno(errcode,
6456 "pthread_mutex_unlock");
6458 if (*done)
6459 err = got_error(GOT_ERR_CANCELLED);
6461 errcode = pthread_mutex_unlock(&tog_mutex);
6462 if (errcode)
6463 return got_error_set_errno(errcode,
6464 "pthread_mutex_lock");
6466 return err;
6469 static const struct got_error *
6470 run_blame(struct tog_view *view)
6472 struct tog_blame_view_state *s = &view->state.blame;
6473 struct tog_blame *blame = &s->blame;
6474 const struct got_error *err = NULL;
6475 struct got_commit_object *commit = NULL;
6476 struct got_blob_object *blob = NULL;
6477 struct got_repository *thread_repo = NULL;
6478 struct got_object_id *obj_id = NULL;
6479 int obj_type, fd = -1;
6480 int *pack_fds = NULL;
6482 err = got_object_open_as_commit(&commit, s->repo,
6483 &s->blamed_commit->id);
6484 if (err)
6485 return err;
6487 fd = got_opentempfd();
6488 if (fd == -1) {
6489 err = got_error_from_errno("got_opentempfd");
6490 goto done;
6493 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6494 if (err)
6495 goto done;
6497 err = got_object_get_type(&obj_type, s->repo, obj_id);
6498 if (err)
6499 goto done;
6501 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6502 err = got_error(GOT_ERR_OBJ_TYPE);
6503 goto done;
6506 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6507 if (err)
6508 goto done;
6509 blame->f = got_opentemp();
6510 if (blame->f == NULL) {
6511 err = got_error_from_errno("got_opentemp");
6512 goto done;
6514 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6515 &blame->line_offsets, blame->f, blob);
6516 if (err)
6517 goto done;
6518 if (blame->nlines == 0) {
6519 s->blame_complete = 1;
6520 goto done;
6523 /* Don't include \n at EOF in the blame line count. */
6524 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6525 blame->nlines--;
6527 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6528 if (blame->lines == NULL) {
6529 err = got_error_from_errno("calloc");
6530 goto done;
6533 err = got_repo_pack_fds_open(&pack_fds);
6534 if (err)
6535 goto done;
6536 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6537 pack_fds);
6538 if (err)
6539 goto done;
6541 blame->pack_fds = pack_fds;
6542 blame->cb_args.view = view;
6543 blame->cb_args.lines = blame->lines;
6544 blame->cb_args.nlines = blame->nlines;
6545 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6546 if (blame->cb_args.commit_id == NULL) {
6547 err = got_error_from_errno("got_object_id_dup");
6548 goto done;
6550 blame->cb_args.quit = &s->done;
6552 blame->thread_args.path = s->path;
6553 blame->thread_args.repo = thread_repo;
6554 blame->thread_args.cb_args = &blame->cb_args;
6555 blame->thread_args.complete = &s->blame_complete;
6556 blame->thread_args.cancel_cb = cancel_blame_view;
6557 blame->thread_args.cancel_arg = &s->done;
6558 s->blame_complete = 0;
6560 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6561 s->first_displayed_line = 1;
6562 s->last_displayed_line = view->nlines;
6563 s->selected_line = 1;
6565 s->matched_line = 0;
6567 done:
6568 if (commit)
6569 got_object_commit_close(commit);
6570 if (fd != -1 && close(fd) == -1 && err == NULL)
6571 err = got_error_from_errno("close");
6572 if (blob)
6573 got_object_blob_close(blob);
6574 free(obj_id);
6575 if (err)
6576 stop_blame(blame);
6577 return err;
6580 static const struct got_error *
6581 open_blame_view(struct tog_view *view, char *path,
6582 struct got_object_id *commit_id, struct got_repository *repo)
6584 const struct got_error *err = NULL;
6585 struct tog_blame_view_state *s = &view->state.blame;
6587 STAILQ_INIT(&s->blamed_commits);
6589 s->path = strdup(path);
6590 if (s->path == NULL)
6591 return got_error_from_errno("strdup");
6593 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6594 if (err) {
6595 free(s->path);
6596 return err;
6599 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6600 s->first_displayed_line = 1;
6601 s->last_displayed_line = view->nlines;
6602 s->selected_line = 1;
6603 s->blame_complete = 0;
6604 s->repo = repo;
6605 s->commit_id = commit_id;
6606 memset(&s->blame, 0, sizeof(s->blame));
6608 STAILQ_INIT(&s->colors);
6609 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6610 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6611 get_color_value("TOG_COLOR_COMMIT"));
6612 if (err)
6613 return err;
6616 view->show = show_blame_view;
6617 view->input = input_blame_view;
6618 view->reset = reset_blame_view;
6619 view->close = close_blame_view;
6620 view->search_start = search_start_blame_view;
6621 view->search_setup = search_setup_blame_view;
6622 view->search_next = search_next_view_match;
6624 if (using_mock_io) {
6625 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6626 int rc;
6628 rc = pthread_cond_init(&bta->blame_complete, NULL);
6629 if (rc)
6630 return got_error_set_errno(rc, "pthread_cond_init");
6633 return run_blame(view);
6636 static const struct got_error *
6637 close_blame_view(struct tog_view *view)
6639 const struct got_error *err = NULL;
6640 struct tog_blame_view_state *s = &view->state.blame;
6642 if (s->blame.thread)
6643 err = stop_blame(&s->blame);
6645 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6646 struct got_object_qid *blamed_commit;
6647 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6648 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6649 got_object_qid_free(blamed_commit);
6652 if (using_mock_io) {
6653 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6654 int rc;
6656 rc = pthread_cond_destroy(&bta->blame_complete);
6657 if (rc && err == NULL)
6658 err = got_error_set_errno(rc, "pthread_cond_destroy");
6661 free(s->path);
6662 free_colors(&s->colors);
6663 return err;
6666 static const struct got_error *
6667 search_start_blame_view(struct tog_view *view)
6669 struct tog_blame_view_state *s = &view->state.blame;
6671 s->matched_line = 0;
6672 return NULL;
6675 static void
6676 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6677 size_t *nlines, int **first, int **last, int **match, int **selected)
6679 struct tog_blame_view_state *s = &view->state.blame;
6681 *f = s->blame.f;
6682 *nlines = s->blame.nlines;
6683 *line_offsets = s->blame.line_offsets;
6684 *match = &s->matched_line;
6685 *first = &s->first_displayed_line;
6686 *last = &s->last_displayed_line;
6687 *selected = &s->selected_line;
6690 static const struct got_error *
6691 show_blame_view(struct tog_view *view)
6693 const struct got_error *err = NULL;
6694 struct tog_blame_view_state *s = &view->state.blame;
6695 int errcode;
6697 if (s->blame.thread == NULL && !s->blame_complete) {
6698 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6699 &s->blame.thread_args);
6700 if (errcode)
6701 return got_error_set_errno(errcode, "pthread_create");
6703 if (!using_mock_io)
6704 halfdelay(1); /* fast refresh while annotating */
6707 if (s->blame_complete && !using_mock_io)
6708 halfdelay(10); /* disable fast refresh */
6710 err = draw_blame(view);
6712 view_border(view);
6713 return err;
6716 static const struct got_error *
6717 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6718 struct got_repository *repo, struct got_object_id *id)
6720 struct tog_view *log_view;
6721 const struct got_error *err = NULL;
6723 *new_view = NULL;
6725 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6726 if (log_view == NULL)
6727 return got_error_from_errno("view_open");
6729 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6730 if (err)
6731 view_close(log_view);
6732 else
6733 *new_view = log_view;
6735 return err;
6738 static const struct got_error *
6739 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6741 const struct got_error *err = NULL, *thread_err = NULL;
6742 struct tog_view *diff_view;
6743 struct tog_blame_view_state *s = &view->state.blame;
6744 int eos, nscroll, begin_y = 0, begin_x = 0;
6746 eos = nscroll = view->nlines - 2;
6747 if (view_is_hsplit_top(view))
6748 --eos; /* border */
6750 switch (ch) {
6751 case '0':
6752 case '$':
6753 case KEY_RIGHT:
6754 case 'l':
6755 case KEY_LEFT:
6756 case 'h':
6757 horizontal_scroll_input(view, ch);
6758 break;
6759 case 'q':
6760 s->done = 1;
6761 break;
6762 case 'g':
6763 case KEY_HOME:
6764 s->selected_line = 1;
6765 s->first_displayed_line = 1;
6766 view->count = 0;
6767 break;
6768 case 'G':
6769 case KEY_END:
6770 if (s->blame.nlines < eos) {
6771 s->selected_line = s->blame.nlines;
6772 s->first_displayed_line = 1;
6773 } else {
6774 s->selected_line = eos;
6775 s->first_displayed_line = s->blame.nlines - (eos - 1);
6777 view->count = 0;
6778 break;
6779 case 'k':
6780 case KEY_UP:
6781 case CTRL('p'):
6782 if (s->selected_line > 1)
6783 s->selected_line--;
6784 else if (s->selected_line == 1 &&
6785 s->first_displayed_line > 1)
6786 s->first_displayed_line--;
6787 else
6788 view->count = 0;
6789 break;
6790 case CTRL('u'):
6791 case 'u':
6792 nscroll /= 2;
6793 /* FALL THROUGH */
6794 case KEY_PPAGE:
6795 case CTRL('b'):
6796 case 'b':
6797 if (s->first_displayed_line == 1) {
6798 if (view->count > 1)
6799 nscroll += nscroll;
6800 s->selected_line = MAX(1, s->selected_line - nscroll);
6801 view->count = 0;
6802 break;
6804 if (s->first_displayed_line > nscroll)
6805 s->first_displayed_line -= nscroll;
6806 else
6807 s->first_displayed_line = 1;
6808 break;
6809 case 'j':
6810 case KEY_DOWN:
6811 case CTRL('n'):
6812 if (s->selected_line < eos && s->first_displayed_line +
6813 s->selected_line <= s->blame.nlines)
6814 s->selected_line++;
6815 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6816 s->first_displayed_line++;
6817 else
6818 view->count = 0;
6819 break;
6820 case 'c':
6821 case 'p': {
6822 struct got_object_id *id = NULL;
6824 view->count = 0;
6825 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6826 s->first_displayed_line, s->selected_line);
6827 if (id == NULL)
6828 break;
6829 if (ch == 'p') {
6830 struct got_commit_object *commit, *pcommit;
6831 struct got_object_qid *pid;
6832 struct got_object_id *blob_id = NULL;
6833 int obj_type;
6834 err = got_object_open_as_commit(&commit,
6835 s->repo, id);
6836 if (err)
6837 break;
6838 pid = STAILQ_FIRST(
6839 got_object_commit_get_parent_ids(commit));
6840 if (pid == NULL) {
6841 got_object_commit_close(commit);
6842 break;
6844 /* Check if path history ends here. */
6845 err = got_object_open_as_commit(&pcommit,
6846 s->repo, &pid->id);
6847 if (err)
6848 break;
6849 err = got_object_id_by_path(&blob_id, s->repo,
6850 pcommit, s->path);
6851 got_object_commit_close(pcommit);
6852 if (err) {
6853 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6854 err = NULL;
6855 got_object_commit_close(commit);
6856 break;
6858 err = got_object_get_type(&obj_type, s->repo,
6859 blob_id);
6860 free(blob_id);
6861 /* Can't blame non-blob type objects. */
6862 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6863 got_object_commit_close(commit);
6864 break;
6866 err = got_object_qid_alloc(&s->blamed_commit,
6867 &pid->id);
6868 got_object_commit_close(commit);
6869 } else {
6870 if (got_object_id_cmp(id,
6871 &s->blamed_commit->id) == 0)
6872 break;
6873 err = got_object_qid_alloc(&s->blamed_commit,
6874 id);
6876 if (err)
6877 break;
6878 s->done = 1;
6879 thread_err = stop_blame(&s->blame);
6880 s->done = 0;
6881 if (thread_err)
6882 break;
6883 STAILQ_INSERT_HEAD(&s->blamed_commits,
6884 s->blamed_commit, entry);
6885 err = run_blame(view);
6886 if (err)
6887 break;
6888 break;
6890 case 'C': {
6891 struct got_object_qid *first;
6893 view->count = 0;
6894 first = STAILQ_FIRST(&s->blamed_commits);
6895 if (!got_object_id_cmp(&first->id, s->commit_id))
6896 break;
6897 s->done = 1;
6898 thread_err = stop_blame(&s->blame);
6899 s->done = 0;
6900 if (thread_err)
6901 break;
6902 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6903 got_object_qid_free(s->blamed_commit);
6904 s->blamed_commit =
6905 STAILQ_FIRST(&s->blamed_commits);
6906 err = run_blame(view);
6907 if (err)
6908 break;
6909 break;
6911 case 'L':
6912 view->count = 0;
6913 s->id_to_log = get_selected_commit_id(s->blame.lines,
6914 s->blame.nlines, s->first_displayed_line, s->selected_line);
6915 if (s->id_to_log)
6916 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6917 break;
6918 case KEY_ENTER:
6919 case '\r': {
6920 struct got_object_id *id = NULL;
6921 struct got_object_qid *pid;
6922 struct got_commit_object *commit = NULL;
6924 view->count = 0;
6925 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6926 s->first_displayed_line, s->selected_line);
6927 if (id == NULL)
6928 break;
6929 err = got_object_open_as_commit(&commit, s->repo, id);
6930 if (err)
6931 break;
6932 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6933 if (*new_view) {
6934 /* traversed from diff view, release diff resources */
6935 err = close_diff_view(*new_view);
6936 if (err)
6937 break;
6938 diff_view = *new_view;
6939 } else {
6940 if (view_is_parent_view(view))
6941 view_get_split(view, &begin_y, &begin_x);
6943 diff_view = view_open(0, 0, begin_y, begin_x,
6944 TOG_VIEW_DIFF);
6945 if (diff_view == NULL) {
6946 got_object_commit_close(commit);
6947 err = got_error_from_errno("view_open");
6948 break;
6951 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6952 id, NULL, NULL, 3, 0, 0, view, s->repo);
6953 got_object_commit_close(commit);
6954 if (err) {
6955 view_close(diff_view);
6956 break;
6958 s->last_diffed_line = s->first_displayed_line - 1 +
6959 s->selected_line;
6960 if (*new_view)
6961 break; /* still open from active diff view */
6962 if (view_is_parent_view(view) &&
6963 view->mode == TOG_VIEW_SPLIT_HRZN) {
6964 err = view_init_hsplit(view, begin_y);
6965 if (err)
6966 break;
6969 view->focussed = 0;
6970 diff_view->focussed = 1;
6971 diff_view->mode = view->mode;
6972 diff_view->nlines = view->lines - begin_y;
6973 if (view_is_parent_view(view)) {
6974 view_transfer_size(diff_view, view);
6975 err = view_close_child(view);
6976 if (err)
6977 break;
6978 err = view_set_child(view, diff_view);
6979 if (err)
6980 break;
6981 view->focus_child = 1;
6982 } else
6983 *new_view = diff_view;
6984 if (err)
6985 break;
6986 break;
6988 case CTRL('d'):
6989 case 'd':
6990 nscroll /= 2;
6991 /* FALL THROUGH */
6992 case KEY_NPAGE:
6993 case CTRL('f'):
6994 case 'f':
6995 case ' ':
6996 if (s->last_displayed_line >= s->blame.nlines &&
6997 s->selected_line >= MIN(s->blame.nlines,
6998 view->nlines - 2)) {
6999 view->count = 0;
7000 break;
7002 if (s->last_displayed_line >= s->blame.nlines &&
7003 s->selected_line < view->nlines - 2) {
7004 s->selected_line +=
7005 MIN(nscroll, s->last_displayed_line -
7006 s->first_displayed_line - s->selected_line + 1);
7008 if (s->last_displayed_line + nscroll <= s->blame.nlines)
7009 s->first_displayed_line += nscroll;
7010 else
7011 s->first_displayed_line =
7012 s->blame.nlines - (view->nlines - 3);
7013 break;
7014 case KEY_RESIZE:
7015 if (s->selected_line > view->nlines - 2) {
7016 s->selected_line = MIN(s->blame.nlines,
7017 view->nlines - 2);
7019 break;
7020 default:
7021 view->count = 0;
7022 break;
7024 return thread_err ? thread_err : err;
7027 static const struct got_error *
7028 reset_blame_view(struct tog_view *view)
7030 const struct got_error *err;
7031 struct tog_blame_view_state *s = &view->state.blame;
7033 view->count = 0;
7034 s->done = 1;
7035 err = stop_blame(&s->blame);
7036 s->done = 0;
7037 if (err)
7038 return err;
7039 return run_blame(view);
7042 static const struct got_error *
7043 cmd_blame(int argc, char *argv[])
7045 const struct got_error *error;
7046 struct got_repository *repo = NULL;
7047 struct got_worktree *worktree = NULL;
7048 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7049 char *link_target = NULL;
7050 struct got_object_id *commit_id = NULL;
7051 struct got_commit_object *commit = NULL;
7052 char *commit_id_str = NULL;
7053 int ch;
7054 struct tog_view *view = NULL;
7055 int *pack_fds = NULL;
7057 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7058 switch (ch) {
7059 case 'c':
7060 commit_id_str = optarg;
7061 break;
7062 case 'r':
7063 repo_path = realpath(optarg, NULL);
7064 if (repo_path == NULL)
7065 return got_error_from_errno2("realpath",
7066 optarg);
7067 break;
7068 default:
7069 usage_blame();
7070 /* NOTREACHED */
7074 argc -= optind;
7075 argv += optind;
7077 if (argc != 1)
7078 usage_blame();
7080 error = got_repo_pack_fds_open(&pack_fds);
7081 if (error != NULL)
7082 goto done;
7084 if (repo_path == NULL) {
7085 cwd = getcwd(NULL, 0);
7086 if (cwd == NULL)
7087 return got_error_from_errno("getcwd");
7088 error = got_worktree_open(&worktree, cwd);
7089 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7090 goto done;
7091 if (worktree)
7092 repo_path =
7093 strdup(got_worktree_get_repo_path(worktree));
7094 else
7095 repo_path = strdup(cwd);
7096 if (repo_path == NULL) {
7097 error = got_error_from_errno("strdup");
7098 goto done;
7102 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7103 if (error != NULL)
7104 goto done;
7106 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7107 worktree);
7108 if (error)
7109 goto done;
7111 init_curses();
7113 error = apply_unveil(got_repo_get_path(repo), NULL);
7114 if (error)
7115 goto done;
7117 error = tog_load_refs(repo, 0);
7118 if (error)
7119 goto done;
7121 if (commit_id_str == NULL) {
7122 struct got_reference *head_ref;
7123 error = got_ref_open(&head_ref, repo, worktree ?
7124 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7125 if (error != NULL)
7126 goto done;
7127 error = got_ref_resolve(&commit_id, repo, head_ref);
7128 got_ref_close(head_ref);
7129 } else {
7130 error = got_repo_match_object_id(&commit_id, NULL,
7131 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7133 if (error != NULL)
7134 goto done;
7136 error = got_object_open_as_commit(&commit, repo, commit_id);
7137 if (error)
7138 goto done;
7140 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7141 commit, repo);
7142 if (error)
7143 goto done;
7145 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7146 if (view == NULL) {
7147 error = got_error_from_errno("view_open");
7148 goto done;
7150 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7151 commit_id, repo);
7152 if (error != NULL) {
7153 if (view->close == NULL)
7154 close_blame_view(view);
7155 view_close(view);
7156 goto done;
7158 if (worktree) {
7159 /* Release work tree lock. */
7160 got_worktree_close(worktree);
7161 worktree = NULL;
7163 error = view_loop(view);
7164 done:
7165 free(repo_path);
7166 free(in_repo_path);
7167 free(link_target);
7168 free(cwd);
7169 free(commit_id);
7170 if (commit)
7171 got_object_commit_close(commit);
7172 if (worktree)
7173 got_worktree_close(worktree);
7174 if (repo) {
7175 const struct got_error *close_err = got_repo_close(repo);
7176 if (error == NULL)
7177 error = close_err;
7179 if (pack_fds) {
7180 const struct got_error *pack_err =
7181 got_repo_pack_fds_close(pack_fds);
7182 if (error == NULL)
7183 error = pack_err;
7185 tog_free_refs();
7186 return error;
7189 static const struct got_error *
7190 draw_tree_entries(struct tog_view *view, const char *parent_path)
7192 struct tog_tree_view_state *s = &view->state.tree;
7193 const struct got_error *err = NULL;
7194 struct got_tree_entry *te;
7195 wchar_t *wline;
7196 char *index = NULL;
7197 struct tog_color *tc;
7198 int width, n, nentries, scrollx, i = 1;
7199 int limit = view->nlines;
7201 s->ndisplayed = 0;
7202 if (view_is_hsplit_top(view))
7203 --limit; /* border */
7205 werase(view->window);
7207 if (limit == 0)
7208 return NULL;
7210 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7211 0, 0);
7212 if (err)
7213 return err;
7214 if (view_needs_focus_indication(view))
7215 wstandout(view->window);
7216 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7217 if (tc)
7218 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7219 waddwstr(view->window, wline);
7220 free(wline);
7221 wline = NULL;
7222 while (width++ < view->ncols)
7223 waddch(view->window, ' ');
7224 if (tc)
7225 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7226 if (view_needs_focus_indication(view))
7227 wstandend(view->window);
7228 if (--limit <= 0)
7229 return NULL;
7231 i += s->selected;
7232 if (s->first_displayed_entry) {
7233 i += got_tree_entry_get_index(s->first_displayed_entry);
7234 if (s->tree != s->root)
7235 ++i; /* account for ".." entry */
7237 nentries = got_object_tree_get_nentries(s->tree);
7238 if (asprintf(&index, "[%d/%d] %s",
7239 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7240 return got_error_from_errno("asprintf");
7241 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7242 free(index);
7243 if (err)
7244 return err;
7245 waddwstr(view->window, wline);
7246 free(wline);
7247 wline = NULL;
7248 if (width < view->ncols - 1)
7249 waddch(view->window, '\n');
7250 if (--limit <= 0)
7251 return NULL;
7252 waddch(view->window, '\n');
7253 if (--limit <= 0)
7254 return NULL;
7256 if (s->first_displayed_entry == NULL) {
7257 te = got_object_tree_get_first_entry(s->tree);
7258 if (s->selected == 0) {
7259 if (view->focussed)
7260 wstandout(view->window);
7261 s->selected_entry = NULL;
7263 waddstr(view->window, " ..\n"); /* parent directory */
7264 if (s->selected == 0 && view->focussed)
7265 wstandend(view->window);
7266 s->ndisplayed++;
7267 if (--limit <= 0)
7268 return NULL;
7269 n = 1;
7270 } else {
7271 n = 0;
7272 te = s->first_displayed_entry;
7275 view->maxx = 0;
7276 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7277 char *line = NULL, *id_str = NULL, *link_target = NULL;
7278 const char *modestr = "";
7279 mode_t mode;
7281 te = got_object_tree_get_entry(s->tree, i);
7282 mode = got_tree_entry_get_mode(te);
7284 if (s->show_ids) {
7285 err = got_object_id_str(&id_str,
7286 got_tree_entry_get_id(te));
7287 if (err)
7288 return got_error_from_errno(
7289 "got_object_id_str");
7291 if (got_object_tree_entry_is_submodule(te))
7292 modestr = "$";
7293 else if (S_ISLNK(mode)) {
7294 int i;
7296 err = got_tree_entry_get_symlink_target(&link_target,
7297 te, s->repo);
7298 if (err) {
7299 free(id_str);
7300 return err;
7302 for (i = 0; i < strlen(link_target); i++) {
7303 if (!isprint((unsigned char)link_target[i]))
7304 link_target[i] = '?';
7306 modestr = "@";
7308 else if (S_ISDIR(mode))
7309 modestr = "/";
7310 else if (mode & S_IXUSR)
7311 modestr = "*";
7312 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7313 got_tree_entry_get_name(te), modestr,
7314 link_target ? " -> ": "",
7315 link_target ? link_target : "") == -1) {
7316 free(id_str);
7317 free(link_target);
7318 return got_error_from_errno("asprintf");
7320 free(id_str);
7321 free(link_target);
7323 /* use full line width to determine view->maxx */
7324 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7325 if (err) {
7326 free(line);
7327 break;
7329 view->maxx = MAX(view->maxx, width);
7330 free(wline);
7331 wline = NULL;
7333 err = format_line(&wline, &width, &scrollx, line, view->x,
7334 view->ncols, 0, 0);
7335 if (err) {
7336 free(line);
7337 break;
7339 if (n == s->selected) {
7340 if (view->focussed)
7341 wstandout(view->window);
7342 s->selected_entry = te;
7344 tc = match_color(&s->colors, line);
7345 if (tc)
7346 wattr_on(view->window,
7347 COLOR_PAIR(tc->colorpair), NULL);
7348 waddwstr(view->window, &wline[scrollx]);
7349 if (tc)
7350 wattr_off(view->window,
7351 COLOR_PAIR(tc->colorpair), NULL);
7352 if (width < view->ncols)
7353 waddch(view->window, '\n');
7354 if (n == s->selected && view->focussed)
7355 wstandend(view->window);
7356 free(line);
7357 free(wline);
7358 wline = NULL;
7359 n++;
7360 s->ndisplayed++;
7361 s->last_displayed_entry = te;
7362 if (--limit <= 0)
7363 break;
7366 return err;
7369 static void
7370 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7372 struct got_tree_entry *te;
7373 int isroot = s->tree == s->root;
7374 int i = 0;
7376 if (s->first_displayed_entry == NULL)
7377 return;
7379 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7380 while (i++ < maxscroll) {
7381 if (te == NULL) {
7382 if (!isroot)
7383 s->first_displayed_entry = NULL;
7384 break;
7386 s->first_displayed_entry = te;
7387 te = got_tree_entry_get_prev(s->tree, te);
7391 static const struct got_error *
7392 tree_scroll_down(struct tog_view *view, int maxscroll)
7394 struct tog_tree_view_state *s = &view->state.tree;
7395 struct got_tree_entry *next, *last;
7396 int n = 0;
7398 if (s->first_displayed_entry)
7399 next = got_tree_entry_get_next(s->tree,
7400 s->first_displayed_entry);
7401 else
7402 next = got_object_tree_get_first_entry(s->tree);
7404 last = s->last_displayed_entry;
7405 while (next && n++ < maxscroll) {
7406 if (last) {
7407 s->last_displayed_entry = last;
7408 last = got_tree_entry_get_next(s->tree, last);
7410 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7411 s->first_displayed_entry = next;
7412 next = got_tree_entry_get_next(s->tree, next);
7416 return NULL;
7419 static const struct got_error *
7420 tree_entry_path(char **path, struct tog_parent_trees *parents,
7421 struct got_tree_entry *te)
7423 const struct got_error *err = NULL;
7424 struct tog_parent_tree *pt;
7425 size_t len = 2; /* for leading slash and NUL */
7427 TAILQ_FOREACH(pt, parents, entry)
7428 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7429 + 1 /* slash */;
7430 if (te)
7431 len += strlen(got_tree_entry_get_name(te));
7433 *path = calloc(1, len);
7434 if (path == NULL)
7435 return got_error_from_errno("calloc");
7437 (*path)[0] = '/';
7438 pt = TAILQ_LAST(parents, tog_parent_trees);
7439 while (pt) {
7440 const char *name = got_tree_entry_get_name(pt->selected_entry);
7441 if (strlcat(*path, name, len) >= len) {
7442 err = got_error(GOT_ERR_NO_SPACE);
7443 goto done;
7445 if (strlcat(*path, "/", len) >= len) {
7446 err = got_error(GOT_ERR_NO_SPACE);
7447 goto done;
7449 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7451 if (te) {
7452 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7453 err = got_error(GOT_ERR_NO_SPACE);
7454 goto done;
7457 done:
7458 if (err) {
7459 free(*path);
7460 *path = NULL;
7462 return err;
7465 static const struct got_error *
7466 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7467 struct got_tree_entry *te, struct tog_parent_trees *parents,
7468 struct got_object_id *commit_id, struct got_repository *repo)
7470 const struct got_error *err = NULL;
7471 char *path;
7472 struct tog_view *blame_view;
7474 *new_view = NULL;
7476 err = tree_entry_path(&path, parents, te);
7477 if (err)
7478 return err;
7480 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7481 if (blame_view == NULL) {
7482 err = got_error_from_errno("view_open");
7483 goto done;
7486 err = open_blame_view(blame_view, path, commit_id, repo);
7487 if (err) {
7488 if (err->code == GOT_ERR_CANCELLED)
7489 err = NULL;
7490 view_close(blame_view);
7491 } else
7492 *new_view = blame_view;
7493 done:
7494 free(path);
7495 return err;
7498 static const struct got_error *
7499 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7500 struct tog_tree_view_state *s)
7502 struct tog_view *log_view;
7503 const struct got_error *err = NULL;
7504 char *path;
7506 *new_view = NULL;
7508 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7509 if (log_view == NULL)
7510 return got_error_from_errno("view_open");
7512 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7513 if (err)
7514 return err;
7516 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7517 path, 0);
7518 if (err)
7519 view_close(log_view);
7520 else
7521 *new_view = log_view;
7522 free(path);
7523 return err;
7526 static const struct got_error *
7527 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7528 const char *head_ref_name, struct got_repository *repo)
7530 const struct got_error *err = NULL;
7531 char *commit_id_str = NULL;
7532 struct tog_tree_view_state *s = &view->state.tree;
7533 struct got_commit_object *commit = NULL;
7535 TAILQ_INIT(&s->parents);
7536 STAILQ_INIT(&s->colors);
7538 s->commit_id = got_object_id_dup(commit_id);
7539 if (s->commit_id == NULL) {
7540 err = got_error_from_errno("got_object_id_dup");
7541 goto done;
7544 err = got_object_open_as_commit(&commit, repo, commit_id);
7545 if (err)
7546 goto done;
7549 * The root is opened here and will be closed when the view is closed.
7550 * Any visited subtrees and their path-wise parents are opened and
7551 * closed on demand.
7553 err = got_object_open_as_tree(&s->root, repo,
7554 got_object_commit_get_tree_id(commit));
7555 if (err)
7556 goto done;
7557 s->tree = s->root;
7559 err = got_object_id_str(&commit_id_str, commit_id);
7560 if (err != NULL)
7561 goto done;
7563 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7564 err = got_error_from_errno("asprintf");
7565 goto done;
7568 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7569 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7570 if (head_ref_name) {
7571 s->head_ref_name = strdup(head_ref_name);
7572 if (s->head_ref_name == NULL) {
7573 err = got_error_from_errno("strdup");
7574 goto done;
7577 s->repo = repo;
7579 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7580 err = add_color(&s->colors, "\\$$",
7581 TOG_COLOR_TREE_SUBMODULE,
7582 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7583 if (err)
7584 goto done;
7585 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7586 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7587 if (err)
7588 goto done;
7589 err = add_color(&s->colors, "/$",
7590 TOG_COLOR_TREE_DIRECTORY,
7591 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7592 if (err)
7593 goto done;
7595 err = add_color(&s->colors, "\\*$",
7596 TOG_COLOR_TREE_EXECUTABLE,
7597 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7598 if (err)
7599 goto done;
7601 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7602 get_color_value("TOG_COLOR_COMMIT"));
7603 if (err)
7604 goto done;
7607 view->show = show_tree_view;
7608 view->input = input_tree_view;
7609 view->close = close_tree_view;
7610 view->search_start = search_start_tree_view;
7611 view->search_next = search_next_tree_view;
7612 done:
7613 free(commit_id_str);
7614 if (commit)
7615 got_object_commit_close(commit);
7616 if (err) {
7617 if (view->close == NULL)
7618 close_tree_view(view);
7619 view_close(view);
7621 return err;
7624 static const struct got_error *
7625 close_tree_view(struct tog_view *view)
7627 struct tog_tree_view_state *s = &view->state.tree;
7629 free_colors(&s->colors);
7630 free(s->tree_label);
7631 s->tree_label = NULL;
7632 free(s->commit_id);
7633 s->commit_id = NULL;
7634 free(s->head_ref_name);
7635 s->head_ref_name = NULL;
7636 while (!TAILQ_EMPTY(&s->parents)) {
7637 struct tog_parent_tree *parent;
7638 parent = TAILQ_FIRST(&s->parents);
7639 TAILQ_REMOVE(&s->parents, parent, entry);
7640 if (parent->tree != s->root)
7641 got_object_tree_close(parent->tree);
7642 free(parent);
7645 if (s->tree != NULL && s->tree != s->root)
7646 got_object_tree_close(s->tree);
7647 if (s->root)
7648 got_object_tree_close(s->root);
7649 return NULL;
7652 static const struct got_error *
7653 search_start_tree_view(struct tog_view *view)
7655 struct tog_tree_view_state *s = &view->state.tree;
7657 s->matched_entry = NULL;
7658 return NULL;
7661 static int
7662 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7664 regmatch_t regmatch;
7666 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7667 0) == 0;
7670 static const struct got_error *
7671 search_next_tree_view(struct tog_view *view)
7673 struct tog_tree_view_state *s = &view->state.tree;
7674 struct got_tree_entry *te = NULL;
7676 if (!view->searching) {
7677 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7678 return NULL;
7681 if (s->matched_entry) {
7682 if (view->searching == TOG_SEARCH_FORWARD) {
7683 if (s->selected_entry)
7684 te = got_tree_entry_get_next(s->tree,
7685 s->selected_entry);
7686 else
7687 te = got_object_tree_get_first_entry(s->tree);
7688 } else {
7689 if (s->selected_entry == NULL)
7690 te = got_object_tree_get_last_entry(s->tree);
7691 else
7692 te = got_tree_entry_get_prev(s->tree,
7693 s->selected_entry);
7695 } else {
7696 if (s->selected_entry)
7697 te = s->selected_entry;
7698 else if (view->searching == TOG_SEARCH_FORWARD)
7699 te = got_object_tree_get_first_entry(s->tree);
7700 else
7701 te = got_object_tree_get_last_entry(s->tree);
7704 while (1) {
7705 if (te == NULL) {
7706 if (s->matched_entry == NULL) {
7707 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7708 return NULL;
7710 if (view->searching == TOG_SEARCH_FORWARD)
7711 te = got_object_tree_get_first_entry(s->tree);
7712 else
7713 te = got_object_tree_get_last_entry(s->tree);
7716 if (match_tree_entry(te, &view->regex)) {
7717 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7718 s->matched_entry = te;
7719 break;
7722 if (view->searching == TOG_SEARCH_FORWARD)
7723 te = got_tree_entry_get_next(s->tree, te);
7724 else
7725 te = got_tree_entry_get_prev(s->tree, te);
7728 if (s->matched_entry) {
7729 s->first_displayed_entry = s->matched_entry;
7730 s->selected = 0;
7733 return NULL;
7736 static const struct got_error *
7737 show_tree_view(struct tog_view *view)
7739 const struct got_error *err = NULL;
7740 struct tog_tree_view_state *s = &view->state.tree;
7741 char *parent_path;
7743 err = tree_entry_path(&parent_path, &s->parents, NULL);
7744 if (err)
7745 return err;
7747 err = draw_tree_entries(view, parent_path);
7748 free(parent_path);
7750 view_border(view);
7751 return err;
7754 static const struct got_error *
7755 tree_goto_line(struct tog_view *view, int nlines)
7757 const struct got_error *err = NULL;
7758 struct tog_tree_view_state *s = &view->state.tree;
7759 struct got_tree_entry **fte, **lte, **ste;
7760 int g, last, first = 1, i = 1;
7761 int root = s->tree == s->root;
7762 int off = root ? 1 : 2;
7764 g = view->gline;
7765 view->gline = 0;
7767 if (g == 0)
7768 g = 1;
7769 else if (g > got_object_tree_get_nentries(s->tree))
7770 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7772 fte = &s->first_displayed_entry;
7773 lte = &s->last_displayed_entry;
7774 ste = &s->selected_entry;
7776 if (*fte != NULL) {
7777 first = got_tree_entry_get_index(*fte);
7778 first += off; /* account for ".." */
7780 last = got_tree_entry_get_index(*lte);
7781 last += off;
7783 if (g >= first && g <= last && g - first < nlines) {
7784 s->selected = g - first;
7785 return NULL; /* gline is on the current page */
7788 if (*ste != NULL) {
7789 i = got_tree_entry_get_index(*ste);
7790 i += off;
7793 if (i < g) {
7794 err = tree_scroll_down(view, g - i);
7795 if (err)
7796 return err;
7797 if (got_tree_entry_get_index(*lte) >=
7798 got_object_tree_get_nentries(s->tree) - 1 &&
7799 first + s->selected < g &&
7800 s->selected < s->ndisplayed - 1) {
7801 first = got_tree_entry_get_index(*fte);
7802 first += off;
7803 s->selected = g - first;
7805 } else if (i > g)
7806 tree_scroll_up(s, i - g);
7808 if (g < nlines &&
7809 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7810 s->selected = g - 1;
7812 return NULL;
7815 static const struct got_error *
7816 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7818 const struct got_error *err = NULL;
7819 struct tog_tree_view_state *s = &view->state.tree;
7820 struct got_tree_entry *te;
7821 int n, nscroll = view->nlines - 3;
7823 if (view->gline)
7824 return tree_goto_line(view, nscroll);
7826 switch (ch) {
7827 case '0':
7828 case '$':
7829 case KEY_RIGHT:
7830 case 'l':
7831 case KEY_LEFT:
7832 case 'h':
7833 horizontal_scroll_input(view, ch);
7834 break;
7835 case 'i':
7836 s->show_ids = !s->show_ids;
7837 view->count = 0;
7838 break;
7839 case 'L':
7840 view->count = 0;
7841 if (!s->selected_entry)
7842 break;
7843 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7844 break;
7845 case 'R':
7846 view->count = 0;
7847 err = view_request_new(new_view, view, TOG_VIEW_REF);
7848 break;
7849 case 'g':
7850 case '=':
7851 case KEY_HOME:
7852 s->selected = 0;
7853 view->count = 0;
7854 if (s->tree == s->root)
7855 s->first_displayed_entry =
7856 got_object_tree_get_first_entry(s->tree);
7857 else
7858 s->first_displayed_entry = NULL;
7859 break;
7860 case 'G':
7861 case '*':
7862 case KEY_END: {
7863 int eos = view->nlines - 3;
7865 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7866 --eos; /* border */
7867 s->selected = 0;
7868 view->count = 0;
7869 te = got_object_tree_get_last_entry(s->tree);
7870 for (n = 0; n < eos; n++) {
7871 if (te == NULL) {
7872 if (s->tree != s->root) {
7873 s->first_displayed_entry = NULL;
7874 n++;
7876 break;
7878 s->first_displayed_entry = te;
7879 te = got_tree_entry_get_prev(s->tree, te);
7881 if (n > 0)
7882 s->selected = n - 1;
7883 break;
7885 case 'k':
7886 case KEY_UP:
7887 case CTRL('p'):
7888 if (s->selected > 0) {
7889 s->selected--;
7890 break;
7892 tree_scroll_up(s, 1);
7893 if (s->selected_entry == NULL ||
7894 (s->tree == s->root && s->selected_entry ==
7895 got_object_tree_get_first_entry(s->tree)))
7896 view->count = 0;
7897 break;
7898 case CTRL('u'):
7899 case 'u':
7900 nscroll /= 2;
7901 /* FALL THROUGH */
7902 case KEY_PPAGE:
7903 case CTRL('b'):
7904 case 'b':
7905 if (s->tree == s->root) {
7906 if (got_object_tree_get_first_entry(s->tree) ==
7907 s->first_displayed_entry)
7908 s->selected -= MIN(s->selected, nscroll);
7909 } else {
7910 if (s->first_displayed_entry == NULL)
7911 s->selected -= MIN(s->selected, nscroll);
7913 tree_scroll_up(s, MAX(0, nscroll));
7914 if (s->selected_entry == NULL ||
7915 (s->tree == s->root && s->selected_entry ==
7916 got_object_tree_get_first_entry(s->tree)))
7917 view->count = 0;
7918 break;
7919 case 'j':
7920 case KEY_DOWN:
7921 case CTRL('n'):
7922 if (s->selected < s->ndisplayed - 1) {
7923 s->selected++;
7924 break;
7926 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7927 == NULL) {
7928 /* can't scroll any further */
7929 view->count = 0;
7930 break;
7932 tree_scroll_down(view, 1);
7933 break;
7934 case CTRL('d'):
7935 case 'd':
7936 nscroll /= 2;
7937 /* FALL THROUGH */
7938 case KEY_NPAGE:
7939 case CTRL('f'):
7940 case 'f':
7941 case ' ':
7942 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7943 == NULL) {
7944 /* can't scroll any further; move cursor down */
7945 if (s->selected < s->ndisplayed - 1)
7946 s->selected += MIN(nscroll,
7947 s->ndisplayed - s->selected - 1);
7948 else
7949 view->count = 0;
7950 break;
7952 tree_scroll_down(view, nscroll);
7953 break;
7954 case KEY_ENTER:
7955 case '\r':
7956 case KEY_BACKSPACE:
7957 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7958 struct tog_parent_tree *parent;
7959 /* user selected '..' */
7960 if (s->tree == s->root) {
7961 view->count = 0;
7962 break;
7964 parent = TAILQ_FIRST(&s->parents);
7965 TAILQ_REMOVE(&s->parents, parent,
7966 entry);
7967 got_object_tree_close(s->tree);
7968 s->tree = parent->tree;
7969 s->first_displayed_entry =
7970 parent->first_displayed_entry;
7971 s->selected_entry =
7972 parent->selected_entry;
7973 s->selected = parent->selected;
7974 if (s->selected > view->nlines - 3) {
7975 err = offset_selection_down(view);
7976 if (err)
7977 break;
7979 free(parent);
7980 } else if (S_ISDIR(got_tree_entry_get_mode(
7981 s->selected_entry))) {
7982 struct got_tree_object *subtree;
7983 view->count = 0;
7984 err = got_object_open_as_tree(&subtree, s->repo,
7985 got_tree_entry_get_id(s->selected_entry));
7986 if (err)
7987 break;
7988 err = tree_view_visit_subtree(s, subtree);
7989 if (err) {
7990 got_object_tree_close(subtree);
7991 break;
7993 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7994 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7995 break;
7996 case KEY_RESIZE:
7997 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7998 s->selected = view->nlines - 4;
7999 view->count = 0;
8000 break;
8001 default:
8002 view->count = 0;
8003 break;
8006 return err;
8009 __dead static void
8010 usage_tree(void)
8012 endwin();
8013 fprintf(stderr,
8014 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
8015 getprogname());
8016 exit(1);
8019 static const struct got_error *
8020 cmd_tree(int argc, char *argv[])
8022 const struct got_error *error;
8023 struct got_repository *repo = NULL;
8024 struct got_worktree *worktree = NULL;
8025 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8026 struct got_object_id *commit_id = NULL;
8027 struct got_commit_object *commit = NULL;
8028 const char *commit_id_arg = NULL;
8029 char *label = NULL;
8030 struct got_reference *ref = NULL;
8031 const char *head_ref_name = NULL;
8032 int ch;
8033 struct tog_view *view;
8034 int *pack_fds = NULL;
8036 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
8037 switch (ch) {
8038 case 'c':
8039 commit_id_arg = optarg;
8040 break;
8041 case 'r':
8042 repo_path = realpath(optarg, NULL);
8043 if (repo_path == NULL)
8044 return got_error_from_errno2("realpath",
8045 optarg);
8046 break;
8047 default:
8048 usage_tree();
8049 /* NOTREACHED */
8053 argc -= optind;
8054 argv += optind;
8056 if (argc > 1)
8057 usage_tree();
8059 error = got_repo_pack_fds_open(&pack_fds);
8060 if (error != NULL)
8061 goto done;
8063 if (repo_path == NULL) {
8064 cwd = getcwd(NULL, 0);
8065 if (cwd == NULL)
8066 return got_error_from_errno("getcwd");
8067 error = got_worktree_open(&worktree, cwd);
8068 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8069 goto done;
8070 if (worktree)
8071 repo_path =
8072 strdup(got_worktree_get_repo_path(worktree));
8073 else
8074 repo_path = strdup(cwd);
8075 if (repo_path == NULL) {
8076 error = got_error_from_errno("strdup");
8077 goto done;
8081 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8082 if (error != NULL)
8083 goto done;
8085 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8086 repo, worktree);
8087 if (error)
8088 goto done;
8090 init_curses();
8092 error = apply_unveil(got_repo_get_path(repo), NULL);
8093 if (error)
8094 goto done;
8096 error = tog_load_refs(repo, 0);
8097 if (error)
8098 goto done;
8100 if (commit_id_arg == NULL) {
8101 error = got_repo_match_object_id(&commit_id, &label,
8102 worktree ? got_worktree_get_head_ref_name(worktree) :
8103 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8104 if (error)
8105 goto done;
8106 head_ref_name = label;
8107 } else {
8108 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8109 if (error == NULL)
8110 head_ref_name = got_ref_get_name(ref);
8111 else if (error->code != GOT_ERR_NOT_REF)
8112 goto done;
8113 error = got_repo_match_object_id(&commit_id, NULL,
8114 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8115 if (error)
8116 goto done;
8119 error = got_object_open_as_commit(&commit, repo, commit_id);
8120 if (error)
8121 goto done;
8123 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8124 if (view == NULL) {
8125 error = got_error_from_errno("view_open");
8126 goto done;
8128 error = open_tree_view(view, commit_id, head_ref_name, repo);
8129 if (error)
8130 goto done;
8131 if (!got_path_is_root_dir(in_repo_path)) {
8132 error = tree_view_walk_path(&view->state.tree, commit,
8133 in_repo_path);
8134 if (error)
8135 goto done;
8138 if (worktree) {
8139 /* Release work tree lock. */
8140 got_worktree_close(worktree);
8141 worktree = NULL;
8143 error = view_loop(view);
8144 done:
8145 free(repo_path);
8146 free(cwd);
8147 free(commit_id);
8148 free(label);
8149 if (ref)
8150 got_ref_close(ref);
8151 if (repo) {
8152 const struct got_error *close_err = got_repo_close(repo);
8153 if (error == NULL)
8154 error = close_err;
8156 if (pack_fds) {
8157 const struct got_error *pack_err =
8158 got_repo_pack_fds_close(pack_fds);
8159 if (error == NULL)
8160 error = pack_err;
8162 tog_free_refs();
8163 return error;
8166 static const struct got_error *
8167 ref_view_load_refs(struct tog_ref_view_state *s)
8169 struct got_reflist_entry *sre;
8170 struct tog_reflist_entry *re;
8172 s->nrefs = 0;
8173 TAILQ_FOREACH(sre, &tog_refs, entry) {
8174 if (strncmp(got_ref_get_name(sre->ref),
8175 "refs/got/", 9) == 0 &&
8176 strncmp(got_ref_get_name(sre->ref),
8177 "refs/got/backup/", 16) != 0)
8178 continue;
8180 re = malloc(sizeof(*re));
8181 if (re == NULL)
8182 return got_error_from_errno("malloc");
8184 re->ref = got_ref_dup(sre->ref);
8185 if (re->ref == NULL)
8186 return got_error_from_errno("got_ref_dup");
8187 re->idx = s->nrefs++;
8188 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8191 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8192 return NULL;
8195 static void
8196 ref_view_free_refs(struct tog_ref_view_state *s)
8198 struct tog_reflist_entry *re;
8200 while (!TAILQ_EMPTY(&s->refs)) {
8201 re = TAILQ_FIRST(&s->refs);
8202 TAILQ_REMOVE(&s->refs, re, entry);
8203 got_ref_close(re->ref);
8204 free(re);
8208 static const struct got_error *
8209 open_ref_view(struct tog_view *view, struct got_repository *repo)
8211 const struct got_error *err = NULL;
8212 struct tog_ref_view_state *s = &view->state.ref;
8214 s->selected_entry = 0;
8215 s->repo = repo;
8217 TAILQ_INIT(&s->refs);
8218 STAILQ_INIT(&s->colors);
8220 err = ref_view_load_refs(s);
8221 if (err)
8222 goto done;
8224 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8225 err = add_color(&s->colors, "^refs/heads/",
8226 TOG_COLOR_REFS_HEADS,
8227 get_color_value("TOG_COLOR_REFS_HEADS"));
8228 if (err)
8229 goto done;
8231 err = add_color(&s->colors, "^refs/tags/",
8232 TOG_COLOR_REFS_TAGS,
8233 get_color_value("TOG_COLOR_REFS_TAGS"));
8234 if (err)
8235 goto done;
8237 err = add_color(&s->colors, "^refs/remotes/",
8238 TOG_COLOR_REFS_REMOTES,
8239 get_color_value("TOG_COLOR_REFS_REMOTES"));
8240 if (err)
8241 goto done;
8243 err = add_color(&s->colors, "^refs/got/backup/",
8244 TOG_COLOR_REFS_BACKUP,
8245 get_color_value("TOG_COLOR_REFS_BACKUP"));
8246 if (err)
8247 goto done;
8250 view->show = show_ref_view;
8251 view->input = input_ref_view;
8252 view->close = close_ref_view;
8253 view->search_start = search_start_ref_view;
8254 view->search_next = search_next_ref_view;
8255 done:
8256 if (err) {
8257 if (view->close == NULL)
8258 close_ref_view(view);
8259 view_close(view);
8261 return err;
8264 static const struct got_error *
8265 close_ref_view(struct tog_view *view)
8267 struct tog_ref_view_state *s = &view->state.ref;
8269 ref_view_free_refs(s);
8270 free_colors(&s->colors);
8272 return NULL;
8275 static const struct got_error *
8276 resolve_reflist_entry(struct got_object_id **commit_id,
8277 struct tog_reflist_entry *re, struct got_repository *repo)
8279 const struct got_error *err = NULL;
8280 struct got_object_id *obj_id;
8281 struct got_tag_object *tag = NULL;
8282 int obj_type;
8284 *commit_id = NULL;
8286 err = got_ref_resolve(&obj_id, repo, re->ref);
8287 if (err)
8288 return err;
8290 err = got_object_get_type(&obj_type, repo, obj_id);
8291 if (err)
8292 goto done;
8294 switch (obj_type) {
8295 case GOT_OBJ_TYPE_COMMIT:
8296 *commit_id = obj_id;
8297 break;
8298 case GOT_OBJ_TYPE_TAG:
8299 err = got_object_open_as_tag(&tag, repo, obj_id);
8300 if (err)
8301 goto done;
8302 free(obj_id);
8303 err = got_object_get_type(&obj_type, repo,
8304 got_object_tag_get_object_id(tag));
8305 if (err)
8306 goto done;
8307 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8308 err = got_error(GOT_ERR_OBJ_TYPE);
8309 goto done;
8311 *commit_id = got_object_id_dup(
8312 got_object_tag_get_object_id(tag));
8313 if (*commit_id == NULL) {
8314 err = got_error_from_errno("got_object_id_dup");
8315 goto done;
8317 break;
8318 default:
8319 err = got_error(GOT_ERR_OBJ_TYPE);
8320 break;
8323 done:
8324 if (tag)
8325 got_object_tag_close(tag);
8326 if (err) {
8327 free(*commit_id);
8328 *commit_id = NULL;
8330 return err;
8333 static const struct got_error *
8334 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8335 struct tog_reflist_entry *re, struct got_repository *repo)
8337 struct tog_view *log_view;
8338 const struct got_error *err = NULL;
8339 struct got_object_id *commit_id = NULL;
8341 *new_view = NULL;
8343 err = resolve_reflist_entry(&commit_id, re, repo);
8344 if (err) {
8345 if (err->code != GOT_ERR_OBJ_TYPE)
8346 return err;
8347 else
8348 return NULL;
8351 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8352 if (log_view == NULL) {
8353 err = got_error_from_errno("view_open");
8354 goto done;
8357 err = open_log_view(log_view, commit_id, repo,
8358 got_ref_get_name(re->ref), "", 0);
8359 done:
8360 if (err)
8361 view_close(log_view);
8362 else
8363 *new_view = log_view;
8364 free(commit_id);
8365 return err;
8368 static void
8369 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8371 struct tog_reflist_entry *re;
8372 int i = 0;
8374 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8375 return;
8377 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8378 while (i++ < maxscroll) {
8379 if (re == NULL)
8380 break;
8381 s->first_displayed_entry = re;
8382 re = TAILQ_PREV(re, tog_reflist_head, entry);
8386 static const struct got_error *
8387 ref_scroll_down(struct tog_view *view, int maxscroll)
8389 struct tog_ref_view_state *s = &view->state.ref;
8390 struct tog_reflist_entry *next, *last;
8391 int n = 0;
8393 if (s->first_displayed_entry)
8394 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8395 else
8396 next = TAILQ_FIRST(&s->refs);
8398 last = s->last_displayed_entry;
8399 while (next && n++ < maxscroll) {
8400 if (last) {
8401 s->last_displayed_entry = last;
8402 last = TAILQ_NEXT(last, entry);
8404 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8405 s->first_displayed_entry = next;
8406 next = TAILQ_NEXT(next, entry);
8410 return NULL;
8413 static const struct got_error *
8414 search_start_ref_view(struct tog_view *view)
8416 struct tog_ref_view_state *s = &view->state.ref;
8418 s->matched_entry = NULL;
8419 return NULL;
8422 static int
8423 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8425 regmatch_t regmatch;
8427 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8428 0) == 0;
8431 static const struct got_error *
8432 search_next_ref_view(struct tog_view *view)
8434 struct tog_ref_view_state *s = &view->state.ref;
8435 struct tog_reflist_entry *re = NULL;
8437 if (!view->searching) {
8438 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8439 return NULL;
8442 if (s->matched_entry) {
8443 if (view->searching == TOG_SEARCH_FORWARD) {
8444 if (s->selected_entry)
8445 re = TAILQ_NEXT(s->selected_entry, entry);
8446 else
8447 re = TAILQ_PREV(s->selected_entry,
8448 tog_reflist_head, entry);
8449 } else {
8450 if (s->selected_entry == NULL)
8451 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8452 else
8453 re = TAILQ_PREV(s->selected_entry,
8454 tog_reflist_head, entry);
8456 } else {
8457 if (s->selected_entry)
8458 re = s->selected_entry;
8459 else if (view->searching == TOG_SEARCH_FORWARD)
8460 re = TAILQ_FIRST(&s->refs);
8461 else
8462 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8465 while (1) {
8466 if (re == NULL) {
8467 if (s->matched_entry == NULL) {
8468 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8469 return NULL;
8471 if (view->searching == TOG_SEARCH_FORWARD)
8472 re = TAILQ_FIRST(&s->refs);
8473 else
8474 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8477 if (match_reflist_entry(re, &view->regex)) {
8478 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8479 s->matched_entry = re;
8480 break;
8483 if (view->searching == TOG_SEARCH_FORWARD)
8484 re = TAILQ_NEXT(re, entry);
8485 else
8486 re = TAILQ_PREV(re, tog_reflist_head, entry);
8489 if (s->matched_entry) {
8490 s->first_displayed_entry = s->matched_entry;
8491 s->selected = 0;
8494 return NULL;
8497 static const struct got_error *
8498 show_ref_view(struct tog_view *view)
8500 const struct got_error *err = NULL;
8501 struct tog_ref_view_state *s = &view->state.ref;
8502 struct tog_reflist_entry *re;
8503 char *line = NULL;
8504 wchar_t *wline;
8505 struct tog_color *tc;
8506 int width, n, scrollx;
8507 int limit = view->nlines;
8509 werase(view->window);
8511 s->ndisplayed = 0;
8512 if (view_is_hsplit_top(view))
8513 --limit; /* border */
8515 if (limit == 0)
8516 return NULL;
8518 re = s->first_displayed_entry;
8520 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8521 s->nrefs) == -1)
8522 return got_error_from_errno("asprintf");
8524 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8525 if (err) {
8526 free(line);
8527 return err;
8529 if (view_needs_focus_indication(view))
8530 wstandout(view->window);
8531 waddwstr(view->window, wline);
8532 while (width++ < view->ncols)
8533 waddch(view->window, ' ');
8534 if (view_needs_focus_indication(view))
8535 wstandend(view->window);
8536 free(wline);
8537 wline = NULL;
8538 free(line);
8539 line = NULL;
8540 if (--limit <= 0)
8541 return NULL;
8543 n = 0;
8544 view->maxx = 0;
8545 while (re && limit > 0) {
8546 char *line = NULL;
8547 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8549 if (s->show_date) {
8550 struct got_commit_object *ci;
8551 struct got_tag_object *tag;
8552 struct got_object_id *id;
8553 struct tm tm;
8554 time_t t;
8556 err = got_ref_resolve(&id, s->repo, re->ref);
8557 if (err)
8558 return err;
8559 err = got_object_open_as_tag(&tag, s->repo, id);
8560 if (err) {
8561 if (err->code != GOT_ERR_OBJ_TYPE) {
8562 free(id);
8563 return err;
8565 err = got_object_open_as_commit(&ci, s->repo,
8566 id);
8567 if (err) {
8568 free(id);
8569 return err;
8571 t = got_object_commit_get_committer_time(ci);
8572 got_object_commit_close(ci);
8573 } else {
8574 t = got_object_tag_get_tagger_time(tag);
8575 got_object_tag_close(tag);
8577 free(id);
8578 if (gmtime_r(&t, &tm) == NULL)
8579 return got_error_from_errno("gmtime_r");
8580 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8581 return got_error(GOT_ERR_NO_SPACE);
8583 if (got_ref_is_symbolic(re->ref)) {
8584 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8585 ymd : "", got_ref_get_name(re->ref),
8586 got_ref_get_symref_target(re->ref)) == -1)
8587 return got_error_from_errno("asprintf");
8588 } else if (s->show_ids) {
8589 struct got_object_id *id;
8590 char *id_str;
8591 err = got_ref_resolve(&id, s->repo, re->ref);
8592 if (err)
8593 return err;
8594 err = got_object_id_str(&id_str, id);
8595 if (err) {
8596 free(id);
8597 return err;
8599 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8600 got_ref_get_name(re->ref), id_str) == -1) {
8601 err = got_error_from_errno("asprintf");
8602 free(id);
8603 free(id_str);
8604 return err;
8606 free(id);
8607 free(id_str);
8608 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8609 got_ref_get_name(re->ref)) == -1)
8610 return got_error_from_errno("asprintf");
8612 /* use full line width to determine view->maxx */
8613 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8614 if (err) {
8615 free(line);
8616 return err;
8618 view->maxx = MAX(view->maxx, width);
8619 free(wline);
8620 wline = NULL;
8622 err = format_line(&wline, &width, &scrollx, line, view->x,
8623 view->ncols, 0, 0);
8624 if (err) {
8625 free(line);
8626 return err;
8628 if (n == s->selected) {
8629 if (view->focussed)
8630 wstandout(view->window);
8631 s->selected_entry = re;
8633 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8634 if (tc)
8635 wattr_on(view->window,
8636 COLOR_PAIR(tc->colorpair), NULL);
8637 waddwstr(view->window, &wline[scrollx]);
8638 if (tc)
8639 wattr_off(view->window,
8640 COLOR_PAIR(tc->colorpair), NULL);
8641 if (width < view->ncols)
8642 waddch(view->window, '\n');
8643 if (n == s->selected && view->focussed)
8644 wstandend(view->window);
8645 free(line);
8646 free(wline);
8647 wline = NULL;
8648 n++;
8649 s->ndisplayed++;
8650 s->last_displayed_entry = re;
8652 limit--;
8653 re = TAILQ_NEXT(re, entry);
8656 view_border(view);
8657 return err;
8660 static const struct got_error *
8661 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8662 struct tog_reflist_entry *re, struct got_repository *repo)
8664 const struct got_error *err = NULL;
8665 struct got_object_id *commit_id = NULL;
8666 struct tog_view *tree_view;
8668 *new_view = NULL;
8670 err = resolve_reflist_entry(&commit_id, re, repo);
8671 if (err) {
8672 if (err->code != GOT_ERR_OBJ_TYPE)
8673 return err;
8674 else
8675 return NULL;
8679 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8680 if (tree_view == NULL) {
8681 err = got_error_from_errno("view_open");
8682 goto done;
8685 err = open_tree_view(tree_view, commit_id,
8686 got_ref_get_name(re->ref), repo);
8687 if (err)
8688 goto done;
8690 *new_view = tree_view;
8691 done:
8692 free(commit_id);
8693 return err;
8696 static const struct got_error *
8697 ref_goto_line(struct tog_view *view, int nlines)
8699 const struct got_error *err = NULL;
8700 struct tog_ref_view_state *s = &view->state.ref;
8701 int g, idx = s->selected_entry->idx;
8703 g = view->gline;
8704 view->gline = 0;
8706 if (g == 0)
8707 g = 1;
8708 else if (g > s->nrefs)
8709 g = s->nrefs;
8711 if (g >= s->first_displayed_entry->idx + 1 &&
8712 g <= s->last_displayed_entry->idx + 1 &&
8713 g - s->first_displayed_entry->idx - 1 < nlines) {
8714 s->selected = g - s->first_displayed_entry->idx - 1;
8715 return NULL;
8718 if (idx + 1 < g) {
8719 err = ref_scroll_down(view, g - idx - 1);
8720 if (err)
8721 return err;
8722 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8723 s->first_displayed_entry->idx + s->selected < g &&
8724 s->selected < s->ndisplayed - 1)
8725 s->selected = g - s->first_displayed_entry->idx - 1;
8726 } else if (idx + 1 > g)
8727 ref_scroll_up(s, idx - g + 1);
8729 if (g < nlines && s->first_displayed_entry->idx == 0)
8730 s->selected = g - 1;
8732 return NULL;
8736 static const struct got_error *
8737 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8739 const struct got_error *err = NULL;
8740 struct tog_ref_view_state *s = &view->state.ref;
8741 struct tog_reflist_entry *re;
8742 int n, nscroll = view->nlines - 1;
8744 if (view->gline)
8745 return ref_goto_line(view, nscroll);
8747 switch (ch) {
8748 case '0':
8749 case '$':
8750 case KEY_RIGHT:
8751 case 'l':
8752 case KEY_LEFT:
8753 case 'h':
8754 horizontal_scroll_input(view, ch);
8755 break;
8756 case 'i':
8757 s->show_ids = !s->show_ids;
8758 view->count = 0;
8759 break;
8760 case 'm':
8761 s->show_date = !s->show_date;
8762 view->count = 0;
8763 break;
8764 case 'o':
8765 s->sort_by_date = !s->sort_by_date;
8766 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8767 view->count = 0;
8768 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8769 got_ref_cmp_by_commit_timestamp_descending :
8770 tog_ref_cmp_by_name, s->repo);
8771 if (err)
8772 break;
8773 got_reflist_object_id_map_free(tog_refs_idmap);
8774 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8775 &tog_refs, s->repo);
8776 if (err)
8777 break;
8778 ref_view_free_refs(s);
8779 err = ref_view_load_refs(s);
8780 break;
8781 case KEY_ENTER:
8782 case '\r':
8783 view->count = 0;
8784 if (!s->selected_entry)
8785 break;
8786 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8787 break;
8788 case 'T':
8789 view->count = 0;
8790 if (!s->selected_entry)
8791 break;
8792 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8793 break;
8794 case 'g':
8795 case '=':
8796 case KEY_HOME:
8797 s->selected = 0;
8798 view->count = 0;
8799 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8800 break;
8801 case 'G':
8802 case '*':
8803 case KEY_END: {
8804 int eos = view->nlines - 1;
8806 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8807 --eos; /* border */
8808 s->selected = 0;
8809 view->count = 0;
8810 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8811 for (n = 0; n < eos; n++) {
8812 if (re == NULL)
8813 break;
8814 s->first_displayed_entry = re;
8815 re = TAILQ_PREV(re, tog_reflist_head, entry);
8817 if (n > 0)
8818 s->selected = n - 1;
8819 break;
8821 case 'k':
8822 case KEY_UP:
8823 case CTRL('p'):
8824 if (s->selected > 0) {
8825 s->selected--;
8826 break;
8828 ref_scroll_up(s, 1);
8829 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8830 view->count = 0;
8831 break;
8832 case CTRL('u'):
8833 case 'u':
8834 nscroll /= 2;
8835 /* FALL THROUGH */
8836 case KEY_PPAGE:
8837 case CTRL('b'):
8838 case 'b':
8839 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8840 s->selected -= MIN(nscroll, s->selected);
8841 ref_scroll_up(s, MAX(0, nscroll));
8842 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8843 view->count = 0;
8844 break;
8845 case 'j':
8846 case KEY_DOWN:
8847 case CTRL('n'):
8848 if (s->selected < s->ndisplayed - 1) {
8849 s->selected++;
8850 break;
8852 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8853 /* can't scroll any further */
8854 view->count = 0;
8855 break;
8857 ref_scroll_down(view, 1);
8858 break;
8859 case CTRL('d'):
8860 case 'd':
8861 nscroll /= 2;
8862 /* FALL THROUGH */
8863 case KEY_NPAGE:
8864 case CTRL('f'):
8865 case 'f':
8866 case ' ':
8867 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8868 /* can't scroll any further; move cursor down */
8869 if (s->selected < s->ndisplayed - 1)
8870 s->selected += MIN(nscroll,
8871 s->ndisplayed - s->selected - 1);
8872 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8873 s->selected += s->ndisplayed - s->selected - 1;
8874 view->count = 0;
8875 break;
8877 ref_scroll_down(view, nscroll);
8878 break;
8879 case CTRL('l'):
8880 view->count = 0;
8881 tog_free_refs();
8882 err = tog_load_refs(s->repo, s->sort_by_date);
8883 if (err)
8884 break;
8885 ref_view_free_refs(s);
8886 err = ref_view_load_refs(s);
8887 break;
8888 case KEY_RESIZE:
8889 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8890 s->selected = view->nlines - 2;
8891 break;
8892 default:
8893 view->count = 0;
8894 break;
8897 return err;
8900 __dead static void
8901 usage_ref(void)
8903 endwin();
8904 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8905 getprogname());
8906 exit(1);
8909 static const struct got_error *
8910 cmd_ref(int argc, char *argv[])
8912 const struct got_error *error;
8913 struct got_repository *repo = NULL;
8914 struct got_worktree *worktree = NULL;
8915 char *cwd = NULL, *repo_path = NULL;
8916 int ch;
8917 struct tog_view *view;
8918 int *pack_fds = NULL;
8920 while ((ch = getopt(argc, argv, "r:")) != -1) {
8921 switch (ch) {
8922 case 'r':
8923 repo_path = realpath(optarg, NULL);
8924 if (repo_path == NULL)
8925 return got_error_from_errno2("realpath",
8926 optarg);
8927 break;
8928 default:
8929 usage_ref();
8930 /* NOTREACHED */
8934 argc -= optind;
8935 argv += optind;
8937 if (argc > 1)
8938 usage_ref();
8940 error = got_repo_pack_fds_open(&pack_fds);
8941 if (error != NULL)
8942 goto done;
8944 if (repo_path == NULL) {
8945 cwd = getcwd(NULL, 0);
8946 if (cwd == NULL)
8947 return got_error_from_errno("getcwd");
8948 error = got_worktree_open(&worktree, cwd);
8949 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8950 goto done;
8951 if (worktree)
8952 repo_path =
8953 strdup(got_worktree_get_repo_path(worktree));
8954 else
8955 repo_path = strdup(cwd);
8956 if (repo_path == NULL) {
8957 error = got_error_from_errno("strdup");
8958 goto done;
8962 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8963 if (error != NULL)
8964 goto done;
8966 init_curses();
8968 error = apply_unveil(got_repo_get_path(repo), NULL);
8969 if (error)
8970 goto done;
8972 error = tog_load_refs(repo, 0);
8973 if (error)
8974 goto done;
8976 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8977 if (view == NULL) {
8978 error = got_error_from_errno("view_open");
8979 goto done;
8982 error = open_ref_view(view, repo);
8983 if (error)
8984 goto done;
8986 if (worktree) {
8987 /* Release work tree lock. */
8988 got_worktree_close(worktree);
8989 worktree = NULL;
8991 error = view_loop(view);
8992 done:
8993 free(repo_path);
8994 free(cwd);
8995 if (repo) {
8996 const struct got_error *close_err = got_repo_close(repo);
8997 if (close_err)
8998 error = close_err;
9000 if (pack_fds) {
9001 const struct got_error *pack_err =
9002 got_repo_pack_fds_close(pack_fds);
9003 if (error == NULL)
9004 error = pack_err;
9006 tog_free_refs();
9007 return error;
9010 static const struct got_error*
9011 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
9012 const char *str)
9014 size_t len;
9016 if (win == NULL)
9017 win = stdscr;
9019 len = strlen(str);
9020 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
9022 if (focus)
9023 wstandout(win);
9024 if (mvwprintw(win, y, x, "%s", str) == ERR)
9025 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
9026 if (focus)
9027 wstandend(win);
9029 return NULL;
9032 static const struct got_error *
9033 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
9035 off_t *p;
9037 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
9038 if (p == NULL) {
9039 free(*line_offsets);
9040 *line_offsets = NULL;
9041 return got_error_from_errno("reallocarray");
9044 *line_offsets = p;
9045 (*line_offsets)[*nlines] = off;
9046 ++(*nlines);
9047 return NULL;
9050 static const struct got_error *
9051 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
9053 *ret = 0;
9055 for (;n > 0; --n, ++km) {
9056 char *t0, *t, *k;
9057 size_t len = 1;
9059 if (km->keys == NULL)
9060 continue;
9062 t = t0 = strdup(km->keys);
9063 if (t0 == NULL)
9064 return got_error_from_errno("strdup");
9066 len += strlen(t);
9067 while ((k = strsep(&t, " ")) != NULL)
9068 len += strlen(k) > 1 ? 2 : 0;
9069 free(t0);
9070 *ret = MAX(*ret, len);
9073 return NULL;
9077 * Write keymap section headers, keys, and key info in km to f.
9078 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9079 * wrap control and symbolic keys in guillemets, else use <>.
9081 static const struct got_error *
9082 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9084 int n, len = width;
9086 if (km->keys) {
9087 static const char *u8_glyph[] = {
9088 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9089 "\xe2\x80\xba" /* U+203A (utf8 >) */
9091 char *t0, *t, *k;
9092 int cs, s, first = 1;
9094 cs = got_locale_is_utf8();
9096 t = t0 = strdup(km->keys);
9097 if (t0 == NULL)
9098 return got_error_from_errno("strdup");
9100 len = strlen(km->keys);
9101 while ((k = strsep(&t, " ")) != NULL) {
9102 s = strlen(k) > 1; /* control or symbolic key */
9103 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9104 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9105 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9106 if (n < 0) {
9107 free(t0);
9108 return got_error_from_errno("fprintf");
9110 first = 0;
9111 len += s ? 2 : 0;
9112 *off += n;
9114 free(t0);
9116 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9117 if (n < 0)
9118 return got_error_from_errno("fprintf");
9119 *off += n;
9121 return NULL;
9124 static const struct got_error *
9125 format_help(struct tog_help_view_state *s)
9127 const struct got_error *err = NULL;
9128 off_t off = 0;
9129 int i, max, n, show = s->all;
9130 static const struct tog_key_map km[] = {
9131 #define KEYMAP_(info, type) { NULL, (info), type }
9132 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9133 GENERATE_HELP
9134 #undef KEYMAP_
9135 #undef KEY_
9138 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9139 if (err)
9140 return err;
9142 n = nitems(km);
9143 err = max_key_str(&max, km, n);
9144 if (err)
9145 return err;
9147 for (i = 0; i < n; ++i) {
9148 if (km[i].keys == NULL) {
9149 show = s->all;
9150 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9151 km[i].type == s->type || s->all)
9152 show = 1;
9154 if (show) {
9155 err = format_help_line(&off, s->f, &km[i], max);
9156 if (err)
9157 return err;
9158 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9159 if (err)
9160 return err;
9163 fputc('\n', s->f);
9164 ++off;
9165 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9166 return err;
9169 static const struct got_error *
9170 create_help(struct tog_help_view_state *s)
9172 FILE *f;
9173 const struct got_error *err;
9175 free(s->line_offsets);
9176 s->line_offsets = NULL;
9177 s->nlines = 0;
9179 f = got_opentemp();
9180 if (f == NULL)
9181 return got_error_from_errno("got_opentemp");
9182 s->f = f;
9184 err = format_help(s);
9185 if (err)
9186 return err;
9188 if (s->f && fflush(s->f) != 0)
9189 return got_error_from_errno("fflush");
9191 return NULL;
9194 static const struct got_error *
9195 search_start_help_view(struct tog_view *view)
9197 view->state.help.matched_line = 0;
9198 return NULL;
9201 static void
9202 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9203 size_t *nlines, int **first, int **last, int **match, int **selected)
9205 struct tog_help_view_state *s = &view->state.help;
9207 *f = s->f;
9208 *nlines = s->nlines;
9209 *line_offsets = s->line_offsets;
9210 *match = &s->matched_line;
9211 *first = &s->first_displayed_line;
9212 *last = &s->last_displayed_line;
9213 *selected = &s->selected_line;
9216 static const struct got_error *
9217 show_help_view(struct tog_view *view)
9219 struct tog_help_view_state *s = &view->state.help;
9220 const struct got_error *err;
9221 regmatch_t *regmatch = &view->regmatch;
9222 wchar_t *wline;
9223 char *line;
9224 ssize_t linelen;
9225 size_t linesz = 0;
9226 int width, nprinted = 0, rc = 0;
9227 int eos = view->nlines;
9229 if (view_is_hsplit_top(view))
9230 --eos; /* account for border */
9232 s->lineno = 0;
9233 rewind(s->f);
9234 werase(view->window);
9236 if (view->gline > s->nlines - 1)
9237 view->gline = s->nlines - 1;
9239 err = win_draw_center(view->window, 0, 0, view->ncols,
9240 view_needs_focus_indication(view),
9241 "tog help (press q to return to tog)");
9242 if (err)
9243 return err;
9244 if (eos <= 1)
9245 return NULL;
9246 waddstr(view->window, "\n\n");
9247 eos -= 2;
9249 s->eof = 0;
9250 view->maxx = 0;
9251 line = NULL;
9252 while (eos > 0 && nprinted < eos) {
9253 attr_t attr = 0;
9255 linelen = getline(&line, &linesz, s->f);
9256 if (linelen == -1) {
9257 if (!feof(s->f)) {
9258 free(line);
9259 return got_ferror(s->f, GOT_ERR_IO);
9261 s->eof = 1;
9262 break;
9264 if (++s->lineno < s->first_displayed_line)
9265 continue;
9266 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9267 continue;
9268 if (s->lineno == view->hiline)
9269 attr = A_STANDOUT;
9271 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9272 view->x ? 1 : 0);
9273 if (err) {
9274 free(line);
9275 return err;
9277 view->maxx = MAX(view->maxx, width);
9278 free(wline);
9279 wline = NULL;
9281 if (attr)
9282 wattron(view->window, attr);
9283 if (s->first_displayed_line + nprinted == s->matched_line &&
9284 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9285 err = add_matched_line(&width, line, view->ncols - 1, 0,
9286 view->window, view->x, regmatch);
9287 if (err) {
9288 free(line);
9289 return err;
9291 } else {
9292 int skip;
9294 err = format_line(&wline, &width, &skip, line,
9295 view->x, view->ncols, 0, view->x ? 1 : 0);
9296 if (err) {
9297 free(line);
9298 return err;
9300 waddwstr(view->window, &wline[skip]);
9301 free(wline);
9302 wline = NULL;
9304 if (s->lineno == view->hiline) {
9305 while (width++ < view->ncols)
9306 waddch(view->window, ' ');
9307 } else {
9308 if (width < view->ncols)
9309 waddch(view->window, '\n');
9311 if (attr)
9312 wattroff(view->window, attr);
9313 if (++nprinted == 1)
9314 s->first_displayed_line = s->lineno;
9316 free(line);
9317 if (nprinted > 0)
9318 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9319 else
9320 s->last_displayed_line = s->first_displayed_line;
9322 view_border(view);
9324 if (s->eof) {
9325 rc = waddnstr(view->window,
9326 "See the tog(1) manual page for full documentation",
9327 view->ncols - 1);
9328 if (rc == ERR)
9329 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9330 } else {
9331 wmove(view->window, view->nlines - 1, 0);
9332 wclrtoeol(view->window);
9333 wstandout(view->window);
9334 rc = waddnstr(view->window, "scroll down for more...",
9335 view->ncols - 1);
9336 if (rc == ERR)
9337 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9338 if (getcurx(view->window) < view->ncols - 6) {
9339 rc = wprintw(view->window, "[%.0f%%]",
9340 100.00 * s->last_displayed_line / s->nlines);
9341 if (rc == ERR)
9342 return got_error_msg(GOT_ERR_IO, "wprintw");
9344 wstandend(view->window);
9347 return NULL;
9350 static const struct got_error *
9351 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9353 struct tog_help_view_state *s = &view->state.help;
9354 const struct got_error *err = NULL;
9355 char *line = NULL;
9356 ssize_t linelen;
9357 size_t linesz = 0;
9358 int eos, nscroll;
9360 eos = nscroll = view->nlines;
9361 if (view_is_hsplit_top(view))
9362 --eos; /* border */
9364 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9366 switch (ch) {
9367 case '0':
9368 case '$':
9369 case KEY_RIGHT:
9370 case 'l':
9371 case KEY_LEFT:
9372 case 'h':
9373 horizontal_scroll_input(view, ch);
9374 break;
9375 case 'g':
9376 case KEY_HOME:
9377 s->first_displayed_line = 1;
9378 view->count = 0;
9379 break;
9380 case 'G':
9381 case KEY_END:
9382 view->count = 0;
9383 if (s->eof)
9384 break;
9385 s->first_displayed_line = (s->nlines - eos) + 3;
9386 s->eof = 1;
9387 break;
9388 case 'k':
9389 case KEY_UP:
9390 if (s->first_displayed_line > 1)
9391 --s->first_displayed_line;
9392 else
9393 view->count = 0;
9394 break;
9395 case CTRL('u'):
9396 case 'u':
9397 nscroll /= 2;
9398 /* FALL THROUGH */
9399 case KEY_PPAGE:
9400 case CTRL('b'):
9401 case 'b':
9402 if (s->first_displayed_line == 1) {
9403 view->count = 0;
9404 break;
9406 while (--nscroll > 0 && s->first_displayed_line > 1)
9407 s->first_displayed_line--;
9408 break;
9409 case 'j':
9410 case KEY_DOWN:
9411 case CTRL('n'):
9412 if (!s->eof)
9413 ++s->first_displayed_line;
9414 else
9415 view->count = 0;
9416 break;
9417 case CTRL('d'):
9418 case 'd':
9419 nscroll /= 2;
9420 /* FALL THROUGH */
9421 case KEY_NPAGE:
9422 case CTRL('f'):
9423 case 'f':
9424 case ' ':
9425 if (s->eof) {
9426 view->count = 0;
9427 break;
9429 while (!s->eof && --nscroll > 0) {
9430 linelen = getline(&line, &linesz, s->f);
9431 s->first_displayed_line++;
9432 if (linelen == -1) {
9433 if (feof(s->f))
9434 s->eof = 1;
9435 else
9436 err = got_ferror(s->f, GOT_ERR_IO);
9437 break;
9440 free(line);
9441 break;
9442 default:
9443 view->count = 0;
9444 break;
9447 return err;
9450 static const struct got_error *
9451 close_help_view(struct tog_view *view)
9453 struct tog_help_view_state *s = &view->state.help;
9455 free(s->line_offsets);
9456 s->line_offsets = NULL;
9457 if (fclose(s->f) == EOF)
9458 return got_error_from_errno("fclose");
9460 return NULL;
9463 static const struct got_error *
9464 reset_help_view(struct tog_view *view)
9466 struct tog_help_view_state *s = &view->state.help;
9469 if (s->f && fclose(s->f) == EOF)
9470 return got_error_from_errno("fclose");
9472 wclear(view->window);
9473 view->count = 0;
9474 view->x = 0;
9475 s->all = !s->all;
9476 s->first_displayed_line = 1;
9477 s->last_displayed_line = view->nlines;
9478 s->matched_line = 0;
9480 return create_help(s);
9483 static const struct got_error *
9484 open_help_view(struct tog_view *view, struct tog_view *parent)
9486 const struct got_error *err = NULL;
9487 struct tog_help_view_state *s = &view->state.help;
9489 s->type = (enum tog_keymap_type)parent->type;
9490 s->first_displayed_line = 1;
9491 s->last_displayed_line = view->nlines;
9492 s->selected_line = 1;
9494 view->show = show_help_view;
9495 view->input = input_help_view;
9496 view->reset = reset_help_view;
9497 view->close = close_help_view;
9498 view->search_start = search_start_help_view;
9499 view->search_setup = search_setup_help_view;
9500 view->search_next = search_next_view_match;
9502 err = create_help(s);
9503 return err;
9506 static const struct got_error *
9507 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9508 enum tog_view_type request, int y, int x)
9510 const struct got_error *err = NULL;
9512 *new_view = NULL;
9514 switch (request) {
9515 case TOG_VIEW_DIFF:
9516 if (view->type == TOG_VIEW_LOG) {
9517 struct tog_log_view_state *s = &view->state.log;
9519 err = open_diff_view_for_commit(new_view, y, x,
9520 s->selected_entry->commit, s->selected_entry->id,
9521 view, s->repo);
9522 } else
9523 return got_error_msg(GOT_ERR_NOT_IMPL,
9524 "parent/child view pair not supported");
9525 break;
9526 case TOG_VIEW_BLAME:
9527 if (view->type == TOG_VIEW_TREE) {
9528 struct tog_tree_view_state *s = &view->state.tree;
9530 err = blame_tree_entry(new_view, y, x,
9531 s->selected_entry, &s->parents, s->commit_id,
9532 s->repo);
9533 } else
9534 return got_error_msg(GOT_ERR_NOT_IMPL,
9535 "parent/child view pair not supported");
9536 break;
9537 case TOG_VIEW_LOG:
9538 if (view->type == TOG_VIEW_BLAME)
9539 err = log_annotated_line(new_view, y, x,
9540 view->state.blame.repo, view->state.blame.id_to_log);
9541 else if (view->type == TOG_VIEW_TREE)
9542 err = log_selected_tree_entry(new_view, y, x,
9543 &view->state.tree);
9544 else if (view->type == TOG_VIEW_REF)
9545 err = log_ref_entry(new_view, y, x,
9546 view->state.ref.selected_entry,
9547 view->state.ref.repo);
9548 else
9549 return got_error_msg(GOT_ERR_NOT_IMPL,
9550 "parent/child view pair not supported");
9551 break;
9552 case TOG_VIEW_TREE:
9553 if (view->type == TOG_VIEW_LOG)
9554 err = browse_commit_tree(new_view, y, x,
9555 view->state.log.selected_entry,
9556 view->state.log.in_repo_path,
9557 view->state.log.head_ref_name,
9558 view->state.log.repo);
9559 else if (view->type == TOG_VIEW_REF)
9560 err = browse_ref_tree(new_view, y, x,
9561 view->state.ref.selected_entry,
9562 view->state.ref.repo);
9563 else
9564 return got_error_msg(GOT_ERR_NOT_IMPL,
9565 "parent/child view pair not supported");
9566 break;
9567 case TOG_VIEW_REF:
9568 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9569 if (*new_view == NULL)
9570 return got_error_from_errno("view_open");
9571 if (view->type == TOG_VIEW_LOG)
9572 err = open_ref_view(*new_view, view->state.log.repo);
9573 else if (view->type == TOG_VIEW_TREE)
9574 err = open_ref_view(*new_view, view->state.tree.repo);
9575 else
9576 err = got_error_msg(GOT_ERR_NOT_IMPL,
9577 "parent/child view pair not supported");
9578 if (err)
9579 view_close(*new_view);
9580 break;
9581 case TOG_VIEW_HELP:
9582 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9583 if (*new_view == NULL)
9584 return got_error_from_errno("view_open");
9585 err = open_help_view(*new_view, view);
9586 if (err)
9587 view_close(*new_view);
9588 break;
9589 default:
9590 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9593 return err;
9597 * If view was scrolled down to move the selected line into view when opening a
9598 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9600 static void
9601 offset_selection_up(struct tog_view *view)
9603 switch (view->type) {
9604 case TOG_VIEW_BLAME: {
9605 struct tog_blame_view_state *s = &view->state.blame;
9606 if (s->first_displayed_line == 1) {
9607 s->selected_line = MAX(s->selected_line - view->offset,
9608 1);
9609 break;
9611 if (s->first_displayed_line > view->offset)
9612 s->first_displayed_line -= view->offset;
9613 else
9614 s->first_displayed_line = 1;
9615 s->selected_line += view->offset;
9616 break;
9618 case TOG_VIEW_LOG:
9619 log_scroll_up(&view->state.log, view->offset);
9620 view->state.log.selected += view->offset;
9621 break;
9622 case TOG_VIEW_REF:
9623 ref_scroll_up(&view->state.ref, view->offset);
9624 view->state.ref.selected += view->offset;
9625 break;
9626 case TOG_VIEW_TREE:
9627 tree_scroll_up(&view->state.tree, view->offset);
9628 view->state.tree.selected += view->offset;
9629 break;
9630 default:
9631 break;
9634 view->offset = 0;
9638 * If the selected line is in the section of screen covered by the bottom split,
9639 * scroll down offset lines to move it into view and index its new position.
9641 static const struct got_error *
9642 offset_selection_down(struct tog_view *view)
9644 const struct got_error *err = NULL;
9645 const struct got_error *(*scrolld)(struct tog_view *, int);
9646 int *selected = NULL;
9647 int header, offset;
9649 switch (view->type) {
9650 case TOG_VIEW_BLAME: {
9651 struct tog_blame_view_state *s = &view->state.blame;
9652 header = 3;
9653 scrolld = NULL;
9654 if (s->selected_line > view->nlines - header) {
9655 offset = abs(view->nlines - s->selected_line - header);
9656 s->first_displayed_line += offset;
9657 s->selected_line -= offset;
9658 view->offset = offset;
9660 break;
9662 case TOG_VIEW_LOG: {
9663 struct tog_log_view_state *s = &view->state.log;
9664 scrolld = &log_scroll_down;
9665 header = view_is_parent_view(view) ? 3 : 2;
9666 selected = &s->selected;
9667 break;
9669 case TOG_VIEW_REF: {
9670 struct tog_ref_view_state *s = &view->state.ref;
9671 scrolld = &ref_scroll_down;
9672 header = 3;
9673 selected = &s->selected;
9674 break;
9676 case TOG_VIEW_TREE: {
9677 struct tog_tree_view_state *s = &view->state.tree;
9678 scrolld = &tree_scroll_down;
9679 header = 5;
9680 selected = &s->selected;
9681 break;
9683 default:
9684 selected = NULL;
9685 scrolld = NULL;
9686 header = 0;
9687 break;
9690 if (selected && *selected > view->nlines - header) {
9691 offset = abs(view->nlines - *selected - header);
9692 view->offset = offset;
9693 if (scrolld && offset) {
9694 err = scrolld(view, offset);
9695 *selected -= offset;
9699 return err;
9702 static void
9703 list_commands(FILE *fp)
9705 size_t i;
9707 fprintf(fp, "commands:");
9708 for (i = 0; i < nitems(tog_commands); i++) {
9709 const struct tog_cmd *cmd = &tog_commands[i];
9710 fprintf(fp, " %s", cmd->name);
9712 fputc('\n', fp);
9715 __dead static void
9716 usage(int hflag, int status)
9718 FILE *fp = (status == 0) ? stdout : stderr;
9720 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9721 getprogname());
9722 if (hflag) {
9723 fprintf(fp, "lazy usage: %s path\n", getprogname());
9724 list_commands(fp);
9726 exit(status);
9729 static char **
9730 make_argv(int argc, ...)
9732 va_list ap;
9733 char **argv;
9734 int i;
9736 va_start(ap, argc);
9738 argv = calloc(argc, sizeof(char *));
9739 if (argv == NULL)
9740 err(1, "calloc");
9741 for (i = 0; i < argc; i++) {
9742 argv[i] = strdup(va_arg(ap, char *));
9743 if (argv[i] == NULL)
9744 err(1, "strdup");
9747 va_end(ap);
9748 return argv;
9752 * Try to convert 'tog path' into a 'tog log path' command.
9753 * The user could simply have mistyped the command rather than knowingly
9754 * provided a path. So check whether argv[0] can in fact be resolved
9755 * to a path in the HEAD commit and print a special error if not.
9756 * This hack is for mpi@ <3
9758 static const struct got_error *
9759 tog_log_with_path(int argc, char *argv[])
9761 const struct got_error *error = NULL, *close_err;
9762 const struct tog_cmd *cmd = NULL;
9763 struct got_repository *repo = NULL;
9764 struct got_worktree *worktree = NULL;
9765 struct got_object_id *commit_id = NULL, *id = NULL;
9766 struct got_commit_object *commit = NULL;
9767 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9768 char *commit_id_str = NULL, **cmd_argv = NULL;
9769 int *pack_fds = NULL;
9771 cwd = getcwd(NULL, 0);
9772 if (cwd == NULL)
9773 return got_error_from_errno("getcwd");
9775 error = got_repo_pack_fds_open(&pack_fds);
9776 if (error != NULL)
9777 goto done;
9779 error = got_worktree_open(&worktree, cwd);
9780 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9781 goto done;
9783 if (worktree)
9784 repo_path = strdup(got_worktree_get_repo_path(worktree));
9785 else
9786 repo_path = strdup(cwd);
9787 if (repo_path == NULL) {
9788 error = got_error_from_errno("strdup");
9789 goto done;
9792 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9793 if (error != NULL)
9794 goto done;
9796 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9797 repo, worktree);
9798 if (error)
9799 goto done;
9801 error = tog_load_refs(repo, 0);
9802 if (error)
9803 goto done;
9804 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9805 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9806 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9807 if (error)
9808 goto done;
9810 if (worktree) {
9811 got_worktree_close(worktree);
9812 worktree = NULL;
9815 error = got_object_open_as_commit(&commit, repo, commit_id);
9816 if (error)
9817 goto done;
9819 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9820 if (error) {
9821 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9822 goto done;
9823 fprintf(stderr, "%s: '%s' is no known command or path\n",
9824 getprogname(), argv[0]);
9825 usage(1, 1);
9826 /* not reached */
9829 error = got_object_id_str(&commit_id_str, commit_id);
9830 if (error)
9831 goto done;
9833 cmd = &tog_commands[0]; /* log */
9834 argc = 4;
9835 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9836 error = cmd->cmd_main(argc, cmd_argv);
9837 done:
9838 if (repo) {
9839 close_err = got_repo_close(repo);
9840 if (error == NULL)
9841 error = close_err;
9843 if (commit)
9844 got_object_commit_close(commit);
9845 if (worktree)
9846 got_worktree_close(worktree);
9847 if (pack_fds) {
9848 const struct got_error *pack_err =
9849 got_repo_pack_fds_close(pack_fds);
9850 if (error == NULL)
9851 error = pack_err;
9853 free(id);
9854 free(commit_id_str);
9855 free(commit_id);
9856 free(cwd);
9857 free(repo_path);
9858 free(in_repo_path);
9859 if (cmd_argv) {
9860 int i;
9861 for (i = 0; i < argc; i++)
9862 free(cmd_argv[i]);
9863 free(cmd_argv);
9865 tog_free_refs();
9866 return error;
9869 int
9870 main(int argc, char *argv[])
9872 const struct got_error *io_err, *error = NULL;
9873 const struct tog_cmd *cmd = NULL;
9874 int ch, hflag = 0, Vflag = 0;
9875 char **cmd_argv = NULL;
9876 static const struct option longopts[] = {
9877 { "version", no_argument, NULL, 'V' },
9878 { NULL, 0, NULL, 0}
9880 char *diff_algo_str = NULL;
9881 const char *test_script_path;
9883 setlocale(LC_CTYPE, "");
9886 * Test mode init must happen before pledge() because "tty" will
9887 * not allow TTY-related ioctls to occur via regular files.
9889 test_script_path = getenv("TOG_TEST_SCRIPT");
9890 if (test_script_path != NULL) {
9891 error = init_mock_term(test_script_path);
9892 if (error) {
9893 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9894 return 1;
9896 } else if (!isatty(STDIN_FILENO))
9897 errx(1, "standard input is not a tty");
9899 #if !defined(PROFILE)
9900 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9901 NULL) == -1)
9902 err(1, "pledge");
9903 #endif
9905 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9906 switch (ch) {
9907 case 'h':
9908 hflag = 1;
9909 break;
9910 case 'V':
9911 Vflag = 1;
9912 break;
9913 default:
9914 usage(hflag, 1);
9915 /* NOTREACHED */
9919 argc -= optind;
9920 argv += optind;
9921 optind = 1;
9922 optreset = 1;
9924 if (Vflag) {
9925 got_version_print_str();
9926 return 0;
9929 if (argc == 0) {
9930 if (hflag)
9931 usage(hflag, 0);
9932 /* Build an argument vector which runs a default command. */
9933 cmd = &tog_commands[0];
9934 argc = 1;
9935 cmd_argv = make_argv(argc, cmd->name);
9936 } else {
9937 size_t i;
9939 /* Did the user specify a command? */
9940 for (i = 0; i < nitems(tog_commands); i++) {
9941 if (strncmp(tog_commands[i].name, argv[0],
9942 strlen(argv[0])) == 0) {
9943 cmd = &tog_commands[i];
9944 break;
9949 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9950 if (diff_algo_str) {
9951 if (strcasecmp(diff_algo_str, "patience") == 0)
9952 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9953 if (strcasecmp(diff_algo_str, "myers") == 0)
9954 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9957 if (cmd == NULL) {
9958 if (argc != 1)
9959 usage(0, 1);
9960 /* No command specified; try log with a path */
9961 error = tog_log_with_path(argc, argv);
9962 } else {
9963 if (hflag)
9964 cmd->cmd_usage();
9965 else
9966 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9969 if (using_mock_io) {
9970 io_err = tog_io_close();
9971 if (error == NULL)
9972 error = io_err;
9974 endwin();
9975 if (cmd_argv) {
9976 int i;
9977 for (i = 0; i < argc; i++)
9978 free(cmd_argv[i]);
9979 free(cmd_argv);
9982 if (error && error->code != GOT_ERR_CANCELLED &&
9983 error->code != GOT_ERR_EOF &&
9984 error->code != GOT_ERR_PRIVSEP_EXIT &&
9985 error->code != GOT_ERR_PRIVSEP_PIPE &&
9986 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9987 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9988 return 0;