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"
59 #include "got_keyword.h"
61 #ifndef MIN
62 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
63 #endif
65 #ifndef MAX
66 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
67 #endif
69 #define CTRL(x) ((x) & 0x1f)
71 #ifndef nitems
72 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
73 #endif
75 struct tog_cmd {
76 const char *name;
77 const struct got_error *(*cmd_main)(int, char *[]);
78 void (*cmd_usage)(void);
79 };
81 __dead static void usage(int, int);
82 __dead static void usage_log(void);
83 __dead static void usage_diff(void);
84 __dead static void usage_blame(void);
85 __dead static void usage_tree(void);
86 __dead static void usage_ref(void);
88 static const struct got_error* cmd_log(int, char *[]);
89 static const struct got_error* cmd_diff(int, char *[]);
90 static const struct got_error* cmd_blame(int, char *[]);
91 static const struct got_error* cmd_tree(int, char *[]);
92 static const struct got_error* cmd_ref(int, char *[]);
94 static const struct tog_cmd tog_commands[] = {
95 { "log", cmd_log, usage_log },
96 { "diff", cmd_diff, usage_diff },
97 { "blame", cmd_blame, usage_blame },
98 { "tree", cmd_tree, usage_tree },
99 { "ref", cmd_ref, usage_ref },
100 };
102 enum tog_view_type {
103 TOG_VIEW_DIFF,
104 TOG_VIEW_LOG,
105 TOG_VIEW_BLAME,
106 TOG_VIEW_TREE,
107 TOG_VIEW_REF,
108 TOG_VIEW_HELP
109 };
111 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
112 enum tog_keymap_type {
113 TOG_KEYMAP_KEYS = -2,
114 TOG_KEYMAP_GLOBAL,
115 TOG_KEYMAP_DIFF,
116 TOG_KEYMAP_LOG,
117 TOG_KEYMAP_BLAME,
118 TOG_KEYMAP_TREE,
119 TOG_KEYMAP_REF,
120 TOG_KEYMAP_HELP
121 };
123 enum tog_view_mode {
124 TOG_VIEW_SPLIT_NONE,
125 TOG_VIEW_SPLIT_VERT,
126 TOG_VIEW_SPLIT_HRZN
127 };
129 #define HSPLIT_SCALE 0.3f /* default horizontal split scale */
131 #define TOG_EOF_STRING "(END)"
133 struct commit_queue_entry {
134 TAILQ_ENTRY(commit_queue_entry) entry;
135 struct got_object_id *id;
136 struct got_commit_object *commit;
137 int idx;
138 };
139 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
140 struct commit_queue {
141 int ncommits;
142 struct commit_queue_head head;
143 };
145 struct tog_color {
146 STAILQ_ENTRY(tog_color) entry;
147 regex_t regex;
148 short colorpair;
149 };
150 STAILQ_HEAD(tog_colors, tog_color);
152 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
153 static struct got_reflist_object_id_map *tog_refs_idmap;
154 static struct {
155 struct got_object_id *id;
156 int idx;
157 char marker;
158 } tog_base_commit;
159 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
161 static const struct got_error *
162 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
163 struct got_reference* re2)
165 const char *name1 = got_ref_get_name(re1);
166 const char *name2 = got_ref_get_name(re2);
167 int isbackup1, isbackup2;
169 /* Sort backup refs towards the bottom of the list. */
170 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
171 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
172 if (!isbackup1 && isbackup2) {
173 *cmp = -1;
174 return NULL;
175 } else if (isbackup1 && !isbackup2) {
176 *cmp = 1;
177 return NULL;
180 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
181 return NULL;
184 static const struct got_error *
185 tog_load_refs(struct got_repository *repo, int sort_by_date)
187 const struct got_error *err;
189 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
190 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
191 repo);
192 if (err)
193 return err;
195 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
196 repo);
199 static void
200 tog_free_refs(void)
202 if (tog_refs_idmap) {
203 got_reflist_object_id_map_free(tog_refs_idmap);
204 tog_refs_idmap = NULL;
206 got_ref_list_free(&tog_refs);
209 static const struct got_error *
210 add_color(struct tog_colors *colors, const char *pattern,
211 int idx, short color)
213 const struct got_error *err = NULL;
214 struct tog_color *tc;
215 int regerr = 0;
217 if (idx < 1 || idx > COLOR_PAIRS - 1)
218 return NULL;
220 init_pair(idx, color, -1);
222 tc = calloc(1, sizeof(*tc));
223 if (tc == NULL)
224 return got_error_from_errno("calloc");
225 regerr = regcomp(&tc->regex, pattern,
226 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
227 if (regerr) {
228 static char regerr_msg[512];
229 static char err_msg[512];
230 regerror(regerr, &tc->regex, regerr_msg,
231 sizeof(regerr_msg));
232 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
233 regerr_msg);
234 err = got_error_msg(GOT_ERR_REGEX, err_msg);
235 free(tc);
236 return err;
238 tc->colorpair = idx;
239 STAILQ_INSERT_HEAD(colors, tc, entry);
240 return NULL;
243 static void
244 free_colors(struct tog_colors *colors)
246 struct tog_color *tc;
248 while (!STAILQ_EMPTY(colors)) {
249 tc = STAILQ_FIRST(colors);
250 STAILQ_REMOVE_HEAD(colors, entry);
251 regfree(&tc->regex);
252 free(tc);
256 static struct tog_color *
257 get_color(struct tog_colors *colors, int colorpair)
259 struct tog_color *tc = NULL;
261 STAILQ_FOREACH(tc, colors, entry) {
262 if (tc->colorpair == colorpair)
263 return tc;
266 return NULL;
269 static int
270 default_color_value(const char *envvar)
272 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
273 return COLOR_MAGENTA;
274 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
275 return COLOR_CYAN;
276 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
277 return COLOR_YELLOW;
278 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
279 return COLOR_GREEN;
280 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
281 return COLOR_MAGENTA;
282 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
283 return COLOR_MAGENTA;
284 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
285 return COLOR_CYAN;
286 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
287 return COLOR_GREEN;
288 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
289 return COLOR_GREEN;
290 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
291 return COLOR_CYAN;
292 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
293 return COLOR_YELLOW;
294 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
295 return COLOR_GREEN;
296 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
297 return COLOR_MAGENTA;
298 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
299 return COLOR_YELLOW;
300 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
301 return COLOR_CYAN;
303 return -1;
306 static int
307 get_color_value(const char *envvar)
309 const char *val = getenv(envvar);
311 if (val == NULL)
312 return default_color_value(envvar);
314 if (strcasecmp(val, "black") == 0)
315 return COLOR_BLACK;
316 if (strcasecmp(val, "red") == 0)
317 return COLOR_RED;
318 if (strcasecmp(val, "green") == 0)
319 return COLOR_GREEN;
320 if (strcasecmp(val, "yellow") == 0)
321 return COLOR_YELLOW;
322 if (strcasecmp(val, "blue") == 0)
323 return COLOR_BLUE;
324 if (strcasecmp(val, "magenta") == 0)
325 return COLOR_MAGENTA;
326 if (strcasecmp(val, "cyan") == 0)
327 return COLOR_CYAN;
328 if (strcasecmp(val, "white") == 0)
329 return COLOR_WHITE;
330 if (strcasecmp(val, "default") == 0)
331 return -1;
333 return default_color_value(envvar);
336 struct tog_diff_view_state {
337 struct got_object_id *id1, *id2;
338 const char *label1, *label2;
339 FILE *f, *f1, *f2;
340 int fd1, fd2;
341 int lineno;
342 int first_displayed_line;
343 int last_displayed_line;
344 int eof;
345 int diff_context;
346 int ignore_whitespace;
347 int force_text_diff;
348 struct got_repository *repo;
349 struct got_diff_line *lines;
350 size_t nlines;
351 int matched_line;
352 int selected_line;
354 /* passed from log or blame view; may be NULL */
355 struct tog_view *parent_view;
356 };
358 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
359 static volatile sig_atomic_t tog_thread_error;
361 struct tog_log_thread_args {
362 pthread_cond_t need_commits;
363 pthread_cond_t commit_loaded;
364 int commits_needed;
365 int load_all;
366 struct got_commit_graph *graph;
367 struct commit_queue *real_commits;
368 const char *in_repo_path;
369 struct got_object_id *start_id;
370 struct got_repository *repo;
371 int *pack_fds;
372 int log_complete;
373 sig_atomic_t *quit;
374 struct commit_queue_entry **first_displayed_entry;
375 struct commit_queue_entry **selected_entry;
376 int *searching;
377 int *search_next_done;
378 regex_t *regex;
379 int *limiting;
380 int limit_match;
381 regex_t *limit_regex;
382 struct commit_queue *limit_commits;
383 };
385 struct tog_log_view_state {
386 struct commit_queue *commits;
387 struct commit_queue_entry *first_displayed_entry;
388 struct commit_queue_entry *last_displayed_entry;
389 struct commit_queue_entry *selected_entry;
390 struct commit_queue real_commits;
391 int selected;
392 char *in_repo_path;
393 char *head_ref_name;
394 int log_branches;
395 struct got_repository *repo;
396 struct got_object_id *start_id;
397 sig_atomic_t quit;
398 pthread_t thread;
399 struct tog_log_thread_args thread_args;
400 struct commit_queue_entry *matched_entry;
401 struct commit_queue_entry *search_entry;
402 struct tog_colors colors;
403 int use_committer;
404 int limit_view;
405 regex_t limit_regex;
406 struct commit_queue limit_commits;
407 };
409 #define TOG_COLOR_DIFF_MINUS 1
410 #define TOG_COLOR_DIFF_PLUS 2
411 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
412 #define TOG_COLOR_DIFF_META 4
413 #define TOG_COLOR_TREE_SUBMODULE 5
414 #define TOG_COLOR_TREE_SYMLINK 6
415 #define TOG_COLOR_TREE_DIRECTORY 7
416 #define TOG_COLOR_TREE_EXECUTABLE 8
417 #define TOG_COLOR_COMMIT 9
418 #define TOG_COLOR_AUTHOR 10
419 #define TOG_COLOR_DATE 11
420 #define TOG_COLOR_REFS_HEADS 12
421 #define TOG_COLOR_REFS_TAGS 13
422 #define TOG_COLOR_REFS_REMOTES 14
423 #define TOG_COLOR_REFS_BACKUP 15
425 struct tog_blame_cb_args {
426 struct tog_blame_line *lines; /* one per line */
427 int nlines;
429 struct tog_view *view;
430 struct got_object_id *commit_id;
431 int *quit;
432 };
434 struct tog_blame_thread_args {
435 const char *path;
436 struct got_repository *repo;
437 struct tog_blame_cb_args *cb_args;
438 int *complete;
439 got_cancel_cb cancel_cb;
440 void *cancel_arg;
441 pthread_cond_t blame_complete;
442 };
444 struct tog_blame {
445 FILE *f;
446 off_t filesize;
447 struct tog_blame_line *lines;
448 int nlines;
449 off_t *line_offsets;
450 pthread_t thread;
451 struct tog_blame_thread_args thread_args;
452 struct tog_blame_cb_args cb_args;
453 const char *path;
454 int *pack_fds;
455 };
457 struct tog_blame_view_state {
458 int first_displayed_line;
459 int last_displayed_line;
460 int selected_line;
461 int last_diffed_line;
462 int blame_complete;
463 int eof;
464 int done;
465 struct got_object_id_queue blamed_commits;
466 struct got_object_qid *blamed_commit;
467 char *path;
468 struct got_repository *repo;
469 struct got_object_id *commit_id;
470 struct got_object_id *id_to_log;
471 struct tog_blame blame;
472 int matched_line;
473 struct tog_colors colors;
474 };
476 struct tog_parent_tree {
477 TAILQ_ENTRY(tog_parent_tree) entry;
478 struct got_tree_object *tree;
479 struct got_tree_entry *first_displayed_entry;
480 struct got_tree_entry *selected_entry;
481 int selected;
482 };
484 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
486 struct tog_tree_view_state {
487 char *tree_label;
488 struct got_object_id *commit_id;/* commit which this tree belongs to */
489 struct got_tree_object *root; /* the commit's root tree entry */
490 struct got_tree_object *tree; /* currently displayed (sub-)tree */
491 struct got_tree_entry *first_displayed_entry;
492 struct got_tree_entry *last_displayed_entry;
493 struct got_tree_entry *selected_entry;
494 int ndisplayed, selected, show_ids;
495 struct tog_parent_trees parents; /* parent trees of current sub-tree */
496 char *head_ref_name;
497 struct got_repository *repo;
498 struct got_tree_entry *matched_entry;
499 struct tog_colors colors;
500 };
502 struct tog_reflist_entry {
503 TAILQ_ENTRY(tog_reflist_entry) entry;
504 struct got_reference *ref;
505 int idx;
506 };
508 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
510 struct tog_ref_view_state {
511 struct tog_reflist_head refs;
512 struct tog_reflist_entry *first_displayed_entry;
513 struct tog_reflist_entry *last_displayed_entry;
514 struct tog_reflist_entry *selected_entry;
515 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
516 struct got_repository *repo;
517 struct tog_reflist_entry *matched_entry;
518 struct tog_colors colors;
519 };
521 struct tog_help_view_state {
522 FILE *f;
523 off_t *line_offsets;
524 size_t nlines;
525 int lineno;
526 int first_displayed_line;
527 int last_displayed_line;
528 int eof;
529 int matched_line;
530 int selected_line;
531 int all;
532 enum tog_keymap_type type;
533 };
535 #define GENERATE_HELP \
536 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
537 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
538 KEY_("k C-p Up", "Move cursor or page up one line"), \
539 KEY_("j C-n Down", "Move cursor or page down one line"), \
540 KEY_("C-b b PgUp", "Scroll the view up one page"), \
541 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
542 KEY_("C-u u", "Scroll the view up one half page"), \
543 KEY_("C-d d", "Scroll the view down one half page"), \
544 KEY_("g", "Go to line N (default: first line)"), \
545 KEY_("Home =", "Go to the first line"), \
546 KEY_("G", "Go to line N (default: last line)"), \
547 KEY_("End *", "Go to the last line"), \
548 KEY_("l Right", "Scroll the view right"), \
549 KEY_("h Left", "Scroll the view left"), \
550 KEY_("$", "Scroll view to the rightmost position"), \
551 KEY_("0", "Scroll view to the leftmost position"), \
552 KEY_("-", "Decrease size of the focussed split"), \
553 KEY_("+", "Increase size of the focussed split"), \
554 KEY_("Tab", "Switch focus between views"), \
555 KEY_("F", "Toggle fullscreen mode"), \
556 KEY_("S", "Switch split-screen layout"), \
557 KEY_("/", "Open prompt to enter search term"), \
558 KEY_("n", "Find next line/token matching the current search term"), \
559 KEY_("N", "Find previous line/token matching the current search term"),\
560 KEY_("q", "Quit the focussed view; Quit help screen"), \
561 KEY_("Q", "Quit tog"), \
563 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
564 KEY_("< ,", "Move cursor up one commit"), \
565 KEY_("> .", "Move cursor down one commit"), \
566 KEY_("Enter", "Open diff view of the selected commit"), \
567 KEY_("B", "Reload the log view and toggle display of merged commits"), \
568 KEY_("R", "Open ref view of all repository references"), \
569 KEY_("T", "Display tree view of the repository from the selected" \
570 " commit"), \
571 KEY_("@", "Toggle between displaying author and committer name"), \
572 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
573 KEY_("C-g Backspace", "Cancel current search or log operation"), \
574 KEY_("C-l", "Reload the log view with new commits in the repository"), \
576 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
577 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
578 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
579 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
580 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
581 " data"), \
582 KEY_("(", "Go to the previous file in the diff"), \
583 KEY_(")", "Go to the next file in the diff"), \
584 KEY_("{", "Go to the previous hunk in the diff"), \
585 KEY_("}", "Go to the next hunk in the diff"), \
586 KEY_("[", "Decrease the number of context lines"), \
587 KEY_("]", "Increase the number of context lines"), \
588 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
590 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
591 KEY_("Enter", "Display diff view of the selected line's commit"), \
592 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
593 KEY_("L", "Open log view for the currently selected annotated line"), \
594 KEY_("C", "Reload view with the previously blamed commit"), \
595 KEY_("c", "Reload view with the version of the file found in the" \
596 " selected line's commit"), \
597 KEY_("p", "Reload view with the version of the file found in the" \
598 " selected line's parent commit"), \
600 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
601 KEY_("Enter", "Enter selected directory or open blame view of the" \
602 " selected file"), \
603 KEY_("L", "Open log view for the selected entry"), \
604 KEY_("R", "Open ref view of all repository references"), \
605 KEY_("i", "Show object IDs for all tree entries"), \
606 KEY_("Backspace", "Return to the parent directory"), \
608 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
609 KEY_("Enter", "Display log view of the selected reference"), \
610 KEY_("T", "Display tree view of the selected reference"), \
611 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
612 KEY_("m", "Toggle display of last modified date for each reference"), \
613 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
614 KEY_("C-l", "Reload view with all repository references")
616 struct tog_key_map {
617 const char *keys;
618 const char *info;
619 enum tog_keymap_type type;
620 };
622 /* curses io for tog regress */
623 struct tog_io {
624 FILE *cin;
625 FILE *cout;
626 FILE *f;
627 FILE *sdump;
628 int wait_for_ui;
629 } tog_io;
630 static int using_mock_io;
632 #define TOG_KEY_SCRDUMP SHRT_MIN
634 /*
635 * We implement two types of views: parent views and child views.
637 * The 'Tab' key switches focus between a parent view and its child view.
638 * Child views are shown side-by-side to their parent view, provided
639 * there is enough screen estate.
641 * When a new view is opened from within a parent view, this new view
642 * becomes a child view of the parent view, replacing any existing child.
644 * When a new view is opened from within a child view, this new view
645 * becomes a parent view which will obscure the views below until the
646 * user quits the new parent view by typing 'q'.
648 * This list of views contains parent views only.
649 * Child views are only pointed to by their parent view.
650 */
651 TAILQ_HEAD(tog_view_list_head, tog_view);
653 struct tog_view {
654 TAILQ_ENTRY(tog_view) entry;
655 WINDOW *window;
656 PANEL *panel;
657 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
658 int resized_y, resized_x; /* begin_y/x based on user resizing */
659 int maxx, x; /* max column and current start column */
660 int lines, cols; /* copies of LINES and COLS */
661 int nscrolled, offset; /* lines scrolled and hsplit line offset */
662 int gline, hiline; /* navigate to and highlight this nG line */
663 int ch, count; /* current keymap and count prefix */
664 int resized; /* set when in a resize event */
665 int focussed; /* Only set on one parent or child view at a time. */
666 int dying;
667 struct tog_view *parent;
668 struct tog_view *child;
670 /*
671 * This flag is initially set on parent views when a new child view
672 * is created. It gets toggled when the 'Tab' key switches focus
673 * between parent and child.
674 * The flag indicates whether focus should be passed on to our child
675 * view if this parent view gets picked for focus after another parent
676 * view was closed. This prevents child views from losing focus in such
677 * situations.
678 */
679 int focus_child;
681 enum tog_view_mode mode;
682 /* type-specific state */
683 enum tog_view_type type;
684 union {
685 struct tog_diff_view_state diff;
686 struct tog_log_view_state log;
687 struct tog_blame_view_state blame;
688 struct tog_tree_view_state tree;
689 struct tog_ref_view_state ref;
690 struct tog_help_view_state help;
691 } state;
693 const struct got_error *(*show)(struct tog_view *);
694 const struct got_error *(*input)(struct tog_view **,
695 struct tog_view *, int);
696 const struct got_error *(*reset)(struct tog_view *);
697 const struct got_error *(*resize)(struct tog_view *, int);
698 const struct got_error *(*close)(struct tog_view *);
700 const struct got_error *(*search_start)(struct tog_view *);
701 const struct got_error *(*search_next)(struct tog_view *);
702 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
703 int **, int **, int **, int **);
704 int search_started;
705 int searching;
706 #define TOG_SEARCH_FORWARD 1
707 #define TOG_SEARCH_BACKWARD 2
708 int search_next_done;
709 #define TOG_SEARCH_HAVE_MORE 1
710 #define TOG_SEARCH_NO_MORE 2
711 #define TOG_SEARCH_HAVE_NONE 3
712 regex_t regex;
713 regmatch_t regmatch;
714 const char *action;
715 };
717 static const struct got_error *open_diff_view(struct tog_view *,
718 struct got_object_id *, struct got_object_id *,
719 const char *, const char *, int, int, int, struct tog_view *,
720 struct got_repository *);
721 static const struct got_error *show_diff_view(struct tog_view *);
722 static const struct got_error *input_diff_view(struct tog_view **,
723 struct tog_view *, int);
724 static const struct got_error *reset_diff_view(struct tog_view *);
725 static const struct got_error* close_diff_view(struct tog_view *);
726 static const struct got_error *search_start_diff_view(struct tog_view *);
727 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
728 size_t *, int **, int **, int **, int **);
729 static const struct got_error *search_next_view_match(struct tog_view *);
731 static const struct got_error *open_log_view(struct tog_view *,
732 struct got_object_id *, struct got_repository *,
733 const char *, const char *, int);
734 static const struct got_error * show_log_view(struct tog_view *);
735 static const struct got_error *input_log_view(struct tog_view **,
736 struct tog_view *, int);
737 static const struct got_error *resize_log_view(struct tog_view *, int);
738 static const struct got_error *close_log_view(struct tog_view *);
739 static const struct got_error *search_start_log_view(struct tog_view *);
740 static const struct got_error *search_next_log_view(struct tog_view *);
742 static const struct got_error *open_blame_view(struct tog_view *, char *,
743 struct got_object_id *, struct got_repository *);
744 static const struct got_error *show_blame_view(struct tog_view *);
745 static const struct got_error *input_blame_view(struct tog_view **,
746 struct tog_view *, int);
747 static const struct got_error *reset_blame_view(struct tog_view *);
748 static const struct got_error *close_blame_view(struct tog_view *);
749 static const struct got_error *search_start_blame_view(struct tog_view *);
750 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
751 size_t *, int **, int **, int **, int **);
753 static const struct got_error *open_tree_view(struct tog_view *,
754 struct got_object_id *, const char *, struct got_repository *);
755 static const struct got_error *show_tree_view(struct tog_view *);
756 static const struct got_error *input_tree_view(struct tog_view **,
757 struct tog_view *, int);
758 static const struct got_error *close_tree_view(struct tog_view *);
759 static const struct got_error *search_start_tree_view(struct tog_view *);
760 static const struct got_error *search_next_tree_view(struct tog_view *);
762 static const struct got_error *open_ref_view(struct tog_view *,
763 struct got_repository *);
764 static const struct got_error *show_ref_view(struct tog_view *);
765 static const struct got_error *input_ref_view(struct tog_view **,
766 struct tog_view *, int);
767 static const struct got_error *close_ref_view(struct tog_view *);
768 static const struct got_error *search_start_ref_view(struct tog_view *);
769 static const struct got_error *search_next_ref_view(struct tog_view *);
771 static const struct got_error *open_help_view(struct tog_view *,
772 struct tog_view *);
773 static const struct got_error *show_help_view(struct tog_view *);
774 static const struct got_error *input_help_view(struct tog_view **,
775 struct tog_view *, int);
776 static const struct got_error *reset_help_view(struct tog_view *);
777 static const struct got_error* close_help_view(struct tog_view *);
778 static const struct got_error *search_start_help_view(struct tog_view *);
779 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
780 size_t *, int **, int **, int **, int **);
782 static volatile sig_atomic_t tog_sigwinch_received;
783 static volatile sig_atomic_t tog_sigpipe_received;
784 static volatile sig_atomic_t tog_sigcont_received;
785 static volatile sig_atomic_t tog_sigint_received;
786 static volatile sig_atomic_t tog_sigterm_received;
788 static void
789 tog_sigwinch(int signo)
791 tog_sigwinch_received = 1;
794 static void
795 tog_sigpipe(int signo)
797 tog_sigpipe_received = 1;
800 static void
801 tog_sigcont(int signo)
803 tog_sigcont_received = 1;
806 static void
807 tog_sigint(int signo)
809 tog_sigint_received = 1;
812 static void
813 tog_sigterm(int signo)
815 tog_sigterm_received = 1;
818 static int
819 tog_fatal_signal_received(void)
821 return (tog_sigpipe_received ||
822 tog_sigint_received || tog_sigterm_received);
825 static const struct got_error *
826 view_close(struct tog_view *view)
828 const struct got_error *err = NULL, *child_err = NULL;
830 if (view->child) {
831 child_err = view_close(view->child);
832 view->child = NULL;
834 if (view->close)
835 err = view->close(view);
836 if (view->panel)
837 del_panel(view->panel);
838 if (view->window)
839 delwin(view->window);
840 free(view);
841 return err ? err : child_err;
844 static struct tog_view *
845 view_open(int nlines, int ncols, int begin_y, int begin_x,
846 enum tog_view_type type)
848 struct tog_view *view = calloc(1, sizeof(*view));
850 if (view == NULL)
851 return NULL;
853 view->type = type;
854 view->lines = LINES;
855 view->cols = COLS;
856 view->nlines = nlines ? nlines : LINES - begin_y;
857 view->ncols = ncols ? ncols : COLS - begin_x;
858 view->begin_y = begin_y;
859 view->begin_x = begin_x;
860 view->window = newwin(nlines, ncols, begin_y, begin_x);
861 if (view->window == NULL) {
862 view_close(view);
863 return NULL;
865 view->panel = new_panel(view->window);
866 if (view->panel == NULL ||
867 set_panel_userptr(view->panel, view) != OK) {
868 view_close(view);
869 return NULL;
872 keypad(view->window, TRUE);
873 return view;
876 static int
877 view_split_begin_x(int begin_x)
879 if (begin_x > 0 || COLS < 120)
880 return 0;
881 return (COLS - MAX(COLS / 2, 80));
884 /* XXX Stub till we decide what to do. */
885 static int
886 view_split_begin_y(int lines)
888 return lines * HSPLIT_SCALE;
891 static const struct got_error *view_resize(struct tog_view *);
893 static const struct got_error *
894 view_splitscreen(struct tog_view *view)
896 const struct got_error *err = NULL;
898 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
899 if (view->resized_y && view->resized_y < view->lines)
900 view->begin_y = view->resized_y;
901 else
902 view->begin_y = view_split_begin_y(view->nlines);
903 view->begin_x = 0;
904 } else if (!view->resized) {
905 if (view->resized_x && view->resized_x < view->cols - 1 &&
906 view->cols > 119)
907 view->begin_x = view->resized_x;
908 else
909 view->begin_x = view_split_begin_x(0);
910 view->begin_y = 0;
912 view->nlines = LINES - view->begin_y;
913 view->ncols = COLS - view->begin_x;
914 view->lines = LINES;
915 view->cols = COLS;
916 err = view_resize(view);
917 if (err)
918 return err;
920 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
921 view->parent->nlines = view->begin_y;
923 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
924 return got_error_from_errno("mvwin");
926 return NULL;
929 static const struct got_error *
930 view_fullscreen(struct tog_view *view)
932 const struct got_error *err = NULL;
934 view->begin_x = 0;
935 view->begin_y = view->resized ? view->begin_y : 0;
936 view->nlines = view->resized ? view->nlines : LINES;
937 view->ncols = COLS;
938 view->lines = LINES;
939 view->cols = COLS;
940 err = view_resize(view);
941 if (err)
942 return err;
944 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
945 return got_error_from_errno("mvwin");
947 return NULL;
950 static int
951 view_is_parent_view(struct tog_view *view)
953 return view->parent == NULL;
956 static int
957 view_is_splitscreen(struct tog_view *view)
959 return view->begin_x > 0 || view->begin_y > 0;
962 static int
963 view_is_fullscreen(struct tog_view *view)
965 return view->nlines == LINES && view->ncols == COLS;
968 static int
969 view_is_hsplit_top(struct tog_view *view)
971 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
972 view_is_splitscreen(view->child);
975 static void
976 view_border(struct tog_view *view)
978 PANEL *panel;
979 const struct tog_view *view_above;
981 if (view->parent)
982 return view_border(view->parent);
984 panel = panel_above(view->panel);
985 if (panel == NULL)
986 return;
988 view_above = panel_userptr(panel);
989 if (view->mode == TOG_VIEW_SPLIT_HRZN)
990 mvwhline(view->window, view_above->begin_y - 1,
991 view->begin_x, ACS_HLINE, view->ncols);
992 else
993 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
994 ACS_VLINE, view->nlines);
997 static const struct got_error *view_init_hsplit(struct tog_view *, int);
998 static const struct got_error *request_log_commits(struct tog_view *);
999 static const struct got_error *offset_selection_down(struct tog_view *);
1000 static void offset_selection_up(struct tog_view *);
1001 static void view_get_split(struct tog_view *, int *, int *);
1003 static const struct got_error *
1004 view_resize(struct tog_view *view)
1006 const struct got_error *err = NULL;
1007 int dif, nlines, ncols;
1009 dif = LINES - view->lines; /* line difference */
1011 if (view->lines > LINES)
1012 nlines = view->nlines - (view->lines - LINES);
1013 else
1014 nlines = view->nlines + (LINES - view->lines);
1015 if (view->cols > COLS)
1016 ncols = view->ncols - (view->cols - COLS);
1017 else
1018 ncols = view->ncols + (COLS - view->cols);
1020 if (view->child) {
1021 int hs = view->child->begin_y;
1023 if (!view_is_fullscreen(view))
1024 view->child->begin_x = view_split_begin_x(view->begin_x);
1025 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1026 view->child->begin_x == 0) {
1027 ncols = COLS;
1029 view_fullscreen(view->child);
1030 if (view->child->focussed)
1031 show_panel(view->child->panel);
1032 else
1033 show_panel(view->panel);
1034 } else {
1035 ncols = view->child->begin_x;
1037 view_splitscreen(view->child);
1038 show_panel(view->child->panel);
1041 * XXX This is ugly and needs to be moved into the above
1042 * logic but "works" for now and my attempts at moving it
1043 * break either 'tab' or 'F' key maps in horizontal splits.
1045 if (hs) {
1046 err = view_splitscreen(view->child);
1047 if (err)
1048 return err;
1049 if (dif < 0) { /* top split decreased */
1050 err = offset_selection_down(view);
1051 if (err)
1052 return err;
1054 view_border(view);
1055 update_panels();
1056 doupdate();
1057 show_panel(view->child->panel);
1058 nlines = view->nlines;
1060 } else if (view->parent == NULL)
1061 ncols = COLS;
1063 if (view->resize && dif > 0) {
1064 err = view->resize(view, dif);
1065 if (err)
1066 return err;
1069 if (wresize(view->window, nlines, ncols) == ERR)
1070 return got_error_from_errno("wresize");
1071 if (replace_panel(view->panel, view->window) == ERR)
1072 return got_error_from_errno("replace_panel");
1073 wclear(view->window);
1075 view->nlines = nlines;
1076 view->ncols = ncols;
1077 view->lines = LINES;
1078 view->cols = COLS;
1080 return NULL;
1083 static const struct got_error *
1084 resize_log_view(struct tog_view *view, int increase)
1086 struct tog_log_view_state *s = &view->state.log;
1087 const struct got_error *err = NULL;
1088 int n = 0;
1090 if (s->selected_entry)
1091 n = s->selected_entry->idx + view->lines - s->selected;
1094 * Request commits to account for the increased
1095 * height so we have enough to populate the view.
1097 if (s->commits->ncommits < n) {
1098 view->nscrolled = n - s->commits->ncommits + increase + 1;
1099 err = request_log_commits(view);
1102 return err;
1105 static void
1106 view_adjust_offset(struct tog_view *view, int n)
1108 if (n == 0)
1109 return;
1111 if (view->parent && view->parent->offset) {
1112 if (view->parent->offset + n >= 0)
1113 view->parent->offset += n;
1114 else
1115 view->parent->offset = 0;
1116 } else if (view->offset) {
1117 if (view->offset - n >= 0)
1118 view->offset -= n;
1119 else
1120 view->offset = 0;
1124 static const struct got_error *
1125 view_resize_split(struct tog_view *view, int resize)
1127 const struct got_error *err = NULL;
1128 struct tog_view *v = NULL;
1130 if (view->parent)
1131 v = view->parent;
1132 else
1133 v = view;
1135 if (!v->child || !view_is_splitscreen(v->child))
1136 return NULL;
1138 v->resized = v->child->resized = resize; /* lock for resize event */
1140 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1141 if (v->child->resized_y)
1142 v->child->begin_y = v->child->resized_y;
1143 if (view->parent)
1144 v->child->begin_y -= resize;
1145 else
1146 v->child->begin_y += resize;
1147 if (v->child->begin_y < 3) {
1148 view->count = 0;
1149 v->child->begin_y = 3;
1150 } else if (v->child->begin_y > LINES - 1) {
1151 view->count = 0;
1152 v->child->begin_y = LINES - 1;
1154 v->ncols = COLS;
1155 v->child->ncols = COLS;
1156 view_adjust_offset(view, resize);
1157 err = view_init_hsplit(v, v->child->begin_y);
1158 if (err)
1159 return err;
1160 v->child->resized_y = v->child->begin_y;
1161 } else {
1162 if (v->child->resized_x)
1163 v->child->begin_x = v->child->resized_x;
1164 if (view->parent)
1165 v->child->begin_x -= resize;
1166 else
1167 v->child->begin_x += resize;
1168 if (v->child->begin_x < 11) {
1169 view->count = 0;
1170 v->child->begin_x = 11;
1171 } else if (v->child->begin_x > COLS - 1) {
1172 view->count = 0;
1173 v->child->begin_x = COLS - 1;
1175 v->child->resized_x = v->child->begin_x;
1178 v->child->mode = v->mode;
1179 v->child->nlines = v->lines - v->child->begin_y;
1180 v->child->ncols = v->cols - v->child->begin_x;
1181 v->focus_child = 1;
1183 err = view_fullscreen(v);
1184 if (err)
1185 return err;
1186 err = view_splitscreen(v->child);
1187 if (err)
1188 return err;
1190 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1191 err = offset_selection_down(v->child);
1192 if (err)
1193 return err;
1196 if (v->resize)
1197 err = v->resize(v, 0);
1198 else if (v->child->resize)
1199 err = v->child->resize(v->child, 0);
1201 v->resized = v->child->resized = 0;
1203 return err;
1206 static void
1207 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1209 struct tog_view *v = src->child ? src->child : src;
1211 dst->resized_x = v->resized_x;
1212 dst->resized_y = v->resized_y;
1215 static const struct got_error *
1216 view_close_child(struct tog_view *view)
1218 const struct got_error *err = NULL;
1220 if (view->child == NULL)
1221 return NULL;
1223 err = view_close(view->child);
1224 view->child = NULL;
1225 return err;
1228 static const struct got_error *
1229 view_set_child(struct tog_view *view, struct tog_view *child)
1231 const struct got_error *err = NULL;
1233 view->child = child;
1234 child->parent = view;
1236 err = view_resize(view);
1237 if (err)
1238 return err;
1240 if (view->child->resized_x || view->child->resized_y)
1241 err = view_resize_split(view, 0);
1243 return err;
1246 static const struct got_error *view_dispatch_request(struct tog_view **,
1247 struct tog_view *, enum tog_view_type, int, int);
1249 static const struct got_error *
1250 view_request_new(struct tog_view **requested, struct tog_view *view,
1251 enum tog_view_type request)
1253 struct tog_view *new_view = NULL;
1254 const struct got_error *err;
1255 int y = 0, x = 0;
1257 *requested = NULL;
1259 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1260 view_get_split(view, &y, &x);
1262 err = view_dispatch_request(&new_view, view, request, y, x);
1263 if (err)
1264 return err;
1266 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1267 request != TOG_VIEW_HELP) {
1268 err = view_init_hsplit(view, y);
1269 if (err)
1270 return err;
1273 view->focussed = 0;
1274 new_view->focussed = 1;
1275 new_view->mode = view->mode;
1276 new_view->nlines = request == TOG_VIEW_HELP ?
1277 view->lines : view->lines - y;
1279 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1280 view_transfer_size(new_view, view);
1281 err = view_close_child(view);
1282 if (err)
1283 return err;
1284 err = view_set_child(view, new_view);
1285 if (err)
1286 return err;
1287 view->focus_child = 1;
1288 } else
1289 *requested = new_view;
1291 return NULL;
1294 static void
1295 tog_resizeterm(void)
1297 int cols, lines;
1298 struct winsize size;
1300 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1301 cols = 80; /* Default */
1302 lines = 24;
1303 } else {
1304 cols = size.ws_col;
1305 lines = size.ws_row;
1307 resize_term(lines, cols);
1310 static const struct got_error *
1311 view_search_start(struct tog_view *view, int fast_refresh)
1313 const struct got_error *err = NULL;
1314 struct tog_view *v = view;
1315 char pattern[1024];
1316 int ret;
1318 if (view->search_started) {
1319 regfree(&view->regex);
1320 view->searching = 0;
1321 memset(&view->regmatch, 0, sizeof(view->regmatch));
1323 view->search_started = 0;
1325 if (view->nlines < 1)
1326 return NULL;
1328 if (view_is_hsplit_top(view))
1329 v = view->child;
1330 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1331 v = view->parent;
1333 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1334 wclrtoeol(v->window);
1336 nodelay(v->window, FALSE); /* block for search term input */
1337 nocbreak();
1338 echo();
1339 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1340 wrefresh(v->window);
1341 cbreak();
1342 noecho();
1343 nodelay(v->window, TRUE);
1344 if (!fast_refresh && !using_mock_io)
1345 halfdelay(10);
1346 if (ret == ERR)
1347 return NULL;
1349 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1350 err = view->search_start(view);
1351 if (err) {
1352 regfree(&view->regex);
1353 return err;
1355 view->search_started = 1;
1356 view->searching = TOG_SEARCH_FORWARD;
1357 view->search_next_done = 0;
1358 view->search_next(view);
1361 return NULL;
1364 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1365 static const struct got_error *
1366 switch_split(struct tog_view *view)
1368 const struct got_error *err = NULL;
1369 struct tog_view *v = NULL;
1371 if (view->parent)
1372 v = view->parent;
1373 else
1374 v = view;
1376 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1377 v->mode = TOG_VIEW_SPLIT_VERT;
1378 else
1379 v->mode = TOG_VIEW_SPLIT_HRZN;
1381 if (!v->child)
1382 return NULL;
1383 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1384 v->mode = TOG_VIEW_SPLIT_NONE;
1386 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1387 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1388 v->child->begin_y = v->child->resized_y;
1389 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1390 v->child->begin_x = v->child->resized_x;
1393 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1394 v->ncols = COLS;
1395 v->child->ncols = COLS;
1396 v->child->nscrolled = LINES - v->child->nlines;
1398 err = view_init_hsplit(v, v->child->begin_y);
1399 if (err)
1400 return err;
1402 v->child->mode = v->mode;
1403 v->child->nlines = v->lines - v->child->begin_y;
1404 v->focus_child = 1;
1406 err = view_fullscreen(v);
1407 if (err)
1408 return err;
1409 err = view_splitscreen(v->child);
1410 if (err)
1411 return err;
1413 if (v->mode == TOG_VIEW_SPLIT_NONE)
1414 v->mode = TOG_VIEW_SPLIT_VERT;
1415 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1416 err = offset_selection_down(v);
1417 if (err)
1418 return err;
1419 err = offset_selection_down(v->child);
1420 if (err)
1421 return err;
1422 } else {
1423 offset_selection_up(v);
1424 offset_selection_up(v->child);
1426 if (v->resize)
1427 err = v->resize(v, 0);
1428 else if (v->child->resize)
1429 err = v->child->resize(v->child, 0);
1431 return err;
1435 * Strip trailing whitespace from str starting at byte *n;
1436 * if *n < 0, use strlen(str). Return new str length in *n.
1438 static void
1439 strip_trailing_ws(char *str, int *n)
1441 size_t x = *n;
1443 if (str == NULL || *str == '\0')
1444 return;
1446 if (x < 0)
1447 x = strlen(str);
1449 while (x-- > 0 && isspace((unsigned char)str[x]))
1450 str[x] = '\0';
1452 *n = x + 1;
1456 * Extract visible substring of line y from the curses screen
1457 * and strip trailing whitespace. If vline is set, overwrite
1458 * line[vline] with '|' because the ACS_VLINE character is
1459 * written out as 'x'. Write the line to file f.
1461 static const struct got_error *
1462 view_write_line(FILE *f, int y, int vline)
1464 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1465 int r, w;
1467 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1468 if (r == ERR)
1469 return got_error_fmt(GOT_ERR_RANGE,
1470 "failed to extract line %d", y);
1473 * In some views, lines are padded with blanks to COLS width.
1474 * Strip them so we can diff without the -b flag when testing.
1476 strip_trailing_ws(line, &r);
1478 if (vline > 0)
1479 line[vline] = '|';
1481 w = fprintf(f, "%s\n", line);
1482 if (w != r + 1) /* \n */
1483 return got_ferror(f, GOT_ERR_IO);
1485 return NULL;
1489 * Capture the visible curses screen by writing each line to the
1490 * file at the path set via the TOG_SCR_DUMP environment variable.
1492 static const struct got_error *
1493 screendump(struct tog_view *view)
1495 const struct got_error *err;
1496 int i;
1498 err = got_opentemp_truncate(tog_io.sdump);
1499 if (err)
1500 return err;
1502 if ((view->child && view->child->begin_x) ||
1503 (view->parent && view->begin_x)) {
1504 int ncols = view->child ? view->ncols : view->parent->ncols;
1506 /* vertical splitscreen */
1507 for (i = 0; i < view->nlines; ++i) {
1508 err = view_write_line(tog_io.sdump, i, ncols - 1);
1509 if (err)
1510 goto done;
1512 } else {
1513 int hline = 0;
1515 /* fullscreen or horizontal splitscreen */
1516 if ((view->child && view->child->begin_y) ||
1517 (view->parent && view->begin_y)) /* hsplit */
1518 hline = view->child ?
1519 view->child->begin_y : view->begin_y;
1521 for (i = 0; i < view->lines; i++) {
1522 if (hline && i == hline - 1) {
1523 int c;
1525 /* ACS_HLINE writes out as 'q', overwrite it */
1526 for (c = 0; c < view->cols; ++c)
1527 fputc('-', tog_io.sdump);
1528 fputc('\n', tog_io.sdump);
1529 continue;
1532 err = view_write_line(tog_io.sdump, i, 0);
1533 if (err)
1534 goto done;
1538 done:
1539 return err;
1543 * Compute view->count from numeric input. Assign total to view->count and
1544 * return first non-numeric key entered.
1546 static int
1547 get_compound_key(struct tog_view *view, int c)
1549 struct tog_view *v = view;
1550 int x, n = 0;
1552 if (view_is_hsplit_top(view))
1553 v = view->child;
1554 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1555 v = view->parent;
1557 view->count = 0;
1558 cbreak(); /* block for input */
1559 nodelay(view->window, FALSE);
1560 wmove(v->window, v->nlines - 1, 0);
1561 wclrtoeol(v->window);
1562 waddch(v->window, ':');
1564 do {
1565 x = getcurx(v->window);
1566 if (x != ERR && x < view->ncols) {
1567 waddch(v->window, c);
1568 wrefresh(v->window);
1572 * Don't overflow. Max valid request should be the greatest
1573 * between the longest and total lines; cap at 10 million.
1575 if (n >= 9999999)
1576 n = 9999999;
1577 else
1578 n = n * 10 + (c - '0');
1579 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1581 if (c == 'G' || c == 'g') { /* nG key map */
1582 view->gline = view->hiline = n;
1583 n = 0;
1584 c = 0;
1587 /* Massage excessive or inapplicable values at the input handler. */
1588 view->count = n;
1590 return c;
1593 static void
1594 action_report(struct tog_view *view)
1596 struct tog_view *v = view;
1598 if (view_is_hsplit_top(view))
1599 v = view->child;
1600 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1601 v = view->parent;
1603 wmove(v->window, v->nlines - 1, 0);
1604 wclrtoeol(v->window);
1605 wprintw(v->window, ":%s", view->action);
1606 wrefresh(v->window);
1609 * Clear action status report. Only clear in blame view
1610 * once annotating is complete, otherwise it's too fast.
1612 if (view->type == TOG_VIEW_BLAME) {
1613 if (view->state.blame.blame_complete)
1614 view->action = NULL;
1615 } else
1616 view->action = NULL;
1620 * Read the next line from the test script and assign
1621 * key instruction to *ch. If at EOF, set the *done flag.
1623 static const struct got_error *
1624 tog_read_script_key(FILE *script, struct tog_view *view, int *ch, int *done)
1626 const struct got_error *err = NULL;
1627 char *line = NULL;
1628 size_t linesz = 0;
1630 if (view->count && --view->count) {
1631 *ch = view->ch;
1632 return NULL;
1633 } else
1634 *ch = -1;
1636 if (getline(&line, &linesz, script) == -1) {
1637 if (feof(script)) {
1638 *done = 1;
1639 goto done;
1640 } else {
1641 err = got_ferror(script, GOT_ERR_IO);
1642 goto done;
1646 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1647 tog_io.wait_for_ui = 1;
1648 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1649 *ch = KEY_ENTER;
1650 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1651 *ch = KEY_RIGHT;
1652 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1653 *ch = KEY_LEFT;
1654 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1655 *ch = KEY_DOWN;
1656 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1657 *ch = KEY_UP;
1658 else if (strncasecmp(line, "TAB", 3) == 0)
1659 *ch = '\t';
1660 else if (strncasecmp(line, "SCREENDUMP", 10) == 0)
1661 *ch = TOG_KEY_SCRDUMP;
1662 else if (isdigit((unsigned char)*line)) {
1663 char *t = line;
1665 while (isdigit((unsigned char)*t))
1666 ++t;
1667 view->ch = *ch = *t;
1668 *t = '\0';
1669 /* ignore error, view->count is 0 if instruction is invalid */
1670 view->count = strtonum(line, 0, INT_MAX, NULL);
1671 } else
1672 *ch = *line;
1674 done:
1675 free(line);
1676 return err;
1679 static const struct got_error *
1680 view_input(struct tog_view **new, int *done, struct tog_view *view,
1681 struct tog_view_list_head *views, int fast_refresh)
1683 const struct got_error *err = NULL;
1684 struct tog_view *v;
1685 int ch, errcode;
1687 *new = NULL;
1689 if (view->action)
1690 action_report(view);
1692 /* Clear "no matches" indicator. */
1693 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1694 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1695 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1696 view->count = 0;
1699 if (view->searching && !view->search_next_done) {
1700 errcode = pthread_mutex_unlock(&tog_mutex);
1701 if (errcode)
1702 return got_error_set_errno(errcode,
1703 "pthread_mutex_unlock");
1704 sched_yield();
1705 errcode = pthread_mutex_lock(&tog_mutex);
1706 if (errcode)
1707 return got_error_set_errno(errcode,
1708 "pthread_mutex_lock");
1709 view->search_next(view);
1710 return NULL;
1713 /* Allow threads to make progress while we are waiting for input. */
1714 errcode = pthread_mutex_unlock(&tog_mutex);
1715 if (errcode)
1716 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1718 if (using_mock_io) {
1719 err = tog_read_script_key(tog_io.f, view, &ch, done);
1720 if (err) {
1721 errcode = pthread_mutex_lock(&tog_mutex);
1722 return err;
1724 } else if (view->count && --view->count) {
1725 cbreak();
1726 nodelay(view->window, TRUE);
1727 ch = wgetch(view->window);
1728 /* let C-g or backspace abort unfinished count */
1729 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1730 view->count = 0;
1731 else
1732 ch = view->ch;
1733 } else {
1734 ch = wgetch(view->window);
1735 if (ch >= '1' && ch <= '9')
1736 view->ch = ch = get_compound_key(view, ch);
1738 if (view->hiline && ch != ERR && ch != 0)
1739 view->hiline = 0; /* key pressed, clear line highlight */
1740 nodelay(view->window, TRUE);
1741 errcode = pthread_mutex_lock(&tog_mutex);
1742 if (errcode)
1743 return got_error_set_errno(errcode, "pthread_mutex_lock");
1745 if (tog_sigwinch_received || tog_sigcont_received) {
1746 tog_resizeterm();
1747 tog_sigwinch_received = 0;
1748 tog_sigcont_received = 0;
1749 TAILQ_FOREACH(v, views, entry) {
1750 err = view_resize(v);
1751 if (err)
1752 return err;
1753 err = v->input(new, v, KEY_RESIZE);
1754 if (err)
1755 return err;
1756 if (v->child) {
1757 err = view_resize(v->child);
1758 if (err)
1759 return err;
1760 err = v->child->input(new, v->child,
1761 KEY_RESIZE);
1762 if (err)
1763 return err;
1764 if (v->child->resized_x || v->child->resized_y) {
1765 err = view_resize_split(v, 0);
1766 if (err)
1767 return err;
1773 switch (ch) {
1774 case '?':
1775 case 'H':
1776 case KEY_F(1):
1777 if (view->type == TOG_VIEW_HELP)
1778 err = view->reset(view);
1779 else
1780 err = view_request_new(new, view, TOG_VIEW_HELP);
1781 break;
1782 case '\t':
1783 view->count = 0;
1784 if (view->child) {
1785 view->focussed = 0;
1786 view->child->focussed = 1;
1787 view->focus_child = 1;
1788 } else if (view->parent) {
1789 view->focussed = 0;
1790 view->parent->focussed = 1;
1791 view->parent->focus_child = 0;
1792 if (!view_is_splitscreen(view)) {
1793 if (view->parent->resize) {
1794 err = view->parent->resize(view->parent,
1795 0);
1796 if (err)
1797 return err;
1799 offset_selection_up(view->parent);
1800 err = view_fullscreen(view->parent);
1801 if (err)
1802 return err;
1805 break;
1806 case 'q':
1807 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1808 if (view->parent->resize) {
1809 /* might need more commits to fill fullscreen */
1810 err = view->parent->resize(view->parent, 0);
1811 if (err)
1812 break;
1814 offset_selection_up(view->parent);
1816 err = view->input(new, view, ch);
1817 view->dying = 1;
1818 break;
1819 case 'Q':
1820 *done = 1;
1821 break;
1822 case 'F':
1823 view->count = 0;
1824 if (view_is_parent_view(view)) {
1825 if (view->child == NULL)
1826 break;
1827 if (view_is_splitscreen(view->child)) {
1828 view->focussed = 0;
1829 view->child->focussed = 1;
1830 err = view_fullscreen(view->child);
1831 } else {
1832 err = view_splitscreen(view->child);
1833 if (!err)
1834 err = view_resize_split(view, 0);
1836 if (err)
1837 break;
1838 err = view->child->input(new, view->child,
1839 KEY_RESIZE);
1840 } else {
1841 if (view_is_splitscreen(view)) {
1842 view->parent->focussed = 0;
1843 view->focussed = 1;
1844 err = view_fullscreen(view);
1845 } else {
1846 err = view_splitscreen(view);
1847 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1848 err = view_resize(view->parent);
1849 if (!err)
1850 err = view_resize_split(view, 0);
1852 if (err)
1853 break;
1854 err = view->input(new, view, KEY_RESIZE);
1856 if (err)
1857 break;
1858 if (view->resize) {
1859 err = view->resize(view, 0);
1860 if (err)
1861 break;
1863 if (view->parent) {
1864 if (view->parent->resize) {
1865 err = view->parent->resize(view->parent, 0);
1866 if (err != NULL)
1867 break;
1869 err = offset_selection_down(view->parent);
1870 if (err != NULL)
1871 break;
1873 err = offset_selection_down(view);
1874 break;
1875 case 'S':
1876 view->count = 0;
1877 err = switch_split(view);
1878 break;
1879 case '-':
1880 err = view_resize_split(view, -1);
1881 break;
1882 case '+':
1883 err = view_resize_split(view, 1);
1884 break;
1885 case KEY_RESIZE:
1886 break;
1887 case '/':
1888 view->count = 0;
1889 if (view->search_start)
1890 view_search_start(view, fast_refresh);
1891 else
1892 err = view->input(new, view, ch);
1893 break;
1894 case 'N':
1895 case 'n':
1896 if (view->search_started && view->search_next) {
1897 view->searching = (ch == 'n' ?
1898 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1899 view->search_next_done = 0;
1900 view->search_next(view);
1901 } else
1902 err = view->input(new, view, ch);
1903 break;
1904 case 'A':
1905 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1906 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1907 view->action = "Patience diff algorithm";
1908 } else {
1909 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1910 view->action = "Myers diff algorithm";
1912 TAILQ_FOREACH(v, views, entry) {
1913 if (v->reset) {
1914 err = v->reset(v);
1915 if (err)
1916 return err;
1918 if (v->child && v->child->reset) {
1919 err = v->child->reset(v->child);
1920 if (err)
1921 return err;
1924 break;
1925 case TOG_KEY_SCRDUMP:
1926 err = screendump(view);
1927 break;
1928 default:
1929 err = view->input(new, view, ch);
1930 break;
1933 return err;
1936 static int
1937 view_needs_focus_indication(struct tog_view *view)
1939 if (view_is_parent_view(view)) {
1940 if (view->child == NULL || view->child->focussed)
1941 return 0;
1942 if (!view_is_splitscreen(view->child))
1943 return 0;
1944 } else if (!view_is_splitscreen(view))
1945 return 0;
1947 return view->focussed;
1950 static const struct got_error *
1951 tog_io_close(void)
1953 const struct got_error *err = NULL;
1955 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1956 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1957 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1958 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1959 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1960 err = got_ferror(tog_io.f, GOT_ERR_IO);
1961 if (tog_io.sdump && fclose(tog_io.sdump) == EOF && err == NULL)
1962 err = got_ferror(tog_io.sdump, GOT_ERR_IO);
1964 return err;
1967 static const struct got_error *
1968 view_loop(struct tog_view *view)
1970 const struct got_error *err = NULL;
1971 struct tog_view_list_head views;
1972 struct tog_view *new_view;
1973 char *mode;
1974 int fast_refresh = 10;
1975 int done = 0, errcode;
1977 mode = getenv("TOG_VIEW_SPLIT_MODE");
1978 if (!mode || !(*mode == 'h' || *mode == 'H'))
1979 view->mode = TOG_VIEW_SPLIT_VERT;
1980 else
1981 view->mode = TOG_VIEW_SPLIT_HRZN;
1983 errcode = pthread_mutex_lock(&tog_mutex);
1984 if (errcode)
1985 return got_error_set_errno(errcode, "pthread_mutex_lock");
1987 TAILQ_INIT(&views);
1988 TAILQ_INSERT_HEAD(&views, view, entry);
1990 view->focussed = 1;
1991 err = view->show(view);
1992 if (err)
1993 return err;
1994 update_panels();
1995 doupdate();
1996 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1997 !tog_fatal_signal_received()) {
1998 /* Refresh fast during initialization, then become slower. */
1999 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
2000 halfdelay(10); /* switch to once per second */
2002 err = view_input(&new_view, &done, view, &views, fast_refresh);
2003 if (err)
2004 break;
2006 if (view->dying && view == TAILQ_FIRST(&views) &&
2007 TAILQ_NEXT(view, entry) == NULL)
2008 done = 1;
2009 if (done) {
2010 struct tog_view *v;
2013 * When we quit, scroll the screen up a single line
2014 * so we don't lose any information.
2016 TAILQ_FOREACH(v, &views, entry) {
2017 wmove(v->window, 0, 0);
2018 wdeleteln(v->window);
2019 wnoutrefresh(v->window);
2020 if (v->child && !view_is_fullscreen(v)) {
2021 wmove(v->child->window, 0, 0);
2022 wdeleteln(v->child->window);
2023 wnoutrefresh(v->child->window);
2026 doupdate();
2029 if (view->dying) {
2030 struct tog_view *v, *prev = NULL;
2032 if (view_is_parent_view(view))
2033 prev = TAILQ_PREV(view, tog_view_list_head,
2034 entry);
2035 else if (view->parent)
2036 prev = view->parent;
2038 if (view->parent) {
2039 view->parent->child = NULL;
2040 view->parent->focus_child = 0;
2041 /* Restore fullscreen line height. */
2042 view->parent->nlines = view->parent->lines;
2043 err = view_resize(view->parent);
2044 if (err)
2045 break;
2046 /* Make resized splits persist. */
2047 view_transfer_size(view->parent, view);
2048 } else
2049 TAILQ_REMOVE(&views, view, entry);
2051 err = view_close(view);
2052 if (err)
2053 goto done;
2055 view = NULL;
2056 TAILQ_FOREACH(v, &views, entry) {
2057 if (v->focussed)
2058 break;
2060 if (view == NULL && new_view == NULL) {
2061 /* No view has focus. Try to pick one. */
2062 if (prev)
2063 view = prev;
2064 else if (!TAILQ_EMPTY(&views)) {
2065 view = TAILQ_LAST(&views,
2066 tog_view_list_head);
2068 if (view) {
2069 if (view->focus_child) {
2070 view->child->focussed = 1;
2071 view = view->child;
2072 } else
2073 view->focussed = 1;
2077 if (new_view) {
2078 struct tog_view *v, *t;
2079 /* Only allow one parent view per type. */
2080 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2081 if (v->type != new_view->type)
2082 continue;
2083 TAILQ_REMOVE(&views, v, entry);
2084 err = view_close(v);
2085 if (err)
2086 goto done;
2087 break;
2089 TAILQ_INSERT_TAIL(&views, new_view, entry);
2090 view = new_view;
2092 if (view && !done) {
2093 if (view_is_parent_view(view)) {
2094 if (view->child && view->child->focussed)
2095 view = view->child;
2096 } else {
2097 if (view->parent && view->parent->focussed)
2098 view = view->parent;
2100 show_panel(view->panel);
2101 if (view->child && view_is_splitscreen(view->child))
2102 show_panel(view->child->panel);
2103 if (view->parent && view_is_splitscreen(view)) {
2104 err = view->parent->show(view->parent);
2105 if (err)
2106 goto done;
2108 err = view->show(view);
2109 if (err)
2110 goto done;
2111 if (view->child) {
2112 err = view->child->show(view->child);
2113 if (err)
2114 goto done;
2116 update_panels();
2117 doupdate();
2120 done:
2121 while (!TAILQ_EMPTY(&views)) {
2122 const struct got_error *close_err;
2123 view = TAILQ_FIRST(&views);
2124 TAILQ_REMOVE(&views, view, entry);
2125 close_err = view_close(view);
2126 if (close_err && err == NULL)
2127 err = close_err;
2130 errcode = pthread_mutex_unlock(&tog_mutex);
2131 if (errcode && err == NULL)
2132 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2134 return err;
2137 __dead static void
2138 usage_log(void)
2140 endwin();
2141 fprintf(stderr,
2142 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2143 getprogname());
2144 exit(1);
2147 /* Create newly allocated wide-character string equivalent to a byte string. */
2148 static const struct got_error *
2149 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2151 char *vis = NULL;
2152 const struct got_error *err = NULL;
2154 *ws = NULL;
2155 *wlen = mbstowcs(NULL, s, 0);
2156 if (*wlen == (size_t)-1) {
2157 int vislen;
2158 if (errno != EILSEQ)
2159 return got_error_from_errno("mbstowcs");
2161 /* byte string invalid in current encoding; try to "fix" it */
2162 err = got_mbsavis(&vis, &vislen, s);
2163 if (err)
2164 return err;
2165 *wlen = mbstowcs(NULL, vis, 0);
2166 if (*wlen == (size_t)-1) {
2167 err = got_error_from_errno("mbstowcs"); /* give up */
2168 goto done;
2172 *ws = calloc(*wlen + 1, sizeof(**ws));
2173 if (*ws == NULL) {
2174 err = got_error_from_errno("calloc");
2175 goto done;
2178 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2179 err = got_error_from_errno("mbstowcs");
2180 done:
2181 free(vis);
2182 if (err) {
2183 free(*ws);
2184 *ws = NULL;
2185 *wlen = 0;
2187 return err;
2190 static const struct got_error *
2191 expand_tab(char **ptr, const char *src)
2193 char *dst;
2194 size_t len, n, idx = 0, sz = 0;
2196 *ptr = NULL;
2197 n = len = strlen(src);
2198 dst = malloc(n + 1);
2199 if (dst == NULL)
2200 return got_error_from_errno("malloc");
2202 while (idx < len && src[idx]) {
2203 const char c = src[idx];
2205 if (c == '\t') {
2206 size_t nb = TABSIZE - sz % TABSIZE;
2207 char *p;
2209 p = realloc(dst, n + nb);
2210 if (p == NULL) {
2211 free(dst);
2212 return got_error_from_errno("realloc");
2215 dst = p;
2216 n += nb;
2217 memset(dst + sz, ' ', nb);
2218 sz += nb;
2219 } else
2220 dst[sz++] = src[idx];
2221 ++idx;
2224 dst[sz] = '\0';
2225 *ptr = dst;
2226 return NULL;
2230 * Advance at most n columns from wline starting at offset off.
2231 * Return the index to the first character after the span operation.
2232 * Return the combined column width of all spanned wide characters in
2233 * *rcol.
2235 static int
2236 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2238 int width, i, cols = 0;
2240 if (n == 0) {
2241 *rcol = cols;
2242 return off;
2245 for (i = off; wline[i] != L'\0'; ++i) {
2246 if (wline[i] == L'\t')
2247 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2248 else
2249 width = wcwidth(wline[i]);
2251 if (width == -1) {
2252 width = 1;
2253 wline[i] = L'.';
2256 if (cols + width > n)
2257 break;
2258 cols += width;
2261 *rcol = cols;
2262 return i;
2266 * Format a line for display, ensuring that it won't overflow a width limit.
2267 * With scrolling, the width returned refers to the scrolled version of the
2268 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2270 static const struct got_error *
2271 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2272 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2274 const struct got_error *err = NULL;
2275 int cols;
2276 wchar_t *wline = NULL;
2277 char *exstr = NULL;
2278 size_t wlen;
2279 int i, scrollx;
2281 *wlinep = NULL;
2282 *widthp = 0;
2284 if (expand) {
2285 err = expand_tab(&exstr, line);
2286 if (err)
2287 return err;
2290 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2291 free(exstr);
2292 if (err)
2293 return err;
2295 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2297 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2298 wline[wlen - 1] = L'\0';
2299 wlen--;
2301 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2302 wline[wlen - 1] = L'\0';
2303 wlen--;
2306 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2307 wline[i] = L'\0';
2309 if (widthp)
2310 *widthp = cols;
2311 if (scrollxp)
2312 *scrollxp = scrollx;
2313 if (err)
2314 free(wline);
2315 else
2316 *wlinep = wline;
2317 return err;
2320 static const struct got_error*
2321 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2322 struct got_object_id *id, struct got_repository *repo)
2324 static const struct got_error *err = NULL;
2325 struct got_reflist_entry *re;
2326 char *s;
2327 const char *name;
2329 *refs_str = NULL;
2331 if (refs == NULL)
2332 return NULL;
2334 TAILQ_FOREACH(re, refs, entry) {
2335 struct got_tag_object *tag = NULL;
2336 struct got_object_id *ref_id;
2337 int cmp;
2339 name = got_ref_get_name(re->ref);
2340 if (strcmp(name, GOT_REF_HEAD) == 0)
2341 continue;
2342 if (strncmp(name, "refs/", 5) == 0)
2343 name += 5;
2344 if (strncmp(name, "got/", 4) == 0)
2345 continue;
2346 if (strncmp(name, "heads/", 6) == 0)
2347 name += 6;
2348 if (strncmp(name, "remotes/", 8) == 0) {
2349 name += 8;
2350 s = strstr(name, "/" GOT_REF_HEAD);
2351 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
2352 continue;
2354 err = got_ref_resolve(&ref_id, repo, re->ref);
2355 if (err)
2356 break;
2357 if (strncmp(name, "tags/", 5) == 0) {
2358 err = got_object_open_as_tag(&tag, repo, ref_id);
2359 if (err) {
2360 if (err->code != GOT_ERR_OBJ_TYPE) {
2361 free(ref_id);
2362 break;
2364 /* Ref points at something other than a tag. */
2365 err = NULL;
2366 tag = NULL;
2369 cmp = got_object_id_cmp(tag ?
2370 got_object_tag_get_object_id(tag) : ref_id, id);
2371 free(ref_id);
2372 if (tag)
2373 got_object_tag_close(tag);
2374 if (cmp != 0)
2375 continue;
2376 s = *refs_str;
2377 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2378 s ? ", " : "", name) == -1) {
2379 err = got_error_from_errno("asprintf");
2380 free(s);
2381 *refs_str = NULL;
2382 break;
2384 free(s);
2387 return err;
2390 static const struct got_error *
2391 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2392 int col_tab_align)
2394 char *smallerthan;
2396 smallerthan = strchr(author, '<');
2397 if (smallerthan && smallerthan[1] != '\0')
2398 author = smallerthan + 1;
2399 author[strcspn(author, "@>")] = '\0';
2400 return format_line(wauthor, author_width, NULL, author, 0, limit,
2401 col_tab_align, 0);
2404 static const struct got_error *
2405 draw_commit(struct tog_view *view, struct commit_queue_entry *entry,
2406 const size_t date_display_cols, int author_display_cols)
2408 struct tog_log_view_state *s = &view->state.log;
2409 const struct got_error *err = NULL;
2410 struct got_commit_object *commit = entry->commit;
2411 struct got_object_id *id = entry->id;
2412 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2413 char *refs_str = NULL;
2414 char *logmsg0 = NULL, *logmsg = NULL;
2415 char *author = NULL;
2416 wchar_t *wrefstr = NULL, *wlogmsg = NULL, *wauthor = NULL;
2417 int author_width, refstr_width, logmsg_width;
2418 char *newline, *line = NULL;
2419 int col, limit, scrollx, logmsg_x;
2420 const int avail = view->ncols, marker_column = author_display_cols + 1;
2421 struct tm tm;
2422 time_t committer_time;
2423 struct tog_color *tc;
2424 struct got_reflist_head *refs;
2426 committer_time = got_object_commit_get_committer_time(commit);
2427 if (gmtime_r(&committer_time, &tm) == NULL)
2428 return got_error_from_errno("gmtime_r");
2429 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2430 return got_error(GOT_ERR_NO_SPACE);
2432 if (avail <= date_display_cols)
2433 limit = MIN(sizeof(datebuf) - 1, avail);
2434 else
2435 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2436 tc = get_color(&s->colors, TOG_COLOR_DATE);
2437 if (tc)
2438 wattr_on(view->window,
2439 COLOR_PAIR(tc->colorpair), NULL);
2440 waddnstr(view->window, datebuf, limit);
2441 if (tc)
2442 wattr_off(view->window,
2443 COLOR_PAIR(tc->colorpair), NULL);
2444 col = limit;
2445 if (col > avail)
2446 goto done;
2448 if (avail >= 120) {
2449 char *id_str;
2450 err = got_object_id_str(&id_str, id);
2451 if (err)
2452 goto done;
2453 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2454 if (tc)
2455 wattr_on(view->window,
2456 COLOR_PAIR(tc->colorpair), NULL);
2457 wprintw(view->window, "%.8s ", id_str);
2458 if (tc)
2459 wattr_off(view->window,
2460 COLOR_PAIR(tc->colorpair), NULL);
2461 free(id_str);
2462 col += 9;
2463 if (col > avail)
2464 goto done;
2467 if (s->use_committer)
2468 author = strdup(got_object_commit_get_committer(commit));
2469 else
2470 author = strdup(got_object_commit_get_author(commit));
2471 if (author == NULL) {
2472 err = got_error_from_errno("strdup");
2473 goto done;
2475 err = format_author(&wauthor, &author_width, author, avail - col, col);
2476 if (err)
2477 goto done;
2478 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2479 if (tc)
2480 wattr_on(view->window,
2481 COLOR_PAIR(tc->colorpair), NULL);
2482 waddwstr(view->window, wauthor);
2483 col += author_width;
2484 while (col < avail && author_width < author_display_cols + 2) {
2485 if (tog_base_commit.id != NULL &&
2486 author_width == marker_column &&
2487 entry->idx == tog_base_commit.idx)
2488 waddch(view->window, tog_base_commit.marker);
2489 else
2490 waddch(view->window, ' ');
2491 col++;
2492 author_width++;
2494 if (tc)
2495 wattr_off(view->window,
2496 COLOR_PAIR(tc->colorpair), NULL);
2497 if (col > avail)
2498 goto done;
2500 err = got_object_commit_get_logmsg(&logmsg0, commit);
2501 if (err)
2502 goto done;
2503 logmsg = logmsg0;
2504 while (*logmsg == '\n')
2505 logmsg++;
2506 newline = strchr(logmsg, '\n');
2507 if (newline)
2508 *newline = '\0';
2510 limit = avail - col;
2511 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2512 limit--; /* for the border */
2514 /* Prepend reference labels to log message if possible .*/
2515 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, id);
2516 err = build_refs_str(&refs_str, refs, id, s->repo);
2517 if (err)
2518 goto done;
2519 if (refs_str) {
2520 char *rs;
2522 if (asprintf(&rs, "[%s]", refs_str) == -1) {
2523 err = got_error_from_errno("asprintf");
2524 goto done;
2526 err = format_line(&wrefstr, &refstr_width,
2527 &scrollx, rs, view->x, limit, col, 1);
2528 free(rs);
2529 if (err)
2530 goto done;
2531 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2532 if (tc)
2533 wattr_on(view->window,
2534 COLOR_PAIR(tc->colorpair), NULL);
2535 waddwstr(view->window, &wrefstr[scrollx]);
2536 if (tc)
2537 wattr_off(view->window,
2538 COLOR_PAIR(tc->colorpair), NULL);
2539 col += MAX(refstr_width, 0);
2540 if (col > avail)
2541 goto done;
2543 if (col < avail) {
2544 waddch(view->window, ' ');
2545 col++;
2548 if (refstr_width > 0)
2549 logmsg_x = 0;
2550 else {
2551 int unscrolled_refstr_width;
2552 size_t len = wcslen(wrefstr);
2555 * No need to check for -1 return value here since
2556 * unprintables have been replaced by span_wline().
2558 unscrolled_refstr_width = wcswidth(wrefstr, len);
2559 unscrolled_refstr_width += 1; /* trailing space */
2560 logmsg_x = view->x - unscrolled_refstr_width;
2563 limit = avail - col;
2564 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2565 limit--; /* for the border */
2566 } else
2567 logmsg_x = view->x;
2569 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, logmsg_x,
2570 limit, col, 1);
2571 if (err)
2572 goto done;
2573 waddwstr(view->window, &wlogmsg[scrollx]);
2574 col += MAX(logmsg_width, 0);
2575 while (col < avail) {
2576 waddch(view->window, ' ');
2577 col++;
2579 done:
2580 free(logmsg0);
2581 free(wlogmsg);
2582 free(wrefstr);
2583 free(refs_str);
2584 free(author);
2585 free(wauthor);
2586 free(line);
2587 return err;
2590 static struct commit_queue_entry *
2591 alloc_commit_queue_entry(struct got_commit_object *commit,
2592 struct got_object_id *id)
2594 struct commit_queue_entry *entry;
2595 struct got_object_id *dup;
2597 entry = calloc(1, sizeof(*entry));
2598 if (entry == NULL)
2599 return NULL;
2601 dup = got_object_id_dup(id);
2602 if (dup == NULL) {
2603 free(entry);
2604 return NULL;
2607 entry->id = dup;
2608 entry->commit = commit;
2609 return entry;
2612 static void
2613 pop_commit(struct commit_queue *commits)
2615 struct commit_queue_entry *entry;
2617 entry = TAILQ_FIRST(&commits->head);
2618 TAILQ_REMOVE(&commits->head, entry, entry);
2619 got_object_commit_close(entry->commit);
2620 commits->ncommits--;
2621 free(entry->id);
2622 free(entry);
2625 static void
2626 free_commits(struct commit_queue *commits)
2628 while (!TAILQ_EMPTY(&commits->head))
2629 pop_commit(commits);
2632 static const struct got_error *
2633 match_commit(int *have_match, struct got_object_id *id,
2634 struct got_commit_object *commit, regex_t *regex)
2636 const struct got_error *err = NULL;
2637 regmatch_t regmatch;
2638 char *id_str = NULL, *logmsg = NULL;
2640 *have_match = 0;
2642 err = got_object_id_str(&id_str, id);
2643 if (err)
2644 return err;
2646 err = got_object_commit_get_logmsg(&logmsg, commit);
2647 if (err)
2648 goto done;
2650 if (regexec(regex, got_object_commit_get_author(commit), 1,
2651 &regmatch, 0) == 0 ||
2652 regexec(regex, got_object_commit_get_committer(commit), 1,
2653 &regmatch, 0) == 0 ||
2654 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2655 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2656 *have_match = 1;
2657 done:
2658 free(id_str);
2659 free(logmsg);
2660 return err;
2663 static const struct got_error *
2664 queue_commits(struct tog_log_thread_args *a)
2666 const struct got_error *err = NULL;
2669 * We keep all commits open throughout the lifetime of the log
2670 * view in order to avoid having to re-fetch commits from disk
2671 * while updating the display.
2673 do {
2674 struct got_object_id id;
2675 struct got_commit_object *commit;
2676 struct commit_queue_entry *entry;
2677 int limit_match = 0;
2678 int errcode;
2680 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2681 NULL, NULL);
2682 if (err)
2683 break;
2685 err = got_object_open_as_commit(&commit, a->repo, &id);
2686 if (err)
2687 break;
2688 entry = alloc_commit_queue_entry(commit, &id);
2689 if (entry == NULL) {
2690 err = got_error_from_errno("alloc_commit_queue_entry");
2691 break;
2694 errcode = pthread_mutex_lock(&tog_mutex);
2695 if (errcode) {
2696 err = got_error_set_errno(errcode,
2697 "pthread_mutex_lock");
2698 break;
2701 entry->idx = a->real_commits->ncommits;
2702 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2703 a->real_commits->ncommits++;
2705 if (tog_base_commit.id != NULL && tog_base_commit.idx == -1 &&
2706 got_object_id_cmp(&id, tog_base_commit.id) == 0)
2707 tog_base_commit.idx = entry->idx;
2709 if (*a->limiting) {
2710 err = match_commit(&limit_match, &id, commit,
2711 a->limit_regex);
2712 if (err)
2713 break;
2715 if (limit_match) {
2716 struct commit_queue_entry *matched;
2718 matched = alloc_commit_queue_entry(
2719 entry->commit, entry->id);
2720 if (matched == NULL) {
2721 err = got_error_from_errno(
2722 "alloc_commit_queue_entry");
2723 break;
2725 matched->commit = entry->commit;
2726 got_object_commit_retain(entry->commit);
2728 matched->idx = a->limit_commits->ncommits;
2729 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2730 matched, entry);
2731 a->limit_commits->ncommits++;
2735 * This is how we signal log_thread() that we
2736 * have found a match, and that it should be
2737 * counted as a new entry for the view.
2739 a->limit_match = limit_match;
2742 if (*a->searching == TOG_SEARCH_FORWARD &&
2743 !*a->search_next_done) {
2744 int have_match;
2745 err = match_commit(&have_match, &id, commit, a->regex);
2746 if (err)
2747 break;
2749 if (*a->limiting) {
2750 if (limit_match && have_match)
2751 *a->search_next_done =
2752 TOG_SEARCH_HAVE_MORE;
2753 } else if (have_match)
2754 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2757 errcode = pthread_mutex_unlock(&tog_mutex);
2758 if (errcode && err == NULL)
2759 err = got_error_set_errno(errcode,
2760 "pthread_mutex_unlock");
2761 if (err)
2762 break;
2763 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2765 return err;
2768 static void
2769 select_commit(struct tog_log_view_state *s)
2771 struct commit_queue_entry *entry;
2772 int ncommits = 0;
2774 entry = s->first_displayed_entry;
2775 while (entry) {
2776 if (ncommits == s->selected) {
2777 s->selected_entry = entry;
2778 break;
2780 entry = TAILQ_NEXT(entry, entry);
2781 ncommits++;
2785 static const struct got_error *
2786 draw_commits(struct tog_view *view)
2788 const struct got_error *err = NULL;
2789 struct tog_log_view_state *s = &view->state.log;
2790 struct commit_queue_entry *entry = s->selected_entry;
2791 int limit = view->nlines;
2792 int width;
2793 int ncommits, author_cols = 4, refstr_cols;
2794 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2795 char *refs_str = NULL;
2796 wchar_t *wline;
2797 struct tog_color *tc;
2798 static const size_t date_display_cols = 12;
2799 struct got_reflist_head *refs;
2801 if (view_is_hsplit_top(view))
2802 --limit; /* account for border */
2804 if (s->selected_entry &&
2805 !(view->searching && view->search_next_done == 0)) {
2806 err = got_object_id_str(&id_str, s->selected_entry->id);
2807 if (err)
2808 return err;
2809 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2810 s->selected_entry->id);
2811 err = build_refs_str(&refs_str, refs, s->selected_entry->id,
2812 s->repo);
2813 if (err)
2814 goto done;
2817 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2818 halfdelay(10); /* disable fast refresh */
2820 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2821 if (asprintf(&ncommits_str, " [%d/%d] %s",
2822 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2823 (view->searching && !view->search_next_done) ?
2824 "searching..." : "loading...") == -1) {
2825 err = got_error_from_errno("asprintf");
2826 goto done;
2828 } else {
2829 const char *search_str = NULL;
2830 const char *limit_str = NULL;
2832 if (view->searching) {
2833 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2834 search_str = "no more matches";
2835 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2836 search_str = "no matches found";
2837 else if (!view->search_next_done)
2838 search_str = "searching...";
2841 if (s->limit_view && s->commits->ncommits == 0)
2842 limit_str = "no matches found";
2844 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2845 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2846 search_str ? search_str : (refs_str ? refs_str : ""),
2847 limit_str ? limit_str : "") == -1) {
2848 err = got_error_from_errno("asprintf");
2849 goto done;
2853 free(refs_str);
2854 refs_str = NULL;
2856 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2857 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2858 "........................................",
2859 s->in_repo_path, ncommits_str) == -1) {
2860 err = got_error_from_errno("asprintf");
2861 header = NULL;
2862 goto done;
2864 } else if (asprintf(&header, "commit %s%s",
2865 id_str ? id_str : "........................................",
2866 ncommits_str) == -1) {
2867 err = got_error_from_errno("asprintf");
2868 header = NULL;
2869 goto done;
2871 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2872 if (err)
2873 goto done;
2875 werase(view->window);
2877 if (view_needs_focus_indication(view))
2878 wstandout(view->window);
2879 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2880 if (tc)
2881 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2882 waddwstr(view->window, wline);
2883 while (width < view->ncols) {
2884 waddch(view->window, ' ');
2885 width++;
2887 if (tc)
2888 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2889 if (view_needs_focus_indication(view))
2890 wstandend(view->window);
2891 free(wline);
2892 if (limit <= 1)
2893 goto done;
2895 /* Grow author column size if necessary, and set view->maxx. */
2896 entry = s->first_displayed_entry;
2897 ncommits = 0;
2898 view->maxx = 0;
2899 while (entry) {
2900 struct got_commit_object *c = entry->commit;
2901 char *author, *eol, *msg, *msg0;
2902 wchar_t *wauthor, *wmsg;
2903 int width;
2904 if (ncommits >= limit - 1)
2905 break;
2906 if (s->use_committer)
2907 author = strdup(got_object_commit_get_committer(c));
2908 else
2909 author = strdup(got_object_commit_get_author(c));
2910 if (author == NULL) {
2911 err = got_error_from_errno("strdup");
2912 goto done;
2914 err = format_author(&wauthor, &width, author, COLS,
2915 date_display_cols);
2916 if (author_cols < width)
2917 author_cols = width;
2918 free(wauthor);
2919 free(author);
2920 if (err)
2921 goto done;
2922 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2923 entry->id);
2924 err = build_refs_str(&refs_str, refs, entry->id, s->repo);
2925 if (err)
2926 goto done;
2927 if (refs_str) {
2928 wchar_t *ws;
2929 err = format_line(&ws, &width, NULL, refs_str,
2930 0, INT_MAX, date_display_cols + author_cols, 0);
2931 free(ws);
2932 free(refs_str);
2933 refs_str = NULL;
2934 if (err)
2935 goto done;
2936 refstr_cols = width + 3; /* account for [ ] + space */
2937 } else
2938 refstr_cols = 0;
2939 err = got_object_commit_get_logmsg(&msg0, c);
2940 if (err)
2941 goto done;
2942 msg = msg0;
2943 while (*msg == '\n')
2944 ++msg;
2945 if ((eol = strchr(msg, '\n')))
2946 *eol = '\0';
2947 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2948 date_display_cols + author_cols + refstr_cols, 0);
2949 if (err)
2950 goto done;
2951 view->maxx = MAX(view->maxx, width + refstr_cols);
2952 free(msg0);
2953 free(wmsg);
2954 ncommits++;
2955 entry = TAILQ_NEXT(entry, entry);
2958 entry = s->first_displayed_entry;
2959 s->last_displayed_entry = s->first_displayed_entry;
2960 ncommits = 0;
2961 while (entry) {
2962 if (ncommits >= limit - 1)
2963 break;
2964 if (ncommits == s->selected)
2965 wstandout(view->window);
2966 err = draw_commit(view, entry, date_display_cols, author_cols);
2967 if (ncommits == s->selected)
2968 wstandend(view->window);
2969 if (err)
2970 goto done;
2971 ncommits++;
2972 s->last_displayed_entry = entry;
2973 entry = TAILQ_NEXT(entry, entry);
2976 view_border(view);
2977 done:
2978 free(id_str);
2979 free(refs_str);
2980 free(ncommits_str);
2981 free(header);
2982 return err;
2985 static void
2986 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2988 struct commit_queue_entry *entry;
2989 int nscrolled = 0;
2991 entry = TAILQ_FIRST(&s->commits->head);
2992 if (s->first_displayed_entry == entry)
2993 return;
2995 entry = s->first_displayed_entry;
2996 while (entry && nscrolled < maxscroll) {
2997 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2998 if (entry) {
2999 s->first_displayed_entry = entry;
3000 nscrolled++;
3005 static const struct got_error *
3006 trigger_log_thread(struct tog_view *view, int wait)
3008 struct tog_log_thread_args *ta = &view->state.log.thread_args;
3009 int errcode;
3011 if (!using_mock_io)
3012 halfdelay(1); /* fast refresh while loading commits */
3014 while (!ta->log_complete && !tog_thread_error &&
3015 (ta->commits_needed > 0 || ta->load_all)) {
3016 /* Wake the log thread. */
3017 errcode = pthread_cond_signal(&ta->need_commits);
3018 if (errcode)
3019 return got_error_set_errno(errcode,
3020 "pthread_cond_signal");
3023 * The mutex will be released while the view loop waits
3024 * in wgetch(), at which time the log thread will run.
3026 if (!wait)
3027 break;
3029 /* Display progress update in log view. */
3030 show_log_view(view);
3031 update_panels();
3032 doupdate();
3034 /* Wait right here while next commit is being loaded. */
3035 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
3036 if (errcode)
3037 return got_error_set_errno(errcode,
3038 "pthread_cond_wait");
3040 /* Display progress update in log view. */
3041 show_log_view(view);
3042 update_panels();
3043 doupdate();
3046 return NULL;
3049 static const struct got_error *
3050 request_log_commits(struct tog_view *view)
3052 struct tog_log_view_state *state = &view->state.log;
3053 const struct got_error *err = NULL;
3055 if (state->thread_args.log_complete)
3056 return NULL;
3058 state->thread_args.commits_needed += view->nscrolled;
3059 err = trigger_log_thread(view, 1);
3060 view->nscrolled = 0;
3062 return err;
3065 static const struct got_error *
3066 log_scroll_down(struct tog_view *view, int maxscroll)
3068 struct tog_log_view_state *s = &view->state.log;
3069 const struct got_error *err = NULL;
3070 struct commit_queue_entry *pentry;
3071 int nscrolled = 0, ncommits_needed;
3073 if (s->last_displayed_entry == NULL)
3074 return NULL;
3076 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
3077 if (s->commits->ncommits < ncommits_needed &&
3078 !s->thread_args.log_complete) {
3080 * Ask the log thread for required amount of commits.
3082 s->thread_args.commits_needed +=
3083 ncommits_needed - s->commits->ncommits;
3084 err = trigger_log_thread(view, 1);
3085 if (err)
3086 return err;
3089 do {
3090 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
3091 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
3092 break;
3094 s->last_displayed_entry = pentry ?
3095 pentry : s->last_displayed_entry;
3097 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3098 if (pentry == NULL)
3099 break;
3100 s->first_displayed_entry = pentry;
3101 } while (++nscrolled < maxscroll);
3103 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3104 view->nscrolled += nscrolled;
3105 else
3106 view->nscrolled = 0;
3108 return err;
3111 static const struct got_error *
3112 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3113 struct got_commit_object *commit, struct got_object_id *commit_id,
3114 struct tog_view *log_view, struct got_repository *repo)
3116 const struct got_error *err;
3117 struct got_object_qid *parent_id;
3118 struct tog_view *diff_view;
3120 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3121 if (diff_view == NULL)
3122 return got_error_from_errno("view_open");
3124 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3125 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3126 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3127 if (err == NULL)
3128 *new_view = diff_view;
3129 return err;
3132 static const struct got_error *
3133 tree_view_visit_subtree(struct tog_tree_view_state *s,
3134 struct got_tree_object *subtree)
3136 struct tog_parent_tree *parent;
3138 parent = calloc(1, sizeof(*parent));
3139 if (parent == NULL)
3140 return got_error_from_errno("calloc");
3142 parent->tree = s->tree;
3143 parent->first_displayed_entry = s->first_displayed_entry;
3144 parent->selected_entry = s->selected_entry;
3145 parent->selected = s->selected;
3146 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3147 s->tree = subtree;
3148 s->selected = 0;
3149 s->first_displayed_entry = NULL;
3150 return NULL;
3153 static const struct got_error *
3154 tree_view_walk_path(struct tog_tree_view_state *s,
3155 struct got_commit_object *commit, const char *path)
3157 const struct got_error *err = NULL;
3158 struct got_tree_object *tree = NULL;
3159 const char *p;
3160 char *slash, *subpath = NULL;
3162 /* Walk the path and open corresponding tree objects. */
3163 p = path;
3164 while (*p) {
3165 struct got_tree_entry *te;
3166 struct got_object_id *tree_id;
3167 char *te_name;
3169 while (p[0] == '/')
3170 p++;
3172 /* Ensure the correct subtree entry is selected. */
3173 slash = strchr(p, '/');
3174 if (slash == NULL)
3175 te_name = strdup(p);
3176 else
3177 te_name = strndup(p, slash - p);
3178 if (te_name == NULL) {
3179 err = got_error_from_errno("strndup");
3180 break;
3182 te = got_object_tree_find_entry(s->tree, te_name);
3183 if (te == NULL) {
3184 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3185 free(te_name);
3186 break;
3188 free(te_name);
3189 s->first_displayed_entry = s->selected_entry = te;
3191 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3192 break; /* jump to this file's entry */
3194 slash = strchr(p, '/');
3195 if (slash)
3196 subpath = strndup(path, slash - path);
3197 else
3198 subpath = strdup(path);
3199 if (subpath == NULL) {
3200 err = got_error_from_errno("strdup");
3201 break;
3204 err = got_object_id_by_path(&tree_id, s->repo, commit,
3205 subpath);
3206 if (err)
3207 break;
3209 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3210 free(tree_id);
3211 if (err)
3212 break;
3214 err = tree_view_visit_subtree(s, tree);
3215 if (err) {
3216 got_object_tree_close(tree);
3217 break;
3219 if (slash == NULL)
3220 break;
3221 free(subpath);
3222 subpath = NULL;
3223 p = slash;
3226 free(subpath);
3227 return err;
3230 static const struct got_error *
3231 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3232 struct commit_queue_entry *entry, const char *path,
3233 const char *head_ref_name, struct got_repository *repo)
3235 const struct got_error *err = NULL;
3236 struct tog_tree_view_state *s;
3237 struct tog_view *tree_view;
3239 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3240 if (tree_view == NULL)
3241 return got_error_from_errno("view_open");
3243 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3244 if (err)
3245 return err;
3246 s = &tree_view->state.tree;
3248 *new_view = tree_view;
3250 if (got_path_is_root_dir(path))
3251 return NULL;
3253 return tree_view_walk_path(s, entry->commit, path);
3256 static const struct got_error *
3257 block_signals_used_by_main_thread(void)
3259 sigset_t sigset;
3260 int errcode;
3262 if (sigemptyset(&sigset) == -1)
3263 return got_error_from_errno("sigemptyset");
3265 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3266 if (sigaddset(&sigset, SIGWINCH) == -1)
3267 return got_error_from_errno("sigaddset");
3268 if (sigaddset(&sigset, SIGCONT) == -1)
3269 return got_error_from_errno("sigaddset");
3270 if (sigaddset(&sigset, SIGINT) == -1)
3271 return got_error_from_errno("sigaddset");
3272 if (sigaddset(&sigset, SIGTERM) == -1)
3273 return got_error_from_errno("sigaddset");
3275 /* ncurses handles SIGTSTP */
3276 if (sigaddset(&sigset, SIGTSTP) == -1)
3277 return got_error_from_errno("sigaddset");
3279 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3280 if (errcode)
3281 return got_error_set_errno(errcode, "pthread_sigmask");
3283 return NULL;
3286 static void *
3287 log_thread(void *arg)
3289 const struct got_error *err = NULL;
3290 int errcode = 0;
3291 struct tog_log_thread_args *a = arg;
3292 int done = 0;
3295 * Sync startup with main thread such that we begin our
3296 * work once view_input() has released the mutex.
3298 errcode = pthread_mutex_lock(&tog_mutex);
3299 if (errcode) {
3300 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3301 return (void *)err;
3304 err = block_signals_used_by_main_thread();
3305 if (err) {
3306 pthread_mutex_unlock(&tog_mutex);
3307 goto done;
3310 while (!done && !err && !tog_fatal_signal_received()) {
3311 errcode = pthread_mutex_unlock(&tog_mutex);
3312 if (errcode) {
3313 err = got_error_set_errno(errcode,
3314 "pthread_mutex_unlock");
3315 goto done;
3317 err = queue_commits(a);
3318 if (err) {
3319 if (err->code != GOT_ERR_ITER_COMPLETED)
3320 goto done;
3321 err = NULL;
3322 done = 1;
3323 } else if (a->commits_needed > 0 && !a->load_all) {
3324 if (*a->limiting) {
3325 if (a->limit_match)
3326 a->commits_needed--;
3327 } else
3328 a->commits_needed--;
3331 errcode = pthread_mutex_lock(&tog_mutex);
3332 if (errcode) {
3333 err = got_error_set_errno(errcode,
3334 "pthread_mutex_lock");
3335 goto done;
3336 } else if (*a->quit)
3337 done = 1;
3338 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3339 *a->first_displayed_entry =
3340 TAILQ_FIRST(&a->limit_commits->head);
3341 *a->selected_entry = *a->first_displayed_entry;
3342 } else if (*a->first_displayed_entry == NULL) {
3343 *a->first_displayed_entry =
3344 TAILQ_FIRST(&a->real_commits->head);
3345 *a->selected_entry = *a->first_displayed_entry;
3348 errcode = pthread_cond_signal(&a->commit_loaded);
3349 if (errcode) {
3350 err = got_error_set_errno(errcode,
3351 "pthread_cond_signal");
3352 pthread_mutex_unlock(&tog_mutex);
3353 goto done;
3356 if (done)
3357 a->commits_needed = 0;
3358 else {
3359 if (a->commits_needed == 0 && !a->load_all) {
3360 errcode = pthread_cond_wait(&a->need_commits,
3361 &tog_mutex);
3362 if (errcode) {
3363 err = got_error_set_errno(errcode,
3364 "pthread_cond_wait");
3365 pthread_mutex_unlock(&tog_mutex);
3366 goto done;
3368 if (*a->quit)
3369 done = 1;
3373 a->log_complete = 1;
3374 errcode = pthread_mutex_unlock(&tog_mutex);
3375 if (errcode)
3376 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3377 done:
3378 if (err) {
3379 tog_thread_error = 1;
3380 pthread_cond_signal(&a->commit_loaded);
3382 return (void *)err;
3385 static const struct got_error *
3386 stop_log_thread(struct tog_log_view_state *s)
3388 const struct got_error *err = NULL, *thread_err = NULL;
3389 int errcode;
3391 if (s->thread) {
3392 s->quit = 1;
3393 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3394 if (errcode)
3395 return got_error_set_errno(errcode,
3396 "pthread_cond_signal");
3397 errcode = pthread_mutex_unlock(&tog_mutex);
3398 if (errcode)
3399 return got_error_set_errno(errcode,
3400 "pthread_mutex_unlock");
3401 errcode = pthread_join(s->thread, (void **)&thread_err);
3402 if (errcode)
3403 return got_error_set_errno(errcode, "pthread_join");
3404 errcode = pthread_mutex_lock(&tog_mutex);
3405 if (errcode)
3406 return got_error_set_errno(errcode,
3407 "pthread_mutex_lock");
3408 s->thread = NULL;
3411 if (s->thread_args.repo) {
3412 err = got_repo_close(s->thread_args.repo);
3413 s->thread_args.repo = NULL;
3416 if (s->thread_args.pack_fds) {
3417 const struct got_error *pack_err =
3418 got_repo_pack_fds_close(s->thread_args.pack_fds);
3419 if (err == NULL)
3420 err = pack_err;
3421 s->thread_args.pack_fds = NULL;
3424 if (s->thread_args.graph) {
3425 got_commit_graph_close(s->thread_args.graph);
3426 s->thread_args.graph = NULL;
3429 return err ? err : thread_err;
3432 static const struct got_error *
3433 close_log_view(struct tog_view *view)
3435 const struct got_error *err = NULL;
3436 struct tog_log_view_state *s = &view->state.log;
3437 int errcode;
3439 err = stop_log_thread(s);
3441 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3442 if (errcode && err == NULL)
3443 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3445 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3446 if (errcode && err == NULL)
3447 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3449 free_commits(&s->limit_commits);
3450 free_commits(&s->real_commits);
3451 free(s->in_repo_path);
3452 s->in_repo_path = NULL;
3453 free(s->start_id);
3454 s->start_id = NULL;
3455 free(s->head_ref_name);
3456 s->head_ref_name = NULL;
3457 return err;
3461 * We use two queues to implement the limit feature: first consists of
3462 * commits matching the current limit_regex; second is the real queue
3463 * of all known commits (real_commits). When the user starts limiting,
3464 * we swap queues such that all movement and displaying functionality
3465 * works with very slight change.
3467 static const struct got_error *
3468 limit_log_view(struct tog_view *view)
3470 struct tog_log_view_state *s = &view->state.log;
3471 struct commit_queue_entry *entry;
3472 struct tog_view *v = view;
3473 const struct got_error *err = NULL;
3474 char pattern[1024];
3475 int ret;
3477 if (view_is_hsplit_top(view))
3478 v = view->child;
3479 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3480 v = view->parent;
3482 /* Get the pattern */
3483 wmove(v->window, v->nlines - 1, 0);
3484 wclrtoeol(v->window);
3485 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3486 nodelay(v->window, FALSE);
3487 nocbreak();
3488 echo();
3489 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3490 cbreak();
3491 noecho();
3492 nodelay(v->window, TRUE);
3493 if (ret == ERR)
3494 return NULL;
3496 if (*pattern == '\0') {
3498 * Safety measure for the situation where the user
3499 * resets limit without previously limiting anything.
3501 if (!s->limit_view)
3502 return NULL;
3505 * User could have pressed Ctrl+L, which refreshed the
3506 * commit queues, it means we can't save previously
3507 * (before limit took place) displayed entries,
3508 * because they would point to already free'ed memory,
3509 * so we are forced to always select first entry of
3510 * the queue.
3512 s->commits = &s->real_commits;
3513 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3514 s->selected_entry = s->first_displayed_entry;
3515 s->selected = 0;
3516 s->limit_view = 0;
3518 return NULL;
3521 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3522 return NULL;
3524 s->limit_view = 1;
3526 /* Clear the screen while loading limit view */
3527 s->first_displayed_entry = NULL;
3528 s->last_displayed_entry = NULL;
3529 s->selected_entry = NULL;
3530 s->commits = &s->limit_commits;
3532 /* Prepare limit queue for new search */
3533 free_commits(&s->limit_commits);
3534 s->limit_commits.ncommits = 0;
3536 /* First process commits, which are in queue already */
3537 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3538 int have_match = 0;
3540 err = match_commit(&have_match, entry->id,
3541 entry->commit, &s->limit_regex);
3542 if (err)
3543 return err;
3545 if (have_match) {
3546 struct commit_queue_entry *matched;
3548 matched = alloc_commit_queue_entry(entry->commit,
3549 entry->id);
3550 if (matched == NULL) {
3551 err = got_error_from_errno(
3552 "alloc_commit_queue_entry");
3553 break;
3555 matched->commit = entry->commit;
3556 got_object_commit_retain(entry->commit);
3558 matched->idx = s->limit_commits.ncommits;
3559 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3560 matched, entry);
3561 s->limit_commits.ncommits++;
3565 /* Second process all the commits, until we fill the screen */
3566 if (s->limit_commits.ncommits < view->nlines - 1 &&
3567 !s->thread_args.log_complete) {
3568 s->thread_args.commits_needed +=
3569 view->nlines - s->limit_commits.ncommits - 1;
3570 err = trigger_log_thread(view, 1);
3571 if (err)
3572 return err;
3575 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3576 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3577 s->selected = 0;
3579 return NULL;
3582 static const struct got_error *
3583 search_start_log_view(struct tog_view *view)
3585 struct tog_log_view_state *s = &view->state.log;
3587 s->matched_entry = NULL;
3588 s->search_entry = NULL;
3589 return NULL;
3592 static const struct got_error *
3593 search_next_log_view(struct tog_view *view)
3595 const struct got_error *err = NULL;
3596 struct tog_log_view_state *s = &view->state.log;
3597 struct commit_queue_entry *entry;
3599 /* Display progress update in log view. */
3600 show_log_view(view);
3601 update_panels();
3602 doupdate();
3604 if (s->search_entry) {
3605 int errcode, ch;
3606 errcode = pthread_mutex_unlock(&tog_mutex);
3607 if (errcode)
3608 return got_error_set_errno(errcode,
3609 "pthread_mutex_unlock");
3610 ch = wgetch(view->window);
3611 errcode = pthread_mutex_lock(&tog_mutex);
3612 if (errcode)
3613 return got_error_set_errno(errcode,
3614 "pthread_mutex_lock");
3615 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3616 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3617 return NULL;
3619 if (view->searching == TOG_SEARCH_FORWARD)
3620 entry = TAILQ_NEXT(s->search_entry, entry);
3621 else
3622 entry = TAILQ_PREV(s->search_entry,
3623 commit_queue_head, entry);
3624 } else if (s->matched_entry) {
3626 * If the user has moved the cursor after we hit a match,
3627 * the position from where we should continue searching
3628 * might have changed.
3630 if (view->searching == TOG_SEARCH_FORWARD)
3631 entry = TAILQ_NEXT(s->selected_entry, entry);
3632 else
3633 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3634 entry);
3635 } else {
3636 entry = s->selected_entry;
3639 while (1) {
3640 int have_match = 0;
3642 if (entry == NULL) {
3643 if (s->thread_args.log_complete ||
3644 view->searching == TOG_SEARCH_BACKWARD) {
3645 view->search_next_done =
3646 (s->matched_entry == NULL ?
3647 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3648 s->search_entry = NULL;
3649 return NULL;
3652 * Poke the log thread for more commits and return,
3653 * allowing the main loop to make progress. Search
3654 * will resume at s->search_entry once we come back.
3656 s->thread_args.commits_needed++;
3657 return trigger_log_thread(view, 0);
3660 err = match_commit(&have_match, entry->id, entry->commit,
3661 &view->regex);
3662 if (err)
3663 break;
3664 if (have_match) {
3665 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3666 s->matched_entry = entry;
3667 break;
3670 s->search_entry = entry;
3671 if (view->searching == TOG_SEARCH_FORWARD)
3672 entry = TAILQ_NEXT(entry, entry);
3673 else
3674 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3677 if (s->matched_entry) {
3678 int cur = s->selected_entry->idx;
3679 while (cur < s->matched_entry->idx) {
3680 err = input_log_view(NULL, view, KEY_DOWN);
3681 if (err)
3682 return err;
3683 cur++;
3685 while (cur > s->matched_entry->idx) {
3686 err = input_log_view(NULL, view, KEY_UP);
3687 if (err)
3688 return err;
3689 cur--;
3693 s->search_entry = NULL;
3695 return NULL;
3698 static const struct got_error *
3699 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3700 struct got_repository *repo, const char *head_ref_name,
3701 const char *in_repo_path, int log_branches)
3703 const struct got_error *err = NULL;
3704 struct tog_log_view_state *s = &view->state.log;
3705 struct got_repository *thread_repo = NULL;
3706 struct got_commit_graph *thread_graph = NULL;
3707 int errcode;
3709 if (in_repo_path != s->in_repo_path) {
3710 free(s->in_repo_path);
3711 s->in_repo_path = strdup(in_repo_path);
3712 if (s->in_repo_path == NULL) {
3713 err = got_error_from_errno("strdup");
3714 goto done;
3718 /* The commit queue only contains commits being displayed. */
3719 TAILQ_INIT(&s->real_commits.head);
3720 s->real_commits.ncommits = 0;
3721 s->commits = &s->real_commits;
3723 TAILQ_INIT(&s->limit_commits.head);
3724 s->limit_view = 0;
3725 s->limit_commits.ncommits = 0;
3727 s->repo = repo;
3728 if (head_ref_name) {
3729 s->head_ref_name = strdup(head_ref_name);
3730 if (s->head_ref_name == NULL) {
3731 err = got_error_from_errno("strdup");
3732 goto done;
3735 s->start_id = got_object_id_dup(start_id);
3736 if (s->start_id == NULL) {
3737 err = got_error_from_errno("got_object_id_dup");
3738 goto done;
3740 s->log_branches = log_branches;
3741 s->use_committer = 1;
3743 STAILQ_INIT(&s->colors);
3744 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3745 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3746 get_color_value("TOG_COLOR_COMMIT"));
3747 if (err)
3748 goto done;
3749 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3750 get_color_value("TOG_COLOR_AUTHOR"));
3751 if (err) {
3752 free_colors(&s->colors);
3753 goto done;
3755 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3756 get_color_value("TOG_COLOR_DATE"));
3757 if (err) {
3758 free_colors(&s->colors);
3759 goto done;
3763 view->show = show_log_view;
3764 view->input = input_log_view;
3765 view->resize = resize_log_view;
3766 view->close = close_log_view;
3767 view->search_start = search_start_log_view;
3768 view->search_next = search_next_log_view;
3770 if (s->thread_args.pack_fds == NULL) {
3771 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3772 if (err)
3773 goto done;
3775 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3776 s->thread_args.pack_fds);
3777 if (err)
3778 goto done;
3779 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3780 !s->log_branches);
3781 if (err)
3782 goto done;
3783 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3784 s->repo, NULL, NULL);
3785 if (err)
3786 goto done;
3788 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3789 if (errcode) {
3790 err = got_error_set_errno(errcode, "pthread_cond_init");
3791 goto done;
3793 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3794 if (errcode) {
3795 err = got_error_set_errno(errcode, "pthread_cond_init");
3796 goto done;
3799 s->thread_args.commits_needed = view->nlines;
3800 s->thread_args.graph = thread_graph;
3801 s->thread_args.real_commits = &s->real_commits;
3802 s->thread_args.limit_commits = &s->limit_commits;
3803 s->thread_args.in_repo_path = s->in_repo_path;
3804 s->thread_args.start_id = s->start_id;
3805 s->thread_args.repo = thread_repo;
3806 s->thread_args.log_complete = 0;
3807 s->thread_args.quit = &s->quit;
3808 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3809 s->thread_args.selected_entry = &s->selected_entry;
3810 s->thread_args.searching = &view->searching;
3811 s->thread_args.search_next_done = &view->search_next_done;
3812 s->thread_args.regex = &view->regex;
3813 s->thread_args.limiting = &s->limit_view;
3814 s->thread_args.limit_regex = &s->limit_regex;
3815 s->thread_args.limit_commits = &s->limit_commits;
3816 done:
3817 if (err) {
3818 if (view->close == NULL)
3819 close_log_view(view);
3820 view_close(view);
3822 return err;
3825 static const struct got_error *
3826 show_log_view(struct tog_view *view)
3828 const struct got_error *err;
3829 struct tog_log_view_state *s = &view->state.log;
3831 if (s->thread == NULL) {
3832 int errcode = pthread_create(&s->thread, NULL, log_thread,
3833 &s->thread_args);
3834 if (errcode)
3835 return got_error_set_errno(errcode, "pthread_create");
3836 if (s->thread_args.commits_needed > 0) {
3837 err = trigger_log_thread(view, 1);
3838 if (err)
3839 return err;
3843 return draw_commits(view);
3846 static void
3847 log_move_cursor_up(struct tog_view *view, int page, int home)
3849 struct tog_log_view_state *s = &view->state.log;
3851 if (s->first_displayed_entry == NULL)
3852 return;
3853 if (s->selected_entry->idx == 0)
3854 view->count = 0;
3856 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3857 || home)
3858 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3860 if (!page && !home && s->selected > 0)
3861 --s->selected;
3862 else
3863 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3865 select_commit(s);
3866 return;
3869 static const struct got_error *
3870 log_move_cursor_down(struct tog_view *view, int page)
3872 struct tog_log_view_state *s = &view->state.log;
3873 const struct got_error *err = NULL;
3874 int eos = view->nlines - 2;
3876 if (s->first_displayed_entry == NULL)
3877 return NULL;
3879 if (s->thread_args.log_complete &&
3880 s->selected_entry->idx >= s->commits->ncommits - 1)
3881 return NULL;
3883 if (view_is_hsplit_top(view))
3884 --eos; /* border consumes the last line */
3886 if (!page) {
3887 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3888 ++s->selected;
3889 else
3890 err = log_scroll_down(view, 1);
3891 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3892 struct commit_queue_entry *entry;
3893 int n;
3895 s->selected = 0;
3896 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3897 s->last_displayed_entry = entry;
3898 for (n = 0; n <= eos; n++) {
3899 if (entry == NULL)
3900 break;
3901 s->first_displayed_entry = entry;
3902 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3904 if (n > 0)
3905 s->selected = n - 1;
3906 } else {
3907 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3908 s->thread_args.log_complete)
3909 s->selected += MIN(page,
3910 s->commits->ncommits - s->selected_entry->idx - 1);
3911 else
3912 err = log_scroll_down(view, page);
3914 if (err)
3915 return err;
3918 * We might necessarily overshoot in horizontal
3919 * splits; if so, select the last displayed commit.
3921 if (s->first_displayed_entry && s->last_displayed_entry) {
3922 s->selected = MIN(s->selected,
3923 s->last_displayed_entry->idx -
3924 s->first_displayed_entry->idx);
3927 select_commit(s);
3929 if (s->thread_args.log_complete &&
3930 s->selected_entry->idx == s->commits->ncommits - 1)
3931 view->count = 0;
3933 return NULL;
3936 static void
3937 view_get_split(struct tog_view *view, int *y, int *x)
3939 *x = 0;
3940 *y = 0;
3942 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3943 if (view->child && view->child->resized_y)
3944 *y = view->child->resized_y;
3945 else if (view->resized_y)
3946 *y = view->resized_y;
3947 else
3948 *y = view_split_begin_y(view->lines);
3949 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3950 if (view->child && view->child->resized_x)
3951 *x = view->child->resized_x;
3952 else if (view->resized_x)
3953 *x = view->resized_x;
3954 else
3955 *x = view_split_begin_x(view->begin_x);
3959 /* Split view horizontally at y and offset view->state->selected line. */
3960 static const struct got_error *
3961 view_init_hsplit(struct tog_view *view, int y)
3963 const struct got_error *err = NULL;
3965 view->nlines = y;
3966 view->ncols = COLS;
3967 err = view_resize(view);
3968 if (err)
3969 return err;
3971 err = offset_selection_down(view);
3973 return err;
3976 static const struct got_error *
3977 log_goto_line(struct tog_view *view, int nlines)
3979 const struct got_error *err = NULL;
3980 struct tog_log_view_state *s = &view->state.log;
3981 int g, idx = s->selected_entry->idx;
3983 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3984 return NULL;
3986 g = view->gline;
3987 view->gline = 0;
3989 if (g >= s->first_displayed_entry->idx + 1 &&
3990 g <= s->last_displayed_entry->idx + 1 &&
3991 g - s->first_displayed_entry->idx - 1 < nlines) {
3992 s->selected = g - s->first_displayed_entry->idx - 1;
3993 select_commit(s);
3994 return NULL;
3997 if (idx + 1 < g) {
3998 err = log_move_cursor_down(view, g - idx - 1);
3999 if (!err && g > s->selected_entry->idx + 1)
4000 err = log_move_cursor_down(view,
4001 g - s->first_displayed_entry->idx - 1);
4002 if (err)
4003 return err;
4004 } else if (idx + 1 > g)
4005 log_move_cursor_up(view, idx - g + 1, 0);
4007 if (g < nlines && s->first_displayed_entry->idx == 0)
4008 s->selected = g - 1;
4010 select_commit(s);
4011 return NULL;
4015 static void
4016 horizontal_scroll_input(struct tog_view *view, int ch)
4019 switch (ch) {
4020 case KEY_LEFT:
4021 case 'h':
4022 view->x -= MIN(view->x, 2);
4023 if (view->x <= 0)
4024 view->count = 0;
4025 break;
4026 case KEY_RIGHT:
4027 case 'l':
4028 if (view->x + view->ncols / 2 < view->maxx)
4029 view->x += 2;
4030 else
4031 view->count = 0;
4032 break;
4033 case '0':
4034 view->x = 0;
4035 break;
4036 case '$':
4037 view->x = MAX(view->maxx - view->ncols / 2, 0);
4038 view->count = 0;
4039 break;
4040 default:
4041 break;
4045 static const struct got_error *
4046 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
4048 const struct got_error *err = NULL;
4049 struct tog_log_view_state *s = &view->state.log;
4050 int eos, nscroll;
4052 if (s->thread_args.load_all) {
4053 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
4054 s->thread_args.load_all = 0;
4055 else if (s->thread_args.log_complete) {
4056 err = log_move_cursor_down(view, s->commits->ncommits);
4057 s->thread_args.load_all = 0;
4059 if (err)
4060 return err;
4063 eos = nscroll = view->nlines - 1;
4064 if (view_is_hsplit_top(view))
4065 --eos; /* border */
4067 if (view->gline)
4068 return log_goto_line(view, eos);
4070 switch (ch) {
4071 case '&':
4072 err = limit_log_view(view);
4073 break;
4074 case 'q':
4075 s->quit = 1;
4076 break;
4077 case '0':
4078 case '$':
4079 case KEY_RIGHT:
4080 case 'l':
4081 case KEY_LEFT:
4082 case 'h':
4083 horizontal_scroll_input(view, ch);
4084 break;
4085 case 'k':
4086 case KEY_UP:
4087 case '<':
4088 case ',':
4089 case CTRL('p'):
4090 log_move_cursor_up(view, 0, 0);
4091 break;
4092 case 'g':
4093 case '=':
4094 case KEY_HOME:
4095 log_move_cursor_up(view, 0, 1);
4096 view->count = 0;
4097 break;
4098 case CTRL('u'):
4099 case 'u':
4100 nscroll /= 2;
4101 /* FALL THROUGH */
4102 case KEY_PPAGE:
4103 case CTRL('b'):
4104 case 'b':
4105 log_move_cursor_up(view, nscroll, 0);
4106 break;
4107 case 'j':
4108 case KEY_DOWN:
4109 case '>':
4110 case '.':
4111 case CTRL('n'):
4112 err = log_move_cursor_down(view, 0);
4113 break;
4114 case '@':
4115 s->use_committer = !s->use_committer;
4116 view->action = s->use_committer ?
4117 "show committer" : "show commit author";
4118 break;
4119 case 'G':
4120 case '*':
4121 case KEY_END: {
4122 /* We don't know yet how many commits, so we're forced to
4123 * traverse them all. */
4124 view->count = 0;
4125 s->thread_args.load_all = 1;
4126 if (!s->thread_args.log_complete)
4127 return trigger_log_thread(view, 0);
4128 err = log_move_cursor_down(view, s->commits->ncommits);
4129 s->thread_args.load_all = 0;
4130 break;
4132 case CTRL('d'):
4133 case 'd':
4134 nscroll /= 2;
4135 /* FALL THROUGH */
4136 case KEY_NPAGE:
4137 case CTRL('f'):
4138 case 'f':
4139 case ' ':
4140 err = log_move_cursor_down(view, nscroll);
4141 break;
4142 case KEY_RESIZE:
4143 if (s->selected > view->nlines - 2)
4144 s->selected = view->nlines - 2;
4145 if (s->selected > s->commits->ncommits - 1)
4146 s->selected = s->commits->ncommits - 1;
4147 select_commit(s);
4148 if (s->commits->ncommits < view->nlines - 1 &&
4149 !s->thread_args.log_complete) {
4150 s->thread_args.commits_needed += (view->nlines - 1) -
4151 s->commits->ncommits;
4152 err = trigger_log_thread(view, 1);
4154 break;
4155 case KEY_ENTER:
4156 case '\r':
4157 view->count = 0;
4158 if (s->selected_entry == NULL)
4159 break;
4160 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4161 break;
4162 case 'T':
4163 view->count = 0;
4164 if (s->selected_entry == NULL)
4165 break;
4166 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4167 break;
4168 case KEY_BACKSPACE:
4169 case CTRL('l'):
4170 case 'B':
4171 view->count = 0;
4172 if (ch == KEY_BACKSPACE &&
4173 got_path_is_root_dir(s->in_repo_path))
4174 break;
4175 err = stop_log_thread(s);
4176 if (err)
4177 return err;
4178 if (ch == KEY_BACKSPACE) {
4179 char *parent_path;
4180 err = got_path_dirname(&parent_path, s->in_repo_path);
4181 if (err)
4182 return err;
4183 free(s->in_repo_path);
4184 s->in_repo_path = parent_path;
4185 s->thread_args.in_repo_path = s->in_repo_path;
4186 } else if (ch == CTRL('l')) {
4187 struct got_object_id *start_id;
4188 err = got_repo_match_object_id(&start_id, NULL,
4189 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4190 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4191 if (err) {
4192 if (s->head_ref_name == NULL ||
4193 err->code != GOT_ERR_NOT_REF)
4194 return err;
4195 /* Try to cope with deleted references. */
4196 free(s->head_ref_name);
4197 s->head_ref_name = NULL;
4198 err = got_repo_match_object_id(&start_id,
4199 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4200 &tog_refs, s->repo);
4201 if (err)
4202 return err;
4204 free(s->start_id);
4205 s->start_id = start_id;
4206 s->thread_args.start_id = s->start_id;
4207 } else /* 'B' */
4208 s->log_branches = !s->log_branches;
4210 if (s->thread_args.pack_fds == NULL) {
4211 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4212 if (err)
4213 return err;
4215 err = got_repo_open(&s->thread_args.repo,
4216 got_repo_get_path(s->repo), NULL,
4217 s->thread_args.pack_fds);
4218 if (err)
4219 return err;
4220 tog_free_refs();
4221 err = tog_load_refs(s->repo, 0);
4222 if (err)
4223 return err;
4224 err = got_commit_graph_open(&s->thread_args.graph,
4225 s->in_repo_path, !s->log_branches);
4226 if (err)
4227 return err;
4228 err = got_commit_graph_iter_start(s->thread_args.graph,
4229 s->start_id, s->repo, NULL, NULL);
4230 if (err)
4231 return err;
4232 free_commits(&s->real_commits);
4233 free_commits(&s->limit_commits);
4234 s->first_displayed_entry = NULL;
4235 s->last_displayed_entry = NULL;
4236 s->selected_entry = NULL;
4237 s->selected = 0;
4238 s->thread_args.log_complete = 0;
4239 s->quit = 0;
4240 s->thread_args.commits_needed = view->lines;
4241 s->matched_entry = NULL;
4242 s->search_entry = NULL;
4243 view->offset = 0;
4244 break;
4245 case 'R':
4246 view->count = 0;
4247 err = view_request_new(new_view, view, TOG_VIEW_REF);
4248 break;
4249 default:
4250 view->count = 0;
4251 break;
4254 return err;
4257 static const struct got_error *
4258 apply_unveil(const char *repo_path, const char *worktree_path)
4260 const struct got_error *error;
4262 #ifdef PROFILE
4263 if (unveil("gmon.out", "rwc") != 0)
4264 return got_error_from_errno2("unveil", "gmon.out");
4265 #endif
4266 if (repo_path && unveil(repo_path, "r") != 0)
4267 return got_error_from_errno2("unveil", repo_path);
4269 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4270 return got_error_from_errno2("unveil", worktree_path);
4272 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4273 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4275 error = got_privsep_unveil_exec_helpers();
4276 if (error != NULL)
4277 return error;
4279 if (unveil(NULL, NULL) != 0)
4280 return got_error_from_errno("unveil");
4282 return NULL;
4285 static const struct got_error *
4286 init_mock_term(const char *test_script_path)
4288 const struct got_error *err = NULL;
4289 const char *screen_dump_path;
4290 int in;
4292 if (test_script_path == NULL || *test_script_path == '\0')
4293 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4295 tog_io.f = fopen(test_script_path, "re");
4296 if (tog_io.f == NULL) {
4297 err = got_error_from_errno_fmt("fopen: %s",
4298 test_script_path);
4299 goto done;
4302 /* test mode, we don't want any output */
4303 tog_io.cout = fopen("/dev/null", "w+");
4304 if (tog_io.cout == NULL) {
4305 err = got_error_from_errno2("fopen", "/dev/null");
4306 goto done;
4309 in = dup(fileno(tog_io.cout));
4310 if (in == -1) {
4311 err = got_error_from_errno("dup");
4312 goto done;
4314 tog_io.cin = fdopen(in, "r");
4315 if (tog_io.cin == NULL) {
4316 err = got_error_from_errno("fdopen");
4317 close(in);
4318 goto done;
4321 screen_dump_path = getenv("TOG_SCR_DUMP");
4322 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4323 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4324 tog_io.sdump = fopen(screen_dump_path, "we");
4325 if (tog_io.sdump == NULL) {
4326 err = got_error_from_errno2("fopen", screen_dump_path);
4327 goto done;
4330 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4331 err = got_error_from_errno("fseeko");
4332 goto done;
4335 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4336 err = got_error_msg(GOT_ERR_IO,
4337 "newterm: failed to initialise curses");
4339 using_mock_io = 1;
4341 done:
4342 if (err)
4343 tog_io_close();
4344 return err;
4347 static void
4348 init_curses(void)
4351 * Override default signal handlers before starting ncurses.
4352 * This should prevent ncurses from installing its own
4353 * broken cleanup() signal handler.
4355 signal(SIGWINCH, tog_sigwinch);
4356 signal(SIGPIPE, tog_sigpipe);
4357 signal(SIGCONT, tog_sigcont);
4358 signal(SIGINT, tog_sigint);
4359 signal(SIGTERM, tog_sigterm);
4361 if (using_mock_io) /* In test mode we use a fake terminal */
4362 return;
4364 initscr();
4366 cbreak();
4367 halfdelay(1); /* Fast refresh while initial view is loading. */
4368 noecho();
4369 nonl();
4370 intrflush(stdscr, FALSE);
4371 keypad(stdscr, TRUE);
4372 curs_set(0);
4373 if (getenv("TOG_COLORS") != NULL) {
4374 start_color();
4375 use_default_colors();
4378 return;
4381 static const struct got_error *
4382 set_tog_base_commit(struct got_repository *repo, struct got_worktree *worktree)
4384 tog_base_commit.id = got_object_id_dup(
4385 got_worktree_get_base_commit_id(worktree));
4386 if (tog_base_commit.id == NULL)
4387 return got_error_from_errno( "got_object_id_dup");
4389 tog_base_commit.idx = -1;
4391 return got_worktree_get_state(&tog_base_commit.marker, repo,
4392 worktree);
4395 static const struct got_error *
4396 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4397 struct got_repository *repo, struct got_worktree *worktree)
4399 const struct got_error *err = NULL;
4401 if (argc == 0) {
4402 *in_repo_path = strdup("/");
4403 if (*in_repo_path == NULL)
4404 return got_error_from_errno("strdup");
4405 return NULL;
4408 if (worktree) {
4409 const char *prefix = got_worktree_get_path_prefix(worktree);
4410 char *p;
4412 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4413 if (err)
4414 return err;
4415 if (asprintf(in_repo_path, "%s%s%s", prefix,
4416 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4417 p) == -1) {
4418 err = got_error_from_errno("asprintf");
4419 *in_repo_path = NULL;
4421 free(p);
4422 } else
4423 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4425 return err;
4428 static const struct got_error *
4429 cmd_log(int argc, char *argv[])
4431 const struct got_error *error;
4432 struct got_repository *repo = NULL;
4433 struct got_worktree *worktree = NULL;
4434 struct got_object_id *start_id = NULL;
4435 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4436 char *keyword_idstr = NULL, *start_commit = NULL, *label = NULL;
4437 struct got_reference *ref = NULL;
4438 const char *head_ref_name = NULL;
4439 int ch, log_branches = 0;
4440 struct tog_view *view;
4441 int *pack_fds = NULL;
4443 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4444 switch (ch) {
4445 case 'b':
4446 log_branches = 1;
4447 break;
4448 case 'c':
4449 start_commit = optarg;
4450 break;
4451 case 'r':
4452 repo_path = realpath(optarg, NULL);
4453 if (repo_path == NULL)
4454 return got_error_from_errno2("realpath",
4455 optarg);
4456 break;
4457 default:
4458 usage_log();
4459 /* NOTREACHED */
4463 argc -= optind;
4464 argv += optind;
4466 if (argc > 1)
4467 usage_log();
4469 error = got_repo_pack_fds_open(&pack_fds);
4470 if (error != NULL)
4471 goto done;
4473 if (repo_path == NULL) {
4474 cwd = getcwd(NULL, 0);
4475 if (cwd == NULL)
4476 return got_error_from_errno("getcwd");
4477 error = got_worktree_open(&worktree, cwd, NULL);
4478 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4479 goto done;
4480 if (worktree)
4481 repo_path =
4482 strdup(got_worktree_get_repo_path(worktree));
4483 else
4484 repo_path = strdup(cwd);
4485 if (repo_path == NULL) {
4486 error = got_error_from_errno("strdup");
4487 goto done;
4491 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4492 if (error != NULL)
4493 goto done;
4495 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4496 repo, worktree);
4497 if (error)
4498 goto done;
4500 init_curses();
4502 error = apply_unveil(got_repo_get_path(repo),
4503 worktree ? got_worktree_get_root_path(worktree) : NULL);
4504 if (error)
4505 goto done;
4507 /* already loaded by tog_log_with_path()? */
4508 if (TAILQ_EMPTY(&tog_refs)) {
4509 error = tog_load_refs(repo, 0);
4510 if (error)
4511 goto done;
4514 if (start_commit == NULL) {
4515 error = got_repo_match_object_id(&start_id, &label,
4516 worktree ? got_worktree_get_head_ref_name(worktree) :
4517 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4518 if (error)
4519 goto done;
4520 head_ref_name = label;
4521 } else {
4522 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4523 repo, worktree);
4524 if (error != NULL)
4525 goto done;
4526 if (keyword_idstr != NULL)
4527 start_commit = keyword_idstr;
4529 error = got_ref_open(&ref, repo, start_commit, 0);
4530 if (error == NULL)
4531 head_ref_name = got_ref_get_name(ref);
4532 else if (error->code != GOT_ERR_NOT_REF)
4533 goto done;
4534 error = got_repo_match_object_id(&start_id, NULL,
4535 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4536 if (error)
4537 goto done;
4540 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4541 if (view == NULL) {
4542 error = got_error_from_errno("view_open");
4543 goto done;
4545 error = open_log_view(view, start_id, repo, head_ref_name,
4546 in_repo_path, log_branches);
4547 if (error)
4548 goto done;
4550 if (worktree) {
4551 error = set_tog_base_commit(repo, worktree);
4552 if (error != NULL)
4553 goto done;
4555 /* Release work tree lock. */
4556 got_worktree_close(worktree);
4557 worktree = NULL;
4560 error = view_loop(view);
4562 done:
4563 free(tog_base_commit.id);
4564 free(keyword_idstr);
4565 free(in_repo_path);
4566 free(repo_path);
4567 free(cwd);
4568 free(start_id);
4569 free(label);
4570 if (ref)
4571 got_ref_close(ref);
4572 if (repo) {
4573 const struct got_error *close_err = got_repo_close(repo);
4574 if (error == NULL)
4575 error = close_err;
4577 if (worktree)
4578 got_worktree_close(worktree);
4579 if (pack_fds) {
4580 const struct got_error *pack_err =
4581 got_repo_pack_fds_close(pack_fds);
4582 if (error == NULL)
4583 error = pack_err;
4585 tog_free_refs();
4586 return error;
4589 __dead static void
4590 usage_diff(void)
4592 endwin();
4593 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4594 "object1 object2\n", getprogname());
4595 exit(1);
4598 static int
4599 match_line(const char *line, regex_t *regex, size_t nmatch,
4600 regmatch_t *regmatch)
4602 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4605 static struct tog_color *
4606 match_color(struct tog_colors *colors, const char *line)
4608 struct tog_color *tc = NULL;
4610 STAILQ_FOREACH(tc, colors, entry) {
4611 if (match_line(line, &tc->regex, 0, NULL))
4612 return tc;
4615 return NULL;
4618 static const struct got_error *
4619 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4620 WINDOW *window, int skipcol, regmatch_t *regmatch)
4622 const struct got_error *err = NULL;
4623 char *exstr = NULL;
4624 wchar_t *wline = NULL;
4625 int rme, rms, n, width, scrollx;
4626 int width0 = 0, width1 = 0, width2 = 0;
4627 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4629 *wtotal = 0;
4631 rms = regmatch->rm_so;
4632 rme = regmatch->rm_eo;
4634 err = expand_tab(&exstr, line);
4635 if (err)
4636 return err;
4638 /* Split the line into 3 segments, according to match offsets. */
4639 seg0 = strndup(exstr, rms);
4640 if (seg0 == NULL) {
4641 err = got_error_from_errno("strndup");
4642 goto done;
4644 seg1 = strndup(exstr + rms, rme - rms);
4645 if (seg1 == NULL) {
4646 err = got_error_from_errno("strndup");
4647 goto done;
4649 seg2 = strdup(exstr + rme);
4650 if (seg2 == NULL) {
4651 err = got_error_from_errno("strndup");
4652 goto done;
4655 /* draw up to matched token if we haven't scrolled past it */
4656 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4657 col_tab_align, 1);
4658 if (err)
4659 goto done;
4660 n = MAX(width0 - skipcol, 0);
4661 if (n) {
4662 free(wline);
4663 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4664 wlimit, col_tab_align, 1);
4665 if (err)
4666 goto done;
4667 waddwstr(window, &wline[scrollx]);
4668 wlimit -= width;
4669 *wtotal += width;
4672 if (wlimit > 0) {
4673 int i = 0, w = 0;
4674 size_t wlen;
4676 free(wline);
4677 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4678 col_tab_align, 1);
4679 if (err)
4680 goto done;
4681 wlen = wcslen(wline);
4682 while (i < wlen) {
4683 width = wcwidth(wline[i]);
4684 if (width == -1) {
4685 /* should not happen, tabs are expanded */
4686 err = got_error(GOT_ERR_RANGE);
4687 goto done;
4689 if (width0 + w + width > skipcol)
4690 break;
4691 w += width;
4692 i++;
4694 /* draw (visible part of) matched token (if scrolled into it) */
4695 if (width1 - w > 0) {
4696 wattron(window, A_STANDOUT);
4697 waddwstr(window, &wline[i]);
4698 wattroff(window, A_STANDOUT);
4699 wlimit -= (width1 - w);
4700 *wtotal += (width1 - w);
4704 if (wlimit > 0) { /* draw rest of line */
4705 free(wline);
4706 if (skipcol > width0 + width1) {
4707 err = format_line(&wline, &width2, &scrollx, seg2,
4708 skipcol - (width0 + width1), wlimit,
4709 col_tab_align, 1);
4710 if (err)
4711 goto done;
4712 waddwstr(window, &wline[scrollx]);
4713 } else {
4714 err = format_line(&wline, &width2, NULL, seg2, 0,
4715 wlimit, col_tab_align, 1);
4716 if (err)
4717 goto done;
4718 waddwstr(window, wline);
4720 *wtotal += width2;
4722 done:
4723 free(wline);
4724 free(exstr);
4725 free(seg0);
4726 free(seg1);
4727 free(seg2);
4728 return err;
4731 static int
4732 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4734 FILE *f = NULL;
4735 int *eof, *first, *selected;
4737 if (view->type == TOG_VIEW_DIFF) {
4738 struct tog_diff_view_state *s = &view->state.diff;
4740 first = &s->first_displayed_line;
4741 selected = first;
4742 eof = &s->eof;
4743 f = s->f;
4744 } else if (view->type == TOG_VIEW_HELP) {
4745 struct tog_help_view_state *s = &view->state.help;
4747 first = &s->first_displayed_line;
4748 selected = first;
4749 eof = &s->eof;
4750 f = s->f;
4751 } else if (view->type == TOG_VIEW_BLAME) {
4752 struct tog_blame_view_state *s = &view->state.blame;
4754 first = &s->first_displayed_line;
4755 selected = &s->selected_line;
4756 eof = &s->eof;
4757 f = s->blame.f;
4758 } else
4759 return 0;
4761 /* Center gline in the middle of the page like vi(1). */
4762 if (*lineno < view->gline - (view->nlines - 3) / 2)
4763 return 0;
4764 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4765 rewind(f);
4766 *eof = 0;
4767 *first = 1;
4768 *lineno = 0;
4769 *nprinted = 0;
4770 return 0;
4773 *selected = view->gline <= (view->nlines - 3) / 2 ?
4774 view->gline : (view->nlines - 3) / 2 + 1;
4775 view->gline = 0;
4777 return 1;
4780 static const struct got_error *
4781 draw_file(struct tog_view *view, const char *header)
4783 struct tog_diff_view_state *s = &view->state.diff;
4784 regmatch_t *regmatch = &view->regmatch;
4785 const struct got_error *err;
4786 int nprinted = 0;
4787 char *line;
4788 size_t linesize = 0;
4789 ssize_t linelen;
4790 wchar_t *wline;
4791 int width;
4792 int max_lines = view->nlines;
4793 int nlines = s->nlines;
4794 off_t line_offset;
4796 s->lineno = s->first_displayed_line - 1;
4797 line_offset = s->lines[s->first_displayed_line - 1].offset;
4798 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4799 return got_error_from_errno("fseek");
4801 werase(view->window);
4803 if (view->gline > s->nlines - 1)
4804 view->gline = s->nlines - 1;
4806 if (header) {
4807 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4808 1 : view->gline - (view->nlines - 3) / 2 :
4809 s->lineno + s->selected_line;
4811 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4812 return got_error_from_errno("asprintf");
4813 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4814 0, 0);
4815 free(line);
4816 if (err)
4817 return err;
4819 if (view_needs_focus_indication(view))
4820 wstandout(view->window);
4821 waddwstr(view->window, wline);
4822 free(wline);
4823 wline = NULL;
4824 while (width++ < view->ncols)
4825 waddch(view->window, ' ');
4826 if (view_needs_focus_indication(view))
4827 wstandend(view->window);
4829 if (max_lines <= 1)
4830 return NULL;
4831 max_lines--;
4834 s->eof = 0;
4835 view->maxx = 0;
4836 line = NULL;
4837 while (max_lines > 0 && nprinted < max_lines) {
4838 enum got_diff_line_type linetype;
4839 attr_t attr = 0;
4841 linelen = getline(&line, &linesize, s->f);
4842 if (linelen == -1) {
4843 if (feof(s->f)) {
4844 s->eof = 1;
4845 break;
4847 free(line);
4848 return got_ferror(s->f, GOT_ERR_IO);
4851 if (++s->lineno < s->first_displayed_line)
4852 continue;
4853 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4854 continue;
4855 if (s->lineno == view->hiline)
4856 attr = A_STANDOUT;
4858 /* Set view->maxx based on full line length. */
4859 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4860 view->x ? 1 : 0);
4861 if (err) {
4862 free(line);
4863 return err;
4865 view->maxx = MAX(view->maxx, width);
4866 free(wline);
4867 wline = NULL;
4869 linetype = s->lines[s->lineno].type;
4870 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4871 linetype < GOT_DIFF_LINE_CONTEXT)
4872 attr |= COLOR_PAIR(linetype);
4873 if (attr)
4874 wattron(view->window, attr);
4875 if (s->first_displayed_line + nprinted == s->matched_line &&
4876 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4877 err = add_matched_line(&width, line, view->ncols, 0,
4878 view->window, view->x, regmatch);
4879 if (err) {
4880 free(line);
4881 return err;
4883 } else {
4884 int skip;
4885 err = format_line(&wline, &width, &skip, line,
4886 view->x, view->ncols, 0, view->x ? 1 : 0);
4887 if (err) {
4888 free(line);
4889 return err;
4891 waddwstr(view->window, &wline[skip]);
4892 free(wline);
4893 wline = NULL;
4895 if (s->lineno == view->hiline) {
4896 /* highlight full gline length */
4897 while (width++ < view->ncols)
4898 waddch(view->window, ' ');
4899 } else {
4900 if (width <= view->ncols - 1)
4901 waddch(view->window, '\n');
4903 if (attr)
4904 wattroff(view->window, attr);
4905 if (++nprinted == 1)
4906 s->first_displayed_line = s->lineno;
4908 free(line);
4909 if (nprinted >= 1)
4910 s->last_displayed_line = s->first_displayed_line +
4911 (nprinted - 1);
4912 else
4913 s->last_displayed_line = s->first_displayed_line;
4915 view_border(view);
4917 if (s->eof) {
4918 while (nprinted < view->nlines) {
4919 waddch(view->window, '\n');
4920 nprinted++;
4923 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4924 view->ncols, 0, 0);
4925 if (err) {
4926 return err;
4929 wstandout(view->window);
4930 waddwstr(view->window, wline);
4931 free(wline);
4932 wline = NULL;
4933 wstandend(view->window);
4936 return NULL;
4939 static char *
4940 get_datestr(time_t *time, char *datebuf)
4942 struct tm mytm, *tm;
4943 char *p, *s;
4945 tm = gmtime_r(time, &mytm);
4946 if (tm == NULL)
4947 return NULL;
4948 s = asctime_r(tm, datebuf);
4949 if (s == NULL)
4950 return NULL;
4951 p = strchr(s, '\n');
4952 if (p)
4953 *p = '\0';
4954 return s;
4957 static const struct got_error *
4958 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4959 off_t off, uint8_t type)
4961 struct got_diff_line *p;
4963 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4964 if (p == NULL)
4965 return got_error_from_errno("reallocarray");
4966 *lines = p;
4967 (*lines)[*nlines].offset = off;
4968 (*lines)[*nlines].type = type;
4969 (*nlines)++;
4971 return NULL;
4974 static const struct got_error *
4975 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4976 struct got_diff_line *s_lines, size_t s_nlines)
4978 struct got_diff_line *p;
4979 char buf[BUFSIZ];
4980 size_t i, r;
4982 if (fseeko(src, 0L, SEEK_SET) == -1)
4983 return got_error_from_errno("fseeko");
4985 for (;;) {
4986 r = fread(buf, 1, sizeof(buf), src);
4987 if (r == 0) {
4988 if (ferror(src))
4989 return got_error_from_errno("fread");
4990 if (feof(src))
4991 break;
4993 if (fwrite(buf, 1, r, dst) != r)
4994 return got_ferror(dst, GOT_ERR_IO);
4997 if (s_nlines == 0 && *d_nlines == 0)
4998 return NULL;
5001 * If commit info was in dst, increment line offsets
5002 * of the appended diff content, but skip s_lines[0]
5003 * because offset zero is already in *d_lines.
5005 if (*d_nlines > 0) {
5006 for (i = 1; i < s_nlines; ++i)
5007 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
5009 if (s_nlines > 0) {
5010 --s_nlines;
5011 ++s_lines;
5015 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
5016 if (p == NULL) {
5017 /* d_lines is freed in close_diff_view() */
5018 return got_error_from_errno("reallocarray");
5021 *d_lines = p;
5023 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
5024 *d_nlines += s_nlines;
5026 return NULL;
5029 static const struct got_error *
5030 write_commit_info(struct got_diff_line **lines, size_t *nlines,
5031 struct got_object_id *commit_id, struct got_reflist_head *refs,
5032 struct got_repository *repo, int ignore_ws, int force_text_diff,
5033 struct got_diffstat_cb_arg *dsa, FILE *outfile)
5035 const struct got_error *err = NULL;
5036 char datebuf[26], *datestr;
5037 struct got_commit_object *commit;
5038 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
5039 time_t committer_time;
5040 const char *author, *committer;
5041 char *refs_str = NULL;
5042 struct got_pathlist_entry *pe;
5043 off_t outoff = 0;
5044 int n;
5046 err = build_refs_str(&refs_str, refs, commit_id, repo);
5047 if (err)
5048 return err;
5050 err = got_object_open_as_commit(&commit, repo, commit_id);
5051 if (err)
5052 return err;
5054 err = got_object_id_str(&id_str, commit_id);
5055 if (err) {
5056 err = got_error_from_errno("got_object_id_str");
5057 goto done;
5060 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
5061 if (err)
5062 goto done;
5064 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
5065 refs_str ? refs_str : "", refs_str ? ")" : "");
5066 if (n < 0) {
5067 err = got_error_from_errno("fprintf");
5068 goto done;
5070 outoff += n;
5071 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
5072 if (err)
5073 goto done;
5075 n = fprintf(outfile, "from: %s\n",
5076 got_object_commit_get_author(commit));
5077 if (n < 0) {
5078 err = got_error_from_errno("fprintf");
5079 goto done;
5081 outoff += n;
5082 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
5083 if (err)
5084 goto done;
5086 author = got_object_commit_get_author(commit);
5087 committer = got_object_commit_get_committer(commit);
5088 if (strcmp(author, committer) != 0) {
5089 n = fprintf(outfile, "via: %s\n", committer);
5090 if (n < 0) {
5091 err = got_error_from_errno("fprintf");
5092 goto done;
5094 outoff += n;
5095 err = add_line_metadata(lines, nlines, outoff,
5096 GOT_DIFF_LINE_AUTHOR);
5097 if (err)
5098 goto done;
5100 committer_time = got_object_commit_get_committer_time(commit);
5101 datestr = get_datestr(&committer_time, datebuf);
5102 if (datestr) {
5103 n = fprintf(outfile, "date: %s UTC\n", datestr);
5104 if (n < 0) {
5105 err = got_error_from_errno("fprintf");
5106 goto done;
5108 outoff += n;
5109 err = add_line_metadata(lines, nlines, outoff,
5110 GOT_DIFF_LINE_DATE);
5111 if (err)
5112 goto done;
5114 if (got_object_commit_get_nparents(commit) > 1) {
5115 const struct got_object_id_queue *parent_ids;
5116 struct got_object_qid *qid;
5117 int pn = 1;
5118 parent_ids = got_object_commit_get_parent_ids(commit);
5119 STAILQ_FOREACH(qid, parent_ids, entry) {
5120 err = got_object_id_str(&id_str, &qid->id);
5121 if (err)
5122 goto done;
5123 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5124 if (n < 0) {
5125 err = got_error_from_errno("fprintf");
5126 goto done;
5128 outoff += n;
5129 err = add_line_metadata(lines, nlines, outoff,
5130 GOT_DIFF_LINE_META);
5131 if (err)
5132 goto done;
5133 free(id_str);
5134 id_str = NULL;
5138 err = got_object_commit_get_logmsg(&logmsg, commit);
5139 if (err)
5140 goto done;
5141 s = logmsg;
5142 while ((line = strsep(&s, "\n")) != NULL) {
5143 n = fprintf(outfile, "%s\n", line);
5144 if (n < 0) {
5145 err = got_error_from_errno("fprintf");
5146 goto done;
5148 outoff += n;
5149 err = add_line_metadata(lines, nlines, outoff,
5150 GOT_DIFF_LINE_LOGMSG);
5151 if (err)
5152 goto done;
5155 TAILQ_FOREACH(pe, dsa->paths, entry) {
5156 struct got_diff_changed_path *cp = pe->data;
5157 int pad = dsa->max_path_len - pe->path_len + 1;
5159 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5160 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5161 dsa->rm_cols + 1, cp->rm);
5162 if (n < 0) {
5163 err = got_error_from_errno("fprintf");
5164 goto done;
5166 outoff += n;
5167 err = add_line_metadata(lines, nlines, outoff,
5168 GOT_DIFF_LINE_CHANGES);
5169 if (err)
5170 goto done;
5173 fputc('\n', outfile);
5174 outoff++;
5175 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5176 if (err)
5177 goto done;
5179 n = fprintf(outfile,
5180 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5181 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5182 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5183 if (n < 0) {
5184 err = got_error_from_errno("fprintf");
5185 goto done;
5187 outoff += n;
5188 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5189 if (err)
5190 goto done;
5192 fputc('\n', outfile);
5193 outoff++;
5194 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5195 done:
5196 free(id_str);
5197 free(logmsg);
5198 free(refs_str);
5199 got_object_commit_close(commit);
5200 if (err) {
5201 free(*lines);
5202 *lines = NULL;
5203 *nlines = 0;
5205 return err;
5208 static const struct got_error *
5209 create_diff(struct tog_diff_view_state *s)
5211 const struct got_error *err = NULL;
5212 FILE *f = NULL, *tmp_diff_file = NULL;
5213 int obj_type;
5214 struct got_diff_line *lines = NULL;
5215 struct got_pathlist_head changed_paths;
5217 TAILQ_INIT(&changed_paths);
5219 free(s->lines);
5220 s->lines = malloc(sizeof(*s->lines));
5221 if (s->lines == NULL)
5222 return got_error_from_errno("malloc");
5223 s->nlines = 0;
5225 f = got_opentemp();
5226 if (f == NULL) {
5227 err = got_error_from_errno("got_opentemp");
5228 goto done;
5230 tmp_diff_file = got_opentemp();
5231 if (tmp_diff_file == NULL) {
5232 err = got_error_from_errno("got_opentemp");
5233 goto done;
5235 if (s->f && fclose(s->f) == EOF) {
5236 err = got_error_from_errno("fclose");
5237 goto done;
5239 s->f = f;
5241 if (s->id1)
5242 err = got_object_get_type(&obj_type, s->repo, s->id1);
5243 else
5244 err = got_object_get_type(&obj_type, s->repo, s->id2);
5245 if (err)
5246 goto done;
5248 switch (obj_type) {
5249 case GOT_OBJ_TYPE_BLOB:
5250 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5251 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5252 s->label1, s->label2, tog_diff_algo, s->diff_context,
5253 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5254 s->f);
5255 break;
5256 case GOT_OBJ_TYPE_TREE:
5257 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5258 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5259 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5260 s->force_text_diff, NULL, s->repo, s->f);
5261 break;
5262 case GOT_OBJ_TYPE_COMMIT: {
5263 const struct got_object_id_queue *parent_ids;
5264 struct got_object_qid *pid;
5265 struct got_commit_object *commit2;
5266 struct got_reflist_head *refs;
5267 size_t nlines = 0;
5268 struct got_diffstat_cb_arg dsa = {
5269 0, 0, 0, 0, 0, 0,
5270 &changed_paths,
5271 s->ignore_whitespace,
5272 s->force_text_diff,
5273 tog_diff_algo
5276 lines = malloc(sizeof(*lines));
5277 if (lines == NULL) {
5278 err = got_error_from_errno("malloc");
5279 goto done;
5282 /* build diff first in tmp file then append to commit info */
5283 err = got_diff_objects_as_commits(&lines, &nlines,
5284 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5285 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5286 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5287 if (err)
5288 break;
5290 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5291 if (err)
5292 goto done;
5293 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5294 /* Show commit info if we're diffing to a parent/root commit. */
5295 if (s->id1 == NULL) {
5296 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5297 refs, s->repo, s->ignore_whitespace,
5298 s->force_text_diff, &dsa, s->f);
5299 if (err)
5300 goto done;
5301 } else {
5302 parent_ids = got_object_commit_get_parent_ids(commit2);
5303 STAILQ_FOREACH(pid, parent_ids, entry) {
5304 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5305 err = write_commit_info(&s->lines,
5306 &s->nlines, s->id2, refs, s->repo,
5307 s->ignore_whitespace,
5308 s->force_text_diff, &dsa, s->f);
5309 if (err)
5310 goto done;
5311 break;
5315 got_object_commit_close(commit2);
5317 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5318 lines, nlines);
5319 break;
5321 default:
5322 err = got_error(GOT_ERR_OBJ_TYPE);
5323 break;
5325 done:
5326 free(lines);
5327 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5328 if (s->f && fflush(s->f) != 0 && err == NULL)
5329 err = got_error_from_errno("fflush");
5330 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5331 err = got_error_from_errno("fclose");
5332 return err;
5335 static void
5336 diff_view_indicate_progress(struct tog_view *view)
5338 mvwaddstr(view->window, 0, 0, "diffing...");
5339 update_panels();
5340 doupdate();
5343 static const struct got_error *
5344 search_start_diff_view(struct tog_view *view)
5346 struct tog_diff_view_state *s = &view->state.diff;
5348 s->matched_line = 0;
5349 return NULL;
5352 static void
5353 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5354 size_t *nlines, int **first, int **last, int **match, int **selected)
5356 struct tog_diff_view_state *s = &view->state.diff;
5358 *f = s->f;
5359 *nlines = s->nlines;
5360 *line_offsets = NULL;
5361 *match = &s->matched_line;
5362 *first = &s->first_displayed_line;
5363 *last = &s->last_displayed_line;
5364 *selected = &s->selected_line;
5367 static const struct got_error *
5368 search_next_view_match(struct tog_view *view)
5370 const struct got_error *err = NULL;
5371 FILE *f;
5372 int lineno;
5373 char *line = NULL;
5374 size_t linesize = 0;
5375 ssize_t linelen;
5376 off_t *line_offsets;
5377 size_t nlines = 0;
5378 int *first, *last, *match, *selected;
5380 if (!view->search_setup)
5381 return got_error_msg(GOT_ERR_NOT_IMPL,
5382 "view search not supported");
5383 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5384 &match, &selected);
5386 if (!view->searching) {
5387 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5388 return NULL;
5391 if (*match) {
5392 if (view->searching == TOG_SEARCH_FORWARD)
5393 lineno = *first + 1;
5394 else
5395 lineno = *first - 1;
5396 } else
5397 lineno = *first - 1 + *selected;
5399 while (1) {
5400 off_t offset;
5402 if (lineno <= 0 || lineno > nlines) {
5403 if (*match == 0) {
5404 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5405 break;
5408 if (view->searching == TOG_SEARCH_FORWARD)
5409 lineno = 1;
5410 else
5411 lineno = nlines;
5414 offset = view->type == TOG_VIEW_DIFF ?
5415 view->state.diff.lines[lineno - 1].offset :
5416 line_offsets[lineno - 1];
5417 if (fseeko(f, offset, SEEK_SET) != 0) {
5418 free(line);
5419 return got_error_from_errno("fseeko");
5421 linelen = getline(&line, &linesize, f);
5422 if (linelen != -1) {
5423 char *exstr;
5424 err = expand_tab(&exstr, line);
5425 if (err)
5426 break;
5427 if (match_line(exstr, &view->regex, 1,
5428 &view->regmatch)) {
5429 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5430 *match = lineno;
5431 free(exstr);
5432 break;
5434 free(exstr);
5436 if (view->searching == TOG_SEARCH_FORWARD)
5437 lineno++;
5438 else
5439 lineno--;
5441 free(line);
5443 if (*match) {
5444 *first = *match;
5445 *selected = 1;
5448 return err;
5451 static const struct got_error *
5452 close_diff_view(struct tog_view *view)
5454 const struct got_error *err = NULL;
5455 struct tog_diff_view_state *s = &view->state.diff;
5457 free(s->id1);
5458 s->id1 = NULL;
5459 free(s->id2);
5460 s->id2 = NULL;
5461 if (s->f && fclose(s->f) == EOF)
5462 err = got_error_from_errno("fclose");
5463 s->f = NULL;
5464 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5465 err = got_error_from_errno("fclose");
5466 s->f1 = NULL;
5467 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5468 err = got_error_from_errno("fclose");
5469 s->f2 = NULL;
5470 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5471 err = got_error_from_errno("close");
5472 s->fd1 = -1;
5473 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5474 err = got_error_from_errno("close");
5475 s->fd2 = -1;
5476 free(s->lines);
5477 s->lines = NULL;
5478 s->nlines = 0;
5479 return err;
5482 static const struct got_error *
5483 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5484 struct got_object_id *id2, const char *label1, const char *label2,
5485 int diff_context, int ignore_whitespace, int force_text_diff,
5486 struct tog_view *parent_view, struct got_repository *repo)
5488 const struct got_error *err;
5489 struct tog_diff_view_state *s = &view->state.diff;
5491 memset(s, 0, sizeof(*s));
5492 s->fd1 = -1;
5493 s->fd2 = -1;
5495 if (id1 != NULL && id2 != NULL) {
5496 int type1, type2;
5498 err = got_object_get_type(&type1, repo, id1);
5499 if (err)
5500 goto done;
5501 err = got_object_get_type(&type2, repo, id2);
5502 if (err)
5503 goto done;
5505 if (type1 != type2) {
5506 err = got_error(GOT_ERR_OBJ_TYPE);
5507 goto done;
5510 s->first_displayed_line = 1;
5511 s->last_displayed_line = view->nlines;
5512 s->selected_line = 1;
5513 s->repo = repo;
5514 s->id1 = id1;
5515 s->id2 = id2;
5516 s->label1 = label1;
5517 s->label2 = label2;
5519 if (id1) {
5520 s->id1 = got_object_id_dup(id1);
5521 if (s->id1 == NULL) {
5522 err = got_error_from_errno("got_object_id_dup");
5523 goto done;
5525 } else
5526 s->id1 = NULL;
5528 s->id2 = got_object_id_dup(id2);
5529 if (s->id2 == NULL) {
5530 err = got_error_from_errno("got_object_id_dup");
5531 goto done;
5534 s->f1 = got_opentemp();
5535 if (s->f1 == NULL) {
5536 err = got_error_from_errno("got_opentemp");
5537 goto done;
5540 s->f2 = got_opentemp();
5541 if (s->f2 == NULL) {
5542 err = got_error_from_errno("got_opentemp");
5543 goto done;
5546 s->fd1 = got_opentempfd();
5547 if (s->fd1 == -1) {
5548 err = got_error_from_errno("got_opentempfd");
5549 goto done;
5552 s->fd2 = got_opentempfd();
5553 if (s->fd2 == -1) {
5554 err = got_error_from_errno("got_opentempfd");
5555 goto done;
5558 s->diff_context = diff_context;
5559 s->ignore_whitespace = ignore_whitespace;
5560 s->force_text_diff = force_text_diff;
5561 s->parent_view = parent_view;
5562 s->repo = repo;
5564 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5565 int rc;
5567 rc = init_pair(GOT_DIFF_LINE_MINUS,
5568 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5569 if (rc != ERR)
5570 rc = init_pair(GOT_DIFF_LINE_PLUS,
5571 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5572 if (rc != ERR)
5573 rc = init_pair(GOT_DIFF_LINE_HUNK,
5574 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5575 if (rc != ERR)
5576 rc = init_pair(GOT_DIFF_LINE_META,
5577 get_color_value("TOG_COLOR_DIFF_META"), -1);
5578 if (rc != ERR)
5579 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5580 get_color_value("TOG_COLOR_DIFF_META"), -1);
5581 if (rc != ERR)
5582 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5583 get_color_value("TOG_COLOR_DIFF_META"), -1);
5584 if (rc != ERR)
5585 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5586 get_color_value("TOG_COLOR_DIFF_META"), -1);
5587 if (rc != ERR)
5588 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5589 get_color_value("TOG_COLOR_AUTHOR"), -1);
5590 if (rc != ERR)
5591 rc = init_pair(GOT_DIFF_LINE_DATE,
5592 get_color_value("TOG_COLOR_DATE"), -1);
5593 if (rc == ERR) {
5594 err = got_error(GOT_ERR_RANGE);
5595 goto done;
5599 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5600 view_is_splitscreen(view))
5601 show_log_view(parent_view); /* draw border */
5602 diff_view_indicate_progress(view);
5604 err = create_diff(s);
5606 view->show = show_diff_view;
5607 view->input = input_diff_view;
5608 view->reset = reset_diff_view;
5609 view->close = close_diff_view;
5610 view->search_start = search_start_diff_view;
5611 view->search_setup = search_setup_diff_view;
5612 view->search_next = search_next_view_match;
5613 done:
5614 if (err) {
5615 if (view->close == NULL)
5616 close_diff_view(view);
5617 view_close(view);
5619 return err;
5622 static const struct got_error *
5623 show_diff_view(struct tog_view *view)
5625 const struct got_error *err;
5626 struct tog_diff_view_state *s = &view->state.diff;
5627 char *id_str1 = NULL, *id_str2, *header;
5628 const char *label1, *label2;
5630 if (s->id1) {
5631 err = got_object_id_str(&id_str1, s->id1);
5632 if (err)
5633 return err;
5634 label1 = s->label1 ? s->label1 : id_str1;
5635 } else
5636 label1 = "/dev/null";
5638 err = got_object_id_str(&id_str2, s->id2);
5639 if (err)
5640 return err;
5641 label2 = s->label2 ? s->label2 : id_str2;
5643 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5644 err = got_error_from_errno("asprintf");
5645 free(id_str1);
5646 free(id_str2);
5647 return err;
5649 free(id_str1);
5650 free(id_str2);
5652 err = draw_file(view, header);
5653 free(header);
5654 return err;
5657 static const struct got_error *
5658 set_selected_commit(struct tog_diff_view_state *s,
5659 struct commit_queue_entry *entry)
5661 const struct got_error *err;
5662 const struct got_object_id_queue *parent_ids;
5663 struct got_commit_object *selected_commit;
5664 struct got_object_qid *pid;
5666 free(s->id2);
5667 s->id2 = got_object_id_dup(entry->id);
5668 if (s->id2 == NULL)
5669 return got_error_from_errno("got_object_id_dup");
5671 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5672 if (err)
5673 return err;
5674 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5675 free(s->id1);
5676 pid = STAILQ_FIRST(parent_ids);
5677 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5678 got_object_commit_close(selected_commit);
5679 return NULL;
5682 static const struct got_error *
5683 reset_diff_view(struct tog_view *view)
5685 struct tog_diff_view_state *s = &view->state.diff;
5687 view->count = 0;
5688 wclear(view->window);
5689 s->first_displayed_line = 1;
5690 s->last_displayed_line = view->nlines;
5691 s->matched_line = 0;
5692 diff_view_indicate_progress(view);
5693 return create_diff(s);
5696 static void
5697 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5699 int start, i;
5701 i = start = s->first_displayed_line - 1;
5703 while (s->lines[i].type != type) {
5704 if (i == 0)
5705 i = s->nlines - 1;
5706 if (--i == start)
5707 return; /* do nothing, requested type not in file */
5710 s->selected_line = 1;
5711 s->first_displayed_line = i;
5714 static void
5715 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5717 int start, i;
5719 i = start = s->first_displayed_line + 1;
5721 while (s->lines[i].type != type) {
5722 if (i == s->nlines - 1)
5723 i = 0;
5724 if (++i == start)
5725 return; /* do nothing, requested type not in file */
5728 s->selected_line = 1;
5729 s->first_displayed_line = i;
5732 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5733 int, int, int);
5734 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5735 int, int);
5737 static const struct got_error *
5738 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5740 const struct got_error *err = NULL;
5741 struct tog_diff_view_state *s = &view->state.diff;
5742 struct tog_log_view_state *ls;
5743 struct commit_queue_entry *old_selected_entry;
5744 char *line = NULL;
5745 size_t linesize = 0;
5746 ssize_t linelen;
5747 int i, nscroll = view->nlines - 1, up = 0;
5749 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5751 switch (ch) {
5752 case '0':
5753 case '$':
5754 case KEY_RIGHT:
5755 case 'l':
5756 case KEY_LEFT:
5757 case 'h':
5758 horizontal_scroll_input(view, ch);
5759 break;
5760 case 'a':
5761 case 'w':
5762 if (ch == 'a') {
5763 s->force_text_diff = !s->force_text_diff;
5764 view->action = s->force_text_diff ?
5765 "force ASCII text enabled" :
5766 "force ASCII text disabled";
5768 else if (ch == 'w') {
5769 s->ignore_whitespace = !s->ignore_whitespace;
5770 view->action = s->ignore_whitespace ?
5771 "ignore whitespace enabled" :
5772 "ignore whitespace disabled";
5774 err = reset_diff_view(view);
5775 break;
5776 case 'g':
5777 case KEY_HOME:
5778 s->first_displayed_line = 1;
5779 view->count = 0;
5780 break;
5781 case 'G':
5782 case KEY_END:
5783 view->count = 0;
5784 if (s->eof)
5785 break;
5787 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5788 s->eof = 1;
5789 break;
5790 case 'k':
5791 case KEY_UP:
5792 case CTRL('p'):
5793 if (s->first_displayed_line > 1)
5794 s->first_displayed_line--;
5795 else
5796 view->count = 0;
5797 break;
5798 case CTRL('u'):
5799 case 'u':
5800 nscroll /= 2;
5801 /* FALL THROUGH */
5802 case KEY_PPAGE:
5803 case CTRL('b'):
5804 case 'b':
5805 if (s->first_displayed_line == 1) {
5806 view->count = 0;
5807 break;
5809 i = 0;
5810 while (i++ < nscroll && s->first_displayed_line > 1)
5811 s->first_displayed_line--;
5812 break;
5813 case 'j':
5814 case KEY_DOWN:
5815 case CTRL('n'):
5816 if (!s->eof)
5817 s->first_displayed_line++;
5818 else
5819 view->count = 0;
5820 break;
5821 case CTRL('d'):
5822 case 'd':
5823 nscroll /= 2;
5824 /* FALL THROUGH */
5825 case KEY_NPAGE:
5826 case CTRL('f'):
5827 case 'f':
5828 case ' ':
5829 if (s->eof) {
5830 view->count = 0;
5831 break;
5833 i = 0;
5834 while (!s->eof && i++ < nscroll) {
5835 linelen = getline(&line, &linesize, s->f);
5836 s->first_displayed_line++;
5837 if (linelen == -1) {
5838 if (feof(s->f)) {
5839 s->eof = 1;
5840 } else
5841 err = got_ferror(s->f, GOT_ERR_IO);
5842 break;
5845 free(line);
5846 break;
5847 case '(':
5848 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5849 break;
5850 case ')':
5851 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5852 break;
5853 case '{':
5854 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5855 break;
5856 case '}':
5857 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5858 break;
5859 case '[':
5860 if (s->diff_context > 0) {
5861 s->diff_context--;
5862 s->matched_line = 0;
5863 diff_view_indicate_progress(view);
5864 err = create_diff(s);
5865 if (s->first_displayed_line + view->nlines - 1 >
5866 s->nlines) {
5867 s->first_displayed_line = 1;
5868 s->last_displayed_line = view->nlines;
5870 } else
5871 view->count = 0;
5872 break;
5873 case ']':
5874 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5875 s->diff_context++;
5876 s->matched_line = 0;
5877 diff_view_indicate_progress(view);
5878 err = create_diff(s);
5879 } else
5880 view->count = 0;
5881 break;
5882 case '<':
5883 case ',':
5884 case 'K':
5885 up = 1;
5886 /* FALL THROUGH */
5887 case '>':
5888 case '.':
5889 case 'J':
5890 if (s->parent_view == NULL) {
5891 view->count = 0;
5892 break;
5894 s->parent_view->count = view->count;
5896 if (s->parent_view->type == TOG_VIEW_LOG) {
5897 ls = &s->parent_view->state.log;
5898 old_selected_entry = ls->selected_entry;
5900 err = input_log_view(NULL, s->parent_view,
5901 up ? KEY_UP : KEY_DOWN);
5902 if (err)
5903 break;
5904 view->count = s->parent_view->count;
5906 if (old_selected_entry == ls->selected_entry)
5907 break;
5909 err = set_selected_commit(s, ls->selected_entry);
5910 if (err)
5911 break;
5912 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5913 struct tog_blame_view_state *bs;
5914 struct got_object_id *id, *prev_id;
5916 bs = &s->parent_view->state.blame;
5917 prev_id = get_annotation_for_line(bs->blame.lines,
5918 bs->blame.nlines, bs->last_diffed_line);
5920 err = input_blame_view(&view, s->parent_view,
5921 up ? KEY_UP : KEY_DOWN);
5922 if (err)
5923 break;
5924 view->count = s->parent_view->count;
5926 if (prev_id == NULL)
5927 break;
5928 id = get_selected_commit_id(bs->blame.lines,
5929 bs->blame.nlines, bs->first_displayed_line,
5930 bs->selected_line);
5931 if (id == NULL)
5932 break;
5934 if (!got_object_id_cmp(prev_id, id))
5935 break;
5937 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5938 if (err)
5939 break;
5941 s->first_displayed_line = 1;
5942 s->last_displayed_line = view->nlines;
5943 s->matched_line = 0;
5944 view->x = 0;
5946 diff_view_indicate_progress(view);
5947 err = create_diff(s);
5948 break;
5949 default:
5950 view->count = 0;
5951 break;
5954 return err;
5957 static const struct got_error *
5958 cmd_diff(int argc, char *argv[])
5960 const struct got_error *error;
5961 struct got_repository *repo = NULL;
5962 struct got_worktree *worktree = NULL;
5963 struct got_object_id *id1 = NULL, *id2 = NULL;
5964 char *repo_path = NULL, *cwd = NULL;
5965 char *id_str1 = NULL, *id_str2 = NULL;
5966 char *keyword_idstr1 = NULL, *keyword_idstr2 = NULL;
5967 char *label1 = NULL, *label2 = NULL;
5968 int diff_context = 3, ignore_whitespace = 0;
5969 int ch, force_text_diff = 0;
5970 const char *errstr;
5971 struct tog_view *view;
5972 int *pack_fds = NULL;
5974 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5975 switch (ch) {
5976 case 'a':
5977 force_text_diff = 1;
5978 break;
5979 case 'C':
5980 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5981 &errstr);
5982 if (errstr != NULL)
5983 errx(1, "number of context lines is %s: %s",
5984 errstr, errstr);
5985 break;
5986 case 'r':
5987 repo_path = realpath(optarg, NULL);
5988 if (repo_path == NULL)
5989 return got_error_from_errno2("realpath",
5990 optarg);
5991 got_path_strip_trailing_slashes(repo_path);
5992 break;
5993 case 'w':
5994 ignore_whitespace = 1;
5995 break;
5996 default:
5997 usage_diff();
5998 /* NOTREACHED */
6002 argc -= optind;
6003 argv += optind;
6005 if (argc == 0) {
6006 usage_diff(); /* TODO show local worktree changes */
6007 } else if (argc == 2) {
6008 id_str1 = argv[0];
6009 id_str2 = argv[1];
6010 } else
6011 usage_diff();
6013 error = got_repo_pack_fds_open(&pack_fds);
6014 if (error)
6015 goto done;
6017 if (repo_path == NULL) {
6018 cwd = getcwd(NULL, 0);
6019 if (cwd == NULL)
6020 return got_error_from_errno("getcwd");
6021 error = got_worktree_open(&worktree, cwd, NULL);
6022 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6023 goto done;
6024 if (worktree)
6025 repo_path =
6026 strdup(got_worktree_get_repo_path(worktree));
6027 else
6028 repo_path = strdup(cwd);
6029 if (repo_path == NULL) {
6030 error = got_error_from_errno("strdup");
6031 goto done;
6035 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6036 if (error)
6037 goto done;
6039 init_curses();
6041 error = apply_unveil(got_repo_get_path(repo), NULL);
6042 if (error)
6043 goto done;
6045 error = tog_load_refs(repo, 0);
6046 if (error)
6047 goto done;
6049 if (id_str1 != NULL) {
6050 error = got_keyword_to_idstr(&keyword_idstr1, id_str1,
6051 repo, worktree);
6052 if (error != NULL)
6053 goto done;
6054 if (keyword_idstr1 != NULL)
6055 id_str1 = keyword_idstr1;
6057 if (id_str2 != NULL) {
6058 error = got_keyword_to_idstr(&keyword_idstr2, id_str2,
6059 repo, worktree);
6060 if (error != NULL)
6061 goto done;
6062 if (keyword_idstr2 != NULL)
6063 id_str2 = keyword_idstr2;
6066 error = got_repo_match_object_id(&id1, &label1, id_str1,
6067 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6068 if (error)
6069 goto done;
6071 error = got_repo_match_object_id(&id2, &label2, id_str2,
6072 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6073 if (error)
6074 goto done;
6076 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
6077 if (view == NULL) {
6078 error = got_error_from_errno("view_open");
6079 goto done;
6081 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
6082 ignore_whitespace, force_text_diff, NULL, repo);
6083 if (error)
6084 goto done;
6086 if (worktree) {
6087 error = set_tog_base_commit(repo, worktree);
6088 if (error != NULL)
6089 goto done;
6092 error = view_loop(view);
6094 done:
6095 free(tog_base_commit.id);
6096 free(keyword_idstr1);
6097 free(keyword_idstr2);
6098 free(label1);
6099 free(label2);
6100 free(repo_path);
6101 free(cwd);
6102 if (repo) {
6103 const struct got_error *close_err = got_repo_close(repo);
6104 if (error == NULL)
6105 error = close_err;
6107 if (worktree)
6108 got_worktree_close(worktree);
6109 if (pack_fds) {
6110 const struct got_error *pack_err =
6111 got_repo_pack_fds_close(pack_fds);
6112 if (error == NULL)
6113 error = pack_err;
6115 tog_free_refs();
6116 return error;
6119 __dead static void
6120 usage_blame(void)
6122 endwin();
6123 fprintf(stderr,
6124 "usage: %s blame [-c commit] [-r repository-path] path\n",
6125 getprogname());
6126 exit(1);
6129 struct tog_blame_line {
6130 int annotated;
6131 struct got_object_id *id;
6134 static const struct got_error *
6135 draw_blame(struct tog_view *view)
6137 struct tog_blame_view_state *s = &view->state.blame;
6138 struct tog_blame *blame = &s->blame;
6139 regmatch_t *regmatch = &view->regmatch;
6140 const struct got_error *err;
6141 int lineno = 0, nprinted = 0;
6142 char *line = NULL;
6143 size_t linesize = 0;
6144 ssize_t linelen;
6145 wchar_t *wline;
6146 int width;
6147 struct tog_blame_line *blame_line;
6148 struct got_object_id *prev_id = NULL;
6149 char *id_str;
6150 struct tog_color *tc;
6152 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6153 if (err)
6154 return err;
6156 rewind(blame->f);
6157 werase(view->window);
6159 if (asprintf(&line, "commit %s", id_str) == -1) {
6160 err = got_error_from_errno("asprintf");
6161 free(id_str);
6162 return err;
6165 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6166 free(line);
6167 line = NULL;
6168 if (err)
6169 return err;
6170 if (view_needs_focus_indication(view))
6171 wstandout(view->window);
6172 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6173 if (tc)
6174 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6175 waddwstr(view->window, wline);
6176 while (width++ < view->ncols)
6177 waddch(view->window, ' ');
6178 if (tc)
6179 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6180 if (view_needs_focus_indication(view))
6181 wstandend(view->window);
6182 free(wline);
6183 wline = NULL;
6185 if (view->gline > blame->nlines)
6186 view->gline = blame->nlines;
6188 if (tog_io.wait_for_ui) {
6189 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6190 int rc;
6192 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6193 if (rc)
6194 return got_error_set_errno(rc, "pthread_cond_wait");
6195 tog_io.wait_for_ui = 0;
6198 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6199 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6200 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6201 free(id_str);
6202 return got_error_from_errno("asprintf");
6204 free(id_str);
6205 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6206 free(line);
6207 line = NULL;
6208 if (err)
6209 return err;
6210 waddwstr(view->window, wline);
6211 free(wline);
6212 wline = NULL;
6213 if (width < view->ncols - 1)
6214 waddch(view->window, '\n');
6216 s->eof = 0;
6217 view->maxx = 0;
6218 while (nprinted < view->nlines - 2) {
6219 linelen = getline(&line, &linesize, blame->f);
6220 if (linelen == -1) {
6221 if (feof(blame->f)) {
6222 s->eof = 1;
6223 break;
6225 free(line);
6226 return got_ferror(blame->f, GOT_ERR_IO);
6228 if (++lineno < s->first_displayed_line)
6229 continue;
6230 if (view->gline && !gotoline(view, &lineno, &nprinted))
6231 continue;
6233 /* Set view->maxx based on full line length. */
6234 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6235 if (err) {
6236 free(line);
6237 return err;
6239 free(wline);
6240 wline = NULL;
6241 view->maxx = MAX(view->maxx, width);
6243 if (nprinted == s->selected_line - 1)
6244 wstandout(view->window);
6246 if (blame->nlines > 0) {
6247 blame_line = &blame->lines[lineno - 1];
6248 if (blame_line->annotated && prev_id &&
6249 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6250 !(nprinted == s->selected_line - 1)) {
6251 waddstr(view->window, " ");
6252 } else if (blame_line->annotated) {
6253 char *id_str;
6254 err = got_object_id_str(&id_str,
6255 blame_line->id);
6256 if (err) {
6257 free(line);
6258 return err;
6260 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6261 if (tc)
6262 wattr_on(view->window,
6263 COLOR_PAIR(tc->colorpair), NULL);
6264 wprintw(view->window, "%.8s", id_str);
6265 if (tc)
6266 wattr_off(view->window,
6267 COLOR_PAIR(tc->colorpair), NULL);
6268 free(id_str);
6269 prev_id = blame_line->id;
6270 } else {
6271 waddstr(view->window, "........");
6272 prev_id = NULL;
6274 } else {
6275 waddstr(view->window, "........");
6276 prev_id = NULL;
6279 if (nprinted == s->selected_line - 1)
6280 wstandend(view->window);
6281 waddstr(view->window, " ");
6283 if (view->ncols <= 9) {
6284 width = 9;
6285 } else if (s->first_displayed_line + nprinted ==
6286 s->matched_line &&
6287 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6288 err = add_matched_line(&width, line, view->ncols - 9, 9,
6289 view->window, view->x, regmatch);
6290 if (err) {
6291 free(line);
6292 return err;
6294 width += 9;
6295 } else {
6296 int skip;
6297 err = format_line(&wline, &width, &skip, line,
6298 view->x, view->ncols - 9, 9, 1);
6299 if (err) {
6300 free(line);
6301 return err;
6303 waddwstr(view->window, &wline[skip]);
6304 width += 9;
6305 free(wline);
6306 wline = NULL;
6309 if (width <= view->ncols - 1)
6310 waddch(view->window, '\n');
6311 if (++nprinted == 1)
6312 s->first_displayed_line = lineno;
6314 free(line);
6315 s->last_displayed_line = lineno;
6317 view_border(view);
6319 return NULL;
6322 static const struct got_error *
6323 blame_cb(void *arg, int nlines, int lineno,
6324 struct got_commit_object *commit, struct got_object_id *id)
6326 const struct got_error *err = NULL;
6327 struct tog_blame_cb_args *a = arg;
6328 struct tog_blame_line *line;
6329 int errcode;
6331 if (nlines != a->nlines ||
6332 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6333 return got_error(GOT_ERR_RANGE);
6335 errcode = pthread_mutex_lock(&tog_mutex);
6336 if (errcode)
6337 return got_error_set_errno(errcode, "pthread_mutex_lock");
6339 if (*a->quit) { /* user has quit the blame view */
6340 err = got_error(GOT_ERR_ITER_COMPLETED);
6341 goto done;
6344 if (lineno == -1)
6345 goto done; /* no change in this commit */
6347 line = &a->lines[lineno - 1];
6348 if (line->annotated)
6349 goto done;
6351 line->id = got_object_id_dup(id);
6352 if (line->id == NULL) {
6353 err = got_error_from_errno("got_object_id_dup");
6354 goto done;
6356 line->annotated = 1;
6357 done:
6358 errcode = pthread_mutex_unlock(&tog_mutex);
6359 if (errcode)
6360 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6361 return err;
6364 static void *
6365 blame_thread(void *arg)
6367 const struct got_error *err, *close_err;
6368 struct tog_blame_thread_args *ta = arg;
6369 struct tog_blame_cb_args *a = ta->cb_args;
6370 int errcode, fd1 = -1, fd2 = -1;
6371 FILE *f1 = NULL, *f2 = NULL;
6373 fd1 = got_opentempfd();
6374 if (fd1 == -1)
6375 return (void *)got_error_from_errno("got_opentempfd");
6377 fd2 = got_opentempfd();
6378 if (fd2 == -1) {
6379 err = got_error_from_errno("got_opentempfd");
6380 goto done;
6383 f1 = got_opentemp();
6384 if (f1 == NULL) {
6385 err = (void *)got_error_from_errno("got_opentemp");
6386 goto done;
6388 f2 = got_opentemp();
6389 if (f2 == NULL) {
6390 err = (void *)got_error_from_errno("got_opentemp");
6391 goto done;
6394 err = block_signals_used_by_main_thread();
6395 if (err)
6396 goto done;
6398 err = got_blame(ta->path, a->commit_id, ta->repo,
6399 tog_diff_algo, blame_cb, ta->cb_args,
6400 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6401 if (err && err->code == GOT_ERR_CANCELLED)
6402 err = NULL;
6404 errcode = pthread_mutex_lock(&tog_mutex);
6405 if (errcode) {
6406 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6407 goto done;
6410 close_err = got_repo_close(ta->repo);
6411 if (err == NULL)
6412 err = close_err;
6413 ta->repo = NULL;
6414 *ta->complete = 1;
6416 if (tog_io.wait_for_ui) {
6417 errcode = pthread_cond_signal(&ta->blame_complete);
6418 if (errcode && err == NULL)
6419 err = got_error_set_errno(errcode,
6420 "pthread_cond_signal");
6423 errcode = pthread_mutex_unlock(&tog_mutex);
6424 if (errcode && err == NULL)
6425 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6427 done:
6428 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6429 err = got_error_from_errno("close");
6430 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6431 err = got_error_from_errno("close");
6432 if (f1 && fclose(f1) == EOF && err == NULL)
6433 err = got_error_from_errno("fclose");
6434 if (f2 && fclose(f2) == EOF && err == NULL)
6435 err = got_error_from_errno("fclose");
6437 return (void *)err;
6440 static struct got_object_id *
6441 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6442 int first_displayed_line, int selected_line)
6444 struct tog_blame_line *line;
6446 if (nlines <= 0)
6447 return NULL;
6449 line = &lines[first_displayed_line - 1 + selected_line - 1];
6450 if (!line->annotated)
6451 return NULL;
6453 return line->id;
6456 static struct got_object_id *
6457 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6458 int lineno)
6460 struct tog_blame_line *line;
6462 if (nlines <= 0 || lineno >= nlines)
6463 return NULL;
6465 line = &lines[lineno - 1];
6466 if (!line->annotated)
6467 return NULL;
6469 return line->id;
6472 static const struct got_error *
6473 stop_blame(struct tog_blame *blame)
6475 const struct got_error *err = NULL;
6476 int i;
6478 if (blame->thread) {
6479 int errcode;
6480 errcode = pthread_mutex_unlock(&tog_mutex);
6481 if (errcode)
6482 return got_error_set_errno(errcode,
6483 "pthread_mutex_unlock");
6484 errcode = pthread_join(blame->thread, (void **)&err);
6485 if (errcode)
6486 return got_error_set_errno(errcode, "pthread_join");
6487 errcode = pthread_mutex_lock(&tog_mutex);
6488 if (errcode)
6489 return got_error_set_errno(errcode,
6490 "pthread_mutex_lock");
6491 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6492 err = NULL;
6493 blame->thread = NULL;
6495 if (blame->thread_args.repo) {
6496 const struct got_error *close_err;
6497 close_err = got_repo_close(blame->thread_args.repo);
6498 if (err == NULL)
6499 err = close_err;
6500 blame->thread_args.repo = NULL;
6502 if (blame->f) {
6503 if (fclose(blame->f) == EOF && err == NULL)
6504 err = got_error_from_errno("fclose");
6505 blame->f = NULL;
6507 if (blame->lines) {
6508 for (i = 0; i < blame->nlines; i++)
6509 free(blame->lines[i].id);
6510 free(blame->lines);
6511 blame->lines = NULL;
6513 free(blame->cb_args.commit_id);
6514 blame->cb_args.commit_id = NULL;
6515 if (blame->pack_fds) {
6516 const struct got_error *pack_err =
6517 got_repo_pack_fds_close(blame->pack_fds);
6518 if (err == NULL)
6519 err = pack_err;
6520 blame->pack_fds = NULL;
6522 return err;
6525 static const struct got_error *
6526 cancel_blame_view(void *arg)
6528 const struct got_error *err = NULL;
6529 int *done = arg;
6530 int errcode;
6532 errcode = pthread_mutex_lock(&tog_mutex);
6533 if (errcode)
6534 return got_error_set_errno(errcode,
6535 "pthread_mutex_unlock");
6537 if (*done)
6538 err = got_error(GOT_ERR_CANCELLED);
6540 errcode = pthread_mutex_unlock(&tog_mutex);
6541 if (errcode)
6542 return got_error_set_errno(errcode,
6543 "pthread_mutex_lock");
6545 return err;
6548 static const struct got_error *
6549 run_blame(struct tog_view *view)
6551 struct tog_blame_view_state *s = &view->state.blame;
6552 struct tog_blame *blame = &s->blame;
6553 const struct got_error *err = NULL;
6554 struct got_commit_object *commit = NULL;
6555 struct got_blob_object *blob = NULL;
6556 struct got_repository *thread_repo = NULL;
6557 struct got_object_id *obj_id = NULL;
6558 int obj_type, fd = -1;
6559 int *pack_fds = NULL;
6561 err = got_object_open_as_commit(&commit, s->repo,
6562 &s->blamed_commit->id);
6563 if (err)
6564 return err;
6566 fd = got_opentempfd();
6567 if (fd == -1) {
6568 err = got_error_from_errno("got_opentempfd");
6569 goto done;
6572 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6573 if (err)
6574 goto done;
6576 err = got_object_get_type(&obj_type, s->repo, obj_id);
6577 if (err)
6578 goto done;
6580 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6581 err = got_error(GOT_ERR_OBJ_TYPE);
6582 goto done;
6585 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6586 if (err)
6587 goto done;
6588 blame->f = got_opentemp();
6589 if (blame->f == NULL) {
6590 err = got_error_from_errno("got_opentemp");
6591 goto done;
6593 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6594 &blame->line_offsets, blame->f, blob);
6595 if (err)
6596 goto done;
6597 if (blame->nlines == 0) {
6598 s->blame_complete = 1;
6599 goto done;
6602 /* Don't include \n at EOF in the blame line count. */
6603 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6604 blame->nlines--;
6606 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6607 if (blame->lines == NULL) {
6608 err = got_error_from_errno("calloc");
6609 goto done;
6612 err = got_repo_pack_fds_open(&pack_fds);
6613 if (err)
6614 goto done;
6615 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6616 pack_fds);
6617 if (err)
6618 goto done;
6620 blame->pack_fds = pack_fds;
6621 blame->cb_args.view = view;
6622 blame->cb_args.lines = blame->lines;
6623 blame->cb_args.nlines = blame->nlines;
6624 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6625 if (blame->cb_args.commit_id == NULL) {
6626 err = got_error_from_errno("got_object_id_dup");
6627 goto done;
6629 blame->cb_args.quit = &s->done;
6631 blame->thread_args.path = s->path;
6632 blame->thread_args.repo = thread_repo;
6633 blame->thread_args.cb_args = &blame->cb_args;
6634 blame->thread_args.complete = &s->blame_complete;
6635 blame->thread_args.cancel_cb = cancel_blame_view;
6636 blame->thread_args.cancel_arg = &s->done;
6637 s->blame_complete = 0;
6639 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6640 s->first_displayed_line = 1;
6641 s->last_displayed_line = view->nlines;
6642 s->selected_line = 1;
6644 s->matched_line = 0;
6646 done:
6647 if (commit)
6648 got_object_commit_close(commit);
6649 if (fd != -1 && close(fd) == -1 && err == NULL)
6650 err = got_error_from_errno("close");
6651 if (blob)
6652 got_object_blob_close(blob);
6653 free(obj_id);
6654 if (err)
6655 stop_blame(blame);
6656 return err;
6659 static const struct got_error *
6660 open_blame_view(struct tog_view *view, char *path,
6661 struct got_object_id *commit_id, struct got_repository *repo)
6663 const struct got_error *err = NULL;
6664 struct tog_blame_view_state *s = &view->state.blame;
6666 STAILQ_INIT(&s->blamed_commits);
6668 s->path = strdup(path);
6669 if (s->path == NULL)
6670 return got_error_from_errno("strdup");
6672 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6673 if (err) {
6674 free(s->path);
6675 return err;
6678 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6679 s->first_displayed_line = 1;
6680 s->last_displayed_line = view->nlines;
6681 s->selected_line = 1;
6682 s->blame_complete = 0;
6683 s->repo = repo;
6684 s->commit_id = commit_id;
6685 memset(&s->blame, 0, sizeof(s->blame));
6687 STAILQ_INIT(&s->colors);
6688 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6689 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6690 get_color_value("TOG_COLOR_COMMIT"));
6691 if (err)
6692 return err;
6695 view->show = show_blame_view;
6696 view->input = input_blame_view;
6697 view->reset = reset_blame_view;
6698 view->close = close_blame_view;
6699 view->search_start = search_start_blame_view;
6700 view->search_setup = search_setup_blame_view;
6701 view->search_next = search_next_view_match;
6703 if (using_mock_io) {
6704 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6705 int rc;
6707 rc = pthread_cond_init(&bta->blame_complete, NULL);
6708 if (rc)
6709 return got_error_set_errno(rc, "pthread_cond_init");
6712 return run_blame(view);
6715 static const struct got_error *
6716 close_blame_view(struct tog_view *view)
6718 const struct got_error *err = NULL;
6719 struct tog_blame_view_state *s = &view->state.blame;
6721 if (s->blame.thread)
6722 err = stop_blame(&s->blame);
6724 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6725 struct got_object_qid *blamed_commit;
6726 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6727 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6728 got_object_qid_free(blamed_commit);
6731 if (using_mock_io) {
6732 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6733 int rc;
6735 rc = pthread_cond_destroy(&bta->blame_complete);
6736 if (rc && err == NULL)
6737 err = got_error_set_errno(rc, "pthread_cond_destroy");
6740 free(s->path);
6741 free_colors(&s->colors);
6742 return err;
6745 static const struct got_error *
6746 search_start_blame_view(struct tog_view *view)
6748 struct tog_blame_view_state *s = &view->state.blame;
6750 s->matched_line = 0;
6751 return NULL;
6754 static void
6755 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6756 size_t *nlines, int **first, int **last, int **match, int **selected)
6758 struct tog_blame_view_state *s = &view->state.blame;
6760 *f = s->blame.f;
6761 *nlines = s->blame.nlines;
6762 *line_offsets = s->blame.line_offsets;
6763 *match = &s->matched_line;
6764 *first = &s->first_displayed_line;
6765 *last = &s->last_displayed_line;
6766 *selected = &s->selected_line;
6769 static const struct got_error *
6770 show_blame_view(struct tog_view *view)
6772 const struct got_error *err = NULL;
6773 struct tog_blame_view_state *s = &view->state.blame;
6774 int errcode;
6776 if (s->blame.thread == NULL && !s->blame_complete) {
6777 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6778 &s->blame.thread_args);
6779 if (errcode)
6780 return got_error_set_errno(errcode, "pthread_create");
6782 if (!using_mock_io)
6783 halfdelay(1); /* fast refresh while annotating */
6786 if (s->blame_complete && !using_mock_io)
6787 halfdelay(10); /* disable fast refresh */
6789 err = draw_blame(view);
6791 view_border(view);
6792 return err;
6795 static const struct got_error *
6796 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6797 struct got_repository *repo, struct got_object_id *id)
6799 struct tog_view *log_view;
6800 const struct got_error *err = NULL;
6802 *new_view = NULL;
6804 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6805 if (log_view == NULL)
6806 return got_error_from_errno("view_open");
6808 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6809 if (err)
6810 view_close(log_view);
6811 else
6812 *new_view = log_view;
6814 return err;
6817 static const struct got_error *
6818 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6820 const struct got_error *err = NULL, *thread_err = NULL;
6821 struct tog_view *diff_view;
6822 struct tog_blame_view_state *s = &view->state.blame;
6823 int eos, nscroll, begin_y = 0, begin_x = 0;
6825 eos = nscroll = view->nlines - 2;
6826 if (view_is_hsplit_top(view))
6827 --eos; /* border */
6829 switch (ch) {
6830 case '0':
6831 case '$':
6832 case KEY_RIGHT:
6833 case 'l':
6834 case KEY_LEFT:
6835 case 'h':
6836 horizontal_scroll_input(view, ch);
6837 break;
6838 case 'q':
6839 s->done = 1;
6840 break;
6841 case 'g':
6842 case KEY_HOME:
6843 s->selected_line = 1;
6844 s->first_displayed_line = 1;
6845 view->count = 0;
6846 break;
6847 case 'G':
6848 case KEY_END:
6849 if (s->blame.nlines < eos) {
6850 s->selected_line = s->blame.nlines;
6851 s->first_displayed_line = 1;
6852 } else {
6853 s->selected_line = eos;
6854 s->first_displayed_line = s->blame.nlines - (eos - 1);
6856 view->count = 0;
6857 break;
6858 case 'k':
6859 case KEY_UP:
6860 case CTRL('p'):
6861 if (s->selected_line > 1)
6862 s->selected_line--;
6863 else if (s->selected_line == 1 &&
6864 s->first_displayed_line > 1)
6865 s->first_displayed_line--;
6866 else
6867 view->count = 0;
6868 break;
6869 case CTRL('u'):
6870 case 'u':
6871 nscroll /= 2;
6872 /* FALL THROUGH */
6873 case KEY_PPAGE:
6874 case CTRL('b'):
6875 case 'b':
6876 if (s->first_displayed_line == 1) {
6877 if (view->count > 1)
6878 nscroll += nscroll;
6879 s->selected_line = MAX(1, s->selected_line - nscroll);
6880 view->count = 0;
6881 break;
6883 if (s->first_displayed_line > nscroll)
6884 s->first_displayed_line -= nscroll;
6885 else
6886 s->first_displayed_line = 1;
6887 break;
6888 case 'j':
6889 case KEY_DOWN:
6890 case CTRL('n'):
6891 if (s->selected_line < eos && s->first_displayed_line +
6892 s->selected_line <= s->blame.nlines)
6893 s->selected_line++;
6894 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6895 s->first_displayed_line++;
6896 else
6897 view->count = 0;
6898 break;
6899 case 'c':
6900 case 'p': {
6901 struct got_object_id *id = NULL;
6903 view->count = 0;
6904 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6905 s->first_displayed_line, s->selected_line);
6906 if (id == NULL)
6907 break;
6908 if (ch == 'p') {
6909 struct got_commit_object *commit, *pcommit;
6910 struct got_object_qid *pid;
6911 struct got_object_id *blob_id = NULL;
6912 int obj_type;
6913 err = got_object_open_as_commit(&commit,
6914 s->repo, id);
6915 if (err)
6916 break;
6917 pid = STAILQ_FIRST(
6918 got_object_commit_get_parent_ids(commit));
6919 if (pid == NULL) {
6920 got_object_commit_close(commit);
6921 break;
6923 /* Check if path history ends here. */
6924 err = got_object_open_as_commit(&pcommit,
6925 s->repo, &pid->id);
6926 if (err)
6927 break;
6928 err = got_object_id_by_path(&blob_id, s->repo,
6929 pcommit, s->path);
6930 got_object_commit_close(pcommit);
6931 if (err) {
6932 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6933 err = NULL;
6934 got_object_commit_close(commit);
6935 break;
6937 err = got_object_get_type(&obj_type, s->repo,
6938 blob_id);
6939 free(blob_id);
6940 /* Can't blame non-blob type objects. */
6941 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6942 got_object_commit_close(commit);
6943 break;
6945 err = got_object_qid_alloc(&s->blamed_commit,
6946 &pid->id);
6947 got_object_commit_close(commit);
6948 } else {
6949 if (got_object_id_cmp(id,
6950 &s->blamed_commit->id) == 0)
6951 break;
6952 err = got_object_qid_alloc(&s->blamed_commit,
6953 id);
6955 if (err)
6956 break;
6957 s->done = 1;
6958 thread_err = stop_blame(&s->blame);
6959 s->done = 0;
6960 if (thread_err)
6961 break;
6962 STAILQ_INSERT_HEAD(&s->blamed_commits,
6963 s->blamed_commit, entry);
6964 err = run_blame(view);
6965 if (err)
6966 break;
6967 break;
6969 case 'C': {
6970 struct got_object_qid *first;
6972 view->count = 0;
6973 first = STAILQ_FIRST(&s->blamed_commits);
6974 if (!got_object_id_cmp(&first->id, s->commit_id))
6975 break;
6976 s->done = 1;
6977 thread_err = stop_blame(&s->blame);
6978 s->done = 0;
6979 if (thread_err)
6980 break;
6981 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6982 got_object_qid_free(s->blamed_commit);
6983 s->blamed_commit =
6984 STAILQ_FIRST(&s->blamed_commits);
6985 err = run_blame(view);
6986 if (err)
6987 break;
6988 break;
6990 case 'L':
6991 view->count = 0;
6992 s->id_to_log = get_selected_commit_id(s->blame.lines,
6993 s->blame.nlines, s->first_displayed_line, s->selected_line);
6994 if (s->id_to_log)
6995 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6996 break;
6997 case KEY_ENTER:
6998 case '\r': {
6999 struct got_object_id *id = NULL;
7000 struct got_object_qid *pid;
7001 struct got_commit_object *commit = NULL;
7003 view->count = 0;
7004 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
7005 s->first_displayed_line, s->selected_line);
7006 if (id == NULL)
7007 break;
7008 err = got_object_open_as_commit(&commit, s->repo, id);
7009 if (err)
7010 break;
7011 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7012 if (*new_view) {
7013 /* traversed from diff view, release diff resources */
7014 err = close_diff_view(*new_view);
7015 if (err)
7016 break;
7017 diff_view = *new_view;
7018 } else {
7019 if (view_is_parent_view(view))
7020 view_get_split(view, &begin_y, &begin_x);
7022 diff_view = view_open(0, 0, begin_y, begin_x,
7023 TOG_VIEW_DIFF);
7024 if (diff_view == NULL) {
7025 got_object_commit_close(commit);
7026 err = got_error_from_errno("view_open");
7027 break;
7030 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
7031 id, NULL, NULL, 3, 0, 0, view, s->repo);
7032 got_object_commit_close(commit);
7033 if (err)
7034 break;
7035 s->last_diffed_line = s->first_displayed_line - 1 +
7036 s->selected_line;
7037 if (*new_view)
7038 break; /* still open from active diff view */
7039 if (view_is_parent_view(view) &&
7040 view->mode == TOG_VIEW_SPLIT_HRZN) {
7041 err = view_init_hsplit(view, begin_y);
7042 if (err)
7043 break;
7046 view->focussed = 0;
7047 diff_view->focussed = 1;
7048 diff_view->mode = view->mode;
7049 diff_view->nlines = view->lines - begin_y;
7050 if (view_is_parent_view(view)) {
7051 view_transfer_size(diff_view, view);
7052 err = view_close_child(view);
7053 if (err)
7054 break;
7055 err = view_set_child(view, diff_view);
7056 if (err)
7057 break;
7058 view->focus_child = 1;
7059 } else
7060 *new_view = diff_view;
7061 if (err)
7062 break;
7063 break;
7065 case CTRL('d'):
7066 case 'd':
7067 nscroll /= 2;
7068 /* FALL THROUGH */
7069 case KEY_NPAGE:
7070 case CTRL('f'):
7071 case 'f':
7072 case ' ':
7073 if (s->last_displayed_line >= s->blame.nlines &&
7074 s->selected_line >= MIN(s->blame.nlines,
7075 view->nlines - 2)) {
7076 view->count = 0;
7077 break;
7079 if (s->last_displayed_line >= s->blame.nlines &&
7080 s->selected_line < view->nlines - 2) {
7081 s->selected_line +=
7082 MIN(nscroll, s->last_displayed_line -
7083 s->first_displayed_line - s->selected_line + 1);
7085 if (s->last_displayed_line + nscroll <= s->blame.nlines)
7086 s->first_displayed_line += nscroll;
7087 else
7088 s->first_displayed_line =
7089 s->blame.nlines - (view->nlines - 3);
7090 break;
7091 case KEY_RESIZE:
7092 if (s->selected_line > view->nlines - 2) {
7093 s->selected_line = MIN(s->blame.nlines,
7094 view->nlines - 2);
7096 break;
7097 default:
7098 view->count = 0;
7099 break;
7101 return thread_err ? thread_err : err;
7104 static const struct got_error *
7105 reset_blame_view(struct tog_view *view)
7107 const struct got_error *err;
7108 struct tog_blame_view_state *s = &view->state.blame;
7110 view->count = 0;
7111 s->done = 1;
7112 err = stop_blame(&s->blame);
7113 s->done = 0;
7114 if (err)
7115 return err;
7116 return run_blame(view);
7119 static const struct got_error *
7120 cmd_blame(int argc, char *argv[])
7122 const struct got_error *error;
7123 struct got_repository *repo = NULL;
7124 struct got_worktree *worktree = NULL;
7125 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7126 char *link_target = NULL;
7127 struct got_object_id *commit_id = NULL;
7128 struct got_commit_object *commit = NULL;
7129 char *keyword_idstr = NULL, *commit_id_str = NULL;
7130 int ch;
7131 struct tog_view *view = NULL;
7132 int *pack_fds = NULL;
7134 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7135 switch (ch) {
7136 case 'c':
7137 commit_id_str = optarg;
7138 break;
7139 case 'r':
7140 repo_path = realpath(optarg, NULL);
7141 if (repo_path == NULL)
7142 return got_error_from_errno2("realpath",
7143 optarg);
7144 break;
7145 default:
7146 usage_blame();
7147 /* NOTREACHED */
7151 argc -= optind;
7152 argv += optind;
7154 if (argc != 1)
7155 usage_blame();
7157 error = got_repo_pack_fds_open(&pack_fds);
7158 if (error != NULL)
7159 goto done;
7161 if (repo_path == NULL) {
7162 cwd = getcwd(NULL, 0);
7163 if (cwd == NULL)
7164 return got_error_from_errno("getcwd");
7165 error = got_worktree_open(&worktree, cwd, NULL);
7166 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7167 goto done;
7168 if (worktree)
7169 repo_path =
7170 strdup(got_worktree_get_repo_path(worktree));
7171 else
7172 repo_path = strdup(cwd);
7173 if (repo_path == NULL) {
7174 error = got_error_from_errno("strdup");
7175 goto done;
7179 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7180 if (error != NULL)
7181 goto done;
7183 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7184 worktree);
7185 if (error)
7186 goto done;
7188 init_curses();
7190 error = apply_unveil(got_repo_get_path(repo), NULL);
7191 if (error)
7192 goto done;
7194 error = tog_load_refs(repo, 0);
7195 if (error)
7196 goto done;
7198 if (commit_id_str == NULL) {
7199 struct got_reference *head_ref;
7200 error = got_ref_open(&head_ref, repo, worktree ?
7201 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7202 if (error != NULL)
7203 goto done;
7204 error = got_ref_resolve(&commit_id, repo, head_ref);
7205 got_ref_close(head_ref);
7206 } else {
7207 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
7208 repo, worktree);
7209 if (error != NULL)
7210 goto done;
7211 if (keyword_idstr != NULL)
7212 commit_id_str = keyword_idstr;
7214 error = got_repo_match_object_id(&commit_id, NULL,
7215 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7217 if (error != NULL)
7218 goto done;
7220 error = got_object_open_as_commit(&commit, repo, commit_id);
7221 if (error)
7222 goto done;
7224 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7225 commit, repo);
7226 if (error)
7227 goto done;
7229 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7230 if (view == NULL) {
7231 error = got_error_from_errno("view_open");
7232 goto done;
7234 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7235 commit_id, repo);
7236 if (error != NULL) {
7237 if (view->close == NULL)
7238 close_blame_view(view);
7239 view_close(view);
7240 goto done;
7243 if (worktree) {
7244 error = set_tog_base_commit(repo, worktree);
7245 if (error != NULL)
7246 goto done;
7248 /* Release work tree lock. */
7249 got_worktree_close(worktree);
7250 worktree = NULL;
7253 error = view_loop(view);
7255 done:
7256 free(tog_base_commit.id);
7257 free(repo_path);
7258 free(in_repo_path);
7259 free(link_target);
7260 free(cwd);
7261 free(commit_id);
7262 free(keyword_idstr);
7263 if (commit)
7264 got_object_commit_close(commit);
7265 if (worktree)
7266 got_worktree_close(worktree);
7267 if (repo) {
7268 const struct got_error *close_err = got_repo_close(repo);
7269 if (error == NULL)
7270 error = close_err;
7272 if (pack_fds) {
7273 const struct got_error *pack_err =
7274 got_repo_pack_fds_close(pack_fds);
7275 if (error == NULL)
7276 error = pack_err;
7278 tog_free_refs();
7279 return error;
7282 static const struct got_error *
7283 draw_tree_entries(struct tog_view *view, const char *parent_path)
7285 struct tog_tree_view_state *s = &view->state.tree;
7286 const struct got_error *err = NULL;
7287 struct got_tree_entry *te;
7288 wchar_t *wline;
7289 char *index = NULL;
7290 struct tog_color *tc;
7291 int width, n, nentries, scrollx, i = 1;
7292 int limit = view->nlines;
7294 s->ndisplayed = 0;
7295 if (view_is_hsplit_top(view))
7296 --limit; /* border */
7298 werase(view->window);
7300 if (limit == 0)
7301 return NULL;
7303 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7304 0, 0);
7305 if (err)
7306 return err;
7307 if (view_needs_focus_indication(view))
7308 wstandout(view->window);
7309 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7310 if (tc)
7311 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7312 waddwstr(view->window, wline);
7313 free(wline);
7314 wline = NULL;
7315 while (width++ < view->ncols)
7316 waddch(view->window, ' ');
7317 if (tc)
7318 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7319 if (view_needs_focus_indication(view))
7320 wstandend(view->window);
7321 if (--limit <= 0)
7322 return NULL;
7324 i += s->selected;
7325 if (s->first_displayed_entry) {
7326 i += got_tree_entry_get_index(s->first_displayed_entry);
7327 if (s->tree != s->root)
7328 ++i; /* account for ".." entry */
7330 nentries = got_object_tree_get_nentries(s->tree);
7331 if (asprintf(&index, "[%d/%d] %s",
7332 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7333 return got_error_from_errno("asprintf");
7334 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7335 free(index);
7336 if (err)
7337 return err;
7338 waddwstr(view->window, wline);
7339 free(wline);
7340 wline = NULL;
7341 if (width < view->ncols - 1)
7342 waddch(view->window, '\n');
7343 if (--limit <= 0)
7344 return NULL;
7345 waddch(view->window, '\n');
7346 if (--limit <= 0)
7347 return NULL;
7349 if (s->first_displayed_entry == NULL) {
7350 te = got_object_tree_get_first_entry(s->tree);
7351 if (s->selected == 0) {
7352 if (view->focussed)
7353 wstandout(view->window);
7354 s->selected_entry = NULL;
7356 waddstr(view->window, " ..\n"); /* parent directory */
7357 if (s->selected == 0 && view->focussed)
7358 wstandend(view->window);
7359 s->ndisplayed++;
7360 if (--limit <= 0)
7361 return NULL;
7362 n = 1;
7363 } else {
7364 n = 0;
7365 te = s->first_displayed_entry;
7368 view->maxx = 0;
7369 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7370 char *line = NULL, *id_str = NULL, *link_target = NULL;
7371 const char *modestr = "";
7372 mode_t mode;
7374 te = got_object_tree_get_entry(s->tree, i);
7375 mode = got_tree_entry_get_mode(te);
7377 if (s->show_ids) {
7378 err = got_object_id_str(&id_str,
7379 got_tree_entry_get_id(te));
7380 if (err)
7381 return got_error_from_errno(
7382 "got_object_id_str");
7384 if (got_object_tree_entry_is_submodule(te))
7385 modestr = "$";
7386 else if (S_ISLNK(mode)) {
7387 int i;
7389 err = got_tree_entry_get_symlink_target(&link_target,
7390 te, s->repo);
7391 if (err) {
7392 free(id_str);
7393 return err;
7395 for (i = 0; link_target[i] != '\0'; i++) {
7396 if (!isprint((unsigned char)link_target[i]))
7397 link_target[i] = '?';
7399 modestr = "@";
7401 else if (S_ISDIR(mode))
7402 modestr = "/";
7403 else if (mode & S_IXUSR)
7404 modestr = "*";
7405 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7406 got_tree_entry_get_name(te), modestr,
7407 link_target ? " -> ": "",
7408 link_target ? link_target : "") == -1) {
7409 free(id_str);
7410 free(link_target);
7411 return got_error_from_errno("asprintf");
7413 free(id_str);
7414 free(link_target);
7416 /* use full line width to determine view->maxx */
7417 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7418 if (err) {
7419 free(line);
7420 break;
7422 view->maxx = MAX(view->maxx, width);
7423 free(wline);
7424 wline = NULL;
7426 err = format_line(&wline, &width, &scrollx, line, view->x,
7427 view->ncols, 0, 0);
7428 if (err) {
7429 free(line);
7430 break;
7432 if (n == s->selected) {
7433 if (view->focussed)
7434 wstandout(view->window);
7435 s->selected_entry = te;
7437 tc = match_color(&s->colors, line);
7438 if (tc)
7439 wattr_on(view->window,
7440 COLOR_PAIR(tc->colorpair), NULL);
7441 waddwstr(view->window, &wline[scrollx]);
7442 if (tc)
7443 wattr_off(view->window,
7444 COLOR_PAIR(tc->colorpair), NULL);
7445 if (width < view->ncols)
7446 waddch(view->window, '\n');
7447 if (n == s->selected && view->focussed)
7448 wstandend(view->window);
7449 free(line);
7450 free(wline);
7451 wline = NULL;
7452 n++;
7453 s->ndisplayed++;
7454 s->last_displayed_entry = te;
7455 if (--limit <= 0)
7456 break;
7459 return err;
7462 static void
7463 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7465 struct got_tree_entry *te;
7466 int isroot = s->tree == s->root;
7467 int i = 0;
7469 if (s->first_displayed_entry == NULL)
7470 return;
7472 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7473 while (i++ < maxscroll) {
7474 if (te == NULL) {
7475 if (!isroot)
7476 s->first_displayed_entry = NULL;
7477 break;
7479 s->first_displayed_entry = te;
7480 te = got_tree_entry_get_prev(s->tree, te);
7484 static const struct got_error *
7485 tree_scroll_down(struct tog_view *view, int maxscroll)
7487 struct tog_tree_view_state *s = &view->state.tree;
7488 struct got_tree_entry *next, *last;
7489 int n = 0;
7491 if (s->first_displayed_entry)
7492 next = got_tree_entry_get_next(s->tree,
7493 s->first_displayed_entry);
7494 else
7495 next = got_object_tree_get_first_entry(s->tree);
7497 last = s->last_displayed_entry;
7498 while (next && n++ < maxscroll) {
7499 if (last) {
7500 s->last_displayed_entry = last;
7501 last = got_tree_entry_get_next(s->tree, last);
7503 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7504 s->first_displayed_entry = next;
7505 next = got_tree_entry_get_next(s->tree, next);
7509 return NULL;
7512 static const struct got_error *
7513 tree_entry_path(char **path, struct tog_parent_trees *parents,
7514 struct got_tree_entry *te)
7516 const struct got_error *err = NULL;
7517 struct tog_parent_tree *pt;
7518 size_t len = 2; /* for leading slash and NUL */
7520 TAILQ_FOREACH(pt, parents, entry)
7521 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7522 + 1 /* slash */;
7523 if (te)
7524 len += strlen(got_tree_entry_get_name(te));
7526 *path = calloc(1, len);
7527 if (path == NULL)
7528 return got_error_from_errno("calloc");
7530 (*path)[0] = '/';
7531 pt = TAILQ_LAST(parents, tog_parent_trees);
7532 while (pt) {
7533 const char *name = got_tree_entry_get_name(pt->selected_entry);
7534 if (strlcat(*path, name, len) >= len) {
7535 err = got_error(GOT_ERR_NO_SPACE);
7536 goto done;
7538 if (strlcat(*path, "/", len) >= len) {
7539 err = got_error(GOT_ERR_NO_SPACE);
7540 goto done;
7542 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7544 if (te) {
7545 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7546 err = got_error(GOT_ERR_NO_SPACE);
7547 goto done;
7550 done:
7551 if (err) {
7552 free(*path);
7553 *path = NULL;
7555 return err;
7558 static const struct got_error *
7559 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7560 struct got_tree_entry *te, struct tog_parent_trees *parents,
7561 struct got_object_id *commit_id, struct got_repository *repo)
7563 const struct got_error *err = NULL;
7564 char *path;
7565 struct tog_view *blame_view;
7567 *new_view = NULL;
7569 err = tree_entry_path(&path, parents, te);
7570 if (err)
7571 return err;
7573 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7574 if (blame_view == NULL) {
7575 err = got_error_from_errno("view_open");
7576 goto done;
7579 err = open_blame_view(blame_view, path, commit_id, repo);
7580 if (err) {
7581 if (err->code == GOT_ERR_CANCELLED)
7582 err = NULL;
7583 view_close(blame_view);
7584 } else
7585 *new_view = blame_view;
7586 done:
7587 free(path);
7588 return err;
7591 static const struct got_error *
7592 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7593 struct tog_tree_view_state *s)
7595 struct tog_view *log_view;
7596 const struct got_error *err = NULL;
7597 char *path;
7599 *new_view = NULL;
7601 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7602 if (log_view == NULL)
7603 return got_error_from_errno("view_open");
7605 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7606 if (err)
7607 return err;
7609 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7610 path, 0);
7611 if (err)
7612 view_close(log_view);
7613 else
7614 *new_view = log_view;
7615 free(path);
7616 return err;
7619 static const struct got_error *
7620 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7621 const char *head_ref_name, struct got_repository *repo)
7623 const struct got_error *err = NULL;
7624 char *commit_id_str = NULL;
7625 struct tog_tree_view_state *s = &view->state.tree;
7626 struct got_commit_object *commit = NULL;
7628 TAILQ_INIT(&s->parents);
7629 STAILQ_INIT(&s->colors);
7631 s->commit_id = got_object_id_dup(commit_id);
7632 if (s->commit_id == NULL) {
7633 err = got_error_from_errno("got_object_id_dup");
7634 goto done;
7637 err = got_object_open_as_commit(&commit, repo, commit_id);
7638 if (err)
7639 goto done;
7642 * The root is opened here and will be closed when the view is closed.
7643 * Any visited subtrees and their path-wise parents are opened and
7644 * closed on demand.
7646 err = got_object_open_as_tree(&s->root, repo,
7647 got_object_commit_get_tree_id(commit));
7648 if (err)
7649 goto done;
7650 s->tree = s->root;
7652 err = got_object_id_str(&commit_id_str, commit_id);
7653 if (err != NULL)
7654 goto done;
7656 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7657 err = got_error_from_errno("asprintf");
7658 goto done;
7661 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7662 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7663 if (head_ref_name) {
7664 s->head_ref_name = strdup(head_ref_name);
7665 if (s->head_ref_name == NULL) {
7666 err = got_error_from_errno("strdup");
7667 goto done;
7670 s->repo = repo;
7672 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7673 err = add_color(&s->colors, "\\$$",
7674 TOG_COLOR_TREE_SUBMODULE,
7675 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7676 if (err)
7677 goto done;
7678 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7679 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7680 if (err)
7681 goto done;
7682 err = add_color(&s->colors, "/$",
7683 TOG_COLOR_TREE_DIRECTORY,
7684 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7685 if (err)
7686 goto done;
7688 err = add_color(&s->colors, "\\*$",
7689 TOG_COLOR_TREE_EXECUTABLE,
7690 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7691 if (err)
7692 goto done;
7694 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7695 get_color_value("TOG_COLOR_COMMIT"));
7696 if (err)
7697 goto done;
7700 view->show = show_tree_view;
7701 view->input = input_tree_view;
7702 view->close = close_tree_view;
7703 view->search_start = search_start_tree_view;
7704 view->search_next = search_next_tree_view;
7705 done:
7706 free(commit_id_str);
7707 if (commit)
7708 got_object_commit_close(commit);
7709 if (err) {
7710 if (view->close == NULL)
7711 close_tree_view(view);
7712 view_close(view);
7714 return err;
7717 static const struct got_error *
7718 close_tree_view(struct tog_view *view)
7720 struct tog_tree_view_state *s = &view->state.tree;
7722 free_colors(&s->colors);
7723 free(s->tree_label);
7724 s->tree_label = NULL;
7725 free(s->commit_id);
7726 s->commit_id = NULL;
7727 free(s->head_ref_name);
7728 s->head_ref_name = NULL;
7729 while (!TAILQ_EMPTY(&s->parents)) {
7730 struct tog_parent_tree *parent;
7731 parent = TAILQ_FIRST(&s->parents);
7732 TAILQ_REMOVE(&s->parents, parent, entry);
7733 if (parent->tree != s->root)
7734 got_object_tree_close(parent->tree);
7735 free(parent);
7738 if (s->tree != NULL && s->tree != s->root)
7739 got_object_tree_close(s->tree);
7740 if (s->root)
7741 got_object_tree_close(s->root);
7742 return NULL;
7745 static const struct got_error *
7746 search_start_tree_view(struct tog_view *view)
7748 struct tog_tree_view_state *s = &view->state.tree;
7750 s->matched_entry = NULL;
7751 return NULL;
7754 static int
7755 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7757 regmatch_t regmatch;
7759 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7760 0) == 0;
7763 static const struct got_error *
7764 search_next_tree_view(struct tog_view *view)
7766 struct tog_tree_view_state *s = &view->state.tree;
7767 struct got_tree_entry *te = NULL;
7769 if (!view->searching) {
7770 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7771 return NULL;
7774 if (s->matched_entry) {
7775 if (view->searching == TOG_SEARCH_FORWARD) {
7776 if (s->selected_entry)
7777 te = got_tree_entry_get_next(s->tree,
7778 s->selected_entry);
7779 else
7780 te = got_object_tree_get_first_entry(s->tree);
7781 } else {
7782 if (s->selected_entry == NULL)
7783 te = got_object_tree_get_last_entry(s->tree);
7784 else
7785 te = got_tree_entry_get_prev(s->tree,
7786 s->selected_entry);
7788 } else {
7789 if (s->selected_entry)
7790 te = s->selected_entry;
7791 else if (view->searching == TOG_SEARCH_FORWARD)
7792 te = got_object_tree_get_first_entry(s->tree);
7793 else
7794 te = got_object_tree_get_last_entry(s->tree);
7797 while (1) {
7798 if (te == NULL) {
7799 if (s->matched_entry == NULL) {
7800 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7801 return NULL;
7803 if (view->searching == TOG_SEARCH_FORWARD)
7804 te = got_object_tree_get_first_entry(s->tree);
7805 else
7806 te = got_object_tree_get_last_entry(s->tree);
7809 if (match_tree_entry(te, &view->regex)) {
7810 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7811 s->matched_entry = te;
7812 break;
7815 if (view->searching == TOG_SEARCH_FORWARD)
7816 te = got_tree_entry_get_next(s->tree, te);
7817 else
7818 te = got_tree_entry_get_prev(s->tree, te);
7821 if (s->matched_entry) {
7822 s->first_displayed_entry = s->matched_entry;
7823 s->selected = 0;
7826 return NULL;
7829 static const struct got_error *
7830 show_tree_view(struct tog_view *view)
7832 const struct got_error *err = NULL;
7833 struct tog_tree_view_state *s = &view->state.tree;
7834 char *parent_path;
7836 err = tree_entry_path(&parent_path, &s->parents, NULL);
7837 if (err)
7838 return err;
7840 err = draw_tree_entries(view, parent_path);
7841 free(parent_path);
7843 view_border(view);
7844 return err;
7847 static const struct got_error *
7848 tree_goto_line(struct tog_view *view, int nlines)
7850 const struct got_error *err = NULL;
7851 struct tog_tree_view_state *s = &view->state.tree;
7852 struct got_tree_entry **fte, **lte, **ste;
7853 int g, last, first = 1, i = 1;
7854 int root = s->tree == s->root;
7855 int off = root ? 1 : 2;
7857 g = view->gline;
7858 view->gline = 0;
7860 if (g == 0)
7861 g = 1;
7862 else if (g > got_object_tree_get_nentries(s->tree))
7863 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7865 fte = &s->first_displayed_entry;
7866 lte = &s->last_displayed_entry;
7867 ste = &s->selected_entry;
7869 if (*fte != NULL) {
7870 first = got_tree_entry_get_index(*fte);
7871 first += off; /* account for ".." */
7873 last = got_tree_entry_get_index(*lte);
7874 last += off;
7876 if (g >= first && g <= last && g - first < nlines) {
7877 s->selected = g - first;
7878 return NULL; /* gline is on the current page */
7881 if (*ste != NULL) {
7882 i = got_tree_entry_get_index(*ste);
7883 i += off;
7886 if (i < g) {
7887 err = tree_scroll_down(view, g - i);
7888 if (err)
7889 return err;
7890 if (got_tree_entry_get_index(*lte) >=
7891 got_object_tree_get_nentries(s->tree) - 1 &&
7892 first + s->selected < g &&
7893 s->selected < s->ndisplayed - 1) {
7894 first = got_tree_entry_get_index(*fte);
7895 first += off;
7896 s->selected = g - first;
7898 } else if (i > g)
7899 tree_scroll_up(s, i - g);
7901 if (g < nlines &&
7902 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7903 s->selected = g - 1;
7905 return NULL;
7908 static const struct got_error *
7909 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7911 const struct got_error *err = NULL;
7912 struct tog_tree_view_state *s = &view->state.tree;
7913 struct got_tree_entry *te;
7914 int n, nscroll = view->nlines - 3;
7916 if (view->gline)
7917 return tree_goto_line(view, nscroll);
7919 switch (ch) {
7920 case '0':
7921 case '$':
7922 case KEY_RIGHT:
7923 case 'l':
7924 case KEY_LEFT:
7925 case 'h':
7926 horizontal_scroll_input(view, ch);
7927 break;
7928 case 'i':
7929 s->show_ids = !s->show_ids;
7930 view->count = 0;
7931 break;
7932 case 'L':
7933 view->count = 0;
7934 if (!s->selected_entry)
7935 break;
7936 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7937 break;
7938 case 'R':
7939 view->count = 0;
7940 err = view_request_new(new_view, view, TOG_VIEW_REF);
7941 break;
7942 case 'g':
7943 case '=':
7944 case KEY_HOME:
7945 s->selected = 0;
7946 view->count = 0;
7947 if (s->tree == s->root)
7948 s->first_displayed_entry =
7949 got_object_tree_get_first_entry(s->tree);
7950 else
7951 s->first_displayed_entry = NULL;
7952 break;
7953 case 'G':
7954 case '*':
7955 case KEY_END: {
7956 int eos = view->nlines - 3;
7958 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7959 --eos; /* border */
7960 s->selected = 0;
7961 view->count = 0;
7962 te = got_object_tree_get_last_entry(s->tree);
7963 for (n = 0; n < eos; n++) {
7964 if (te == NULL) {
7965 if (s->tree != s->root) {
7966 s->first_displayed_entry = NULL;
7967 n++;
7969 break;
7971 s->first_displayed_entry = te;
7972 te = got_tree_entry_get_prev(s->tree, te);
7974 if (n > 0)
7975 s->selected = n - 1;
7976 break;
7978 case 'k':
7979 case KEY_UP:
7980 case CTRL('p'):
7981 if (s->selected > 0) {
7982 s->selected--;
7983 break;
7985 tree_scroll_up(s, 1);
7986 if (s->selected_entry == NULL ||
7987 (s->tree == s->root && s->selected_entry ==
7988 got_object_tree_get_first_entry(s->tree)))
7989 view->count = 0;
7990 break;
7991 case CTRL('u'):
7992 case 'u':
7993 nscroll /= 2;
7994 /* FALL THROUGH */
7995 case KEY_PPAGE:
7996 case CTRL('b'):
7997 case 'b':
7998 if (s->tree == s->root) {
7999 if (got_object_tree_get_first_entry(s->tree) ==
8000 s->first_displayed_entry)
8001 s->selected -= MIN(s->selected, nscroll);
8002 } else {
8003 if (s->first_displayed_entry == NULL)
8004 s->selected -= MIN(s->selected, nscroll);
8006 tree_scroll_up(s, MAX(0, nscroll));
8007 if (s->selected_entry == NULL ||
8008 (s->tree == s->root && s->selected_entry ==
8009 got_object_tree_get_first_entry(s->tree)))
8010 view->count = 0;
8011 break;
8012 case 'j':
8013 case KEY_DOWN:
8014 case CTRL('n'):
8015 if (s->selected < s->ndisplayed - 1) {
8016 s->selected++;
8017 break;
8019 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8020 == NULL) {
8021 /* can't scroll any further */
8022 view->count = 0;
8023 break;
8025 tree_scroll_down(view, 1);
8026 break;
8027 case CTRL('d'):
8028 case 'd':
8029 nscroll /= 2;
8030 /* FALL THROUGH */
8031 case KEY_NPAGE:
8032 case CTRL('f'):
8033 case 'f':
8034 case ' ':
8035 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8036 == NULL) {
8037 /* can't scroll any further; move cursor down */
8038 if (s->selected < s->ndisplayed - 1)
8039 s->selected += MIN(nscroll,
8040 s->ndisplayed - s->selected - 1);
8041 else
8042 view->count = 0;
8043 break;
8045 tree_scroll_down(view, nscroll);
8046 break;
8047 case KEY_ENTER:
8048 case '\r':
8049 case KEY_BACKSPACE:
8050 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
8051 struct tog_parent_tree *parent;
8052 /* user selected '..' */
8053 if (s->tree == s->root) {
8054 view->count = 0;
8055 break;
8057 parent = TAILQ_FIRST(&s->parents);
8058 TAILQ_REMOVE(&s->parents, parent,
8059 entry);
8060 got_object_tree_close(s->tree);
8061 s->tree = parent->tree;
8062 s->first_displayed_entry =
8063 parent->first_displayed_entry;
8064 s->selected_entry =
8065 parent->selected_entry;
8066 s->selected = parent->selected;
8067 if (s->selected > view->nlines - 3) {
8068 err = offset_selection_down(view);
8069 if (err)
8070 break;
8072 free(parent);
8073 } else if (S_ISDIR(got_tree_entry_get_mode(
8074 s->selected_entry))) {
8075 struct got_tree_object *subtree;
8076 view->count = 0;
8077 err = got_object_open_as_tree(&subtree, s->repo,
8078 got_tree_entry_get_id(s->selected_entry));
8079 if (err)
8080 break;
8081 err = tree_view_visit_subtree(s, subtree);
8082 if (err) {
8083 got_object_tree_close(subtree);
8084 break;
8086 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
8087 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
8088 break;
8089 case KEY_RESIZE:
8090 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
8091 s->selected = view->nlines - 4;
8092 view->count = 0;
8093 break;
8094 default:
8095 view->count = 0;
8096 break;
8099 return err;
8102 __dead static void
8103 usage_tree(void)
8105 endwin();
8106 fprintf(stderr,
8107 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
8108 getprogname());
8109 exit(1);
8112 static const struct got_error *
8113 cmd_tree(int argc, char *argv[])
8115 const struct got_error *error;
8116 struct got_repository *repo = NULL;
8117 struct got_worktree *worktree = NULL;
8118 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8119 struct got_object_id *commit_id = NULL;
8120 struct got_commit_object *commit = NULL;
8121 const char *commit_id_arg = NULL;
8122 char *keyword_idstr = NULL, *label = NULL;
8123 struct got_reference *ref = NULL;
8124 const char *head_ref_name = NULL;
8125 int ch;
8126 struct tog_view *view;
8127 int *pack_fds = NULL;
8129 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
8130 switch (ch) {
8131 case 'c':
8132 commit_id_arg = optarg;
8133 break;
8134 case 'r':
8135 repo_path = realpath(optarg, NULL);
8136 if (repo_path == NULL)
8137 return got_error_from_errno2("realpath",
8138 optarg);
8139 break;
8140 default:
8141 usage_tree();
8142 /* NOTREACHED */
8146 argc -= optind;
8147 argv += optind;
8149 if (argc > 1)
8150 usage_tree();
8152 error = got_repo_pack_fds_open(&pack_fds);
8153 if (error != NULL)
8154 goto done;
8156 if (repo_path == NULL) {
8157 cwd = getcwd(NULL, 0);
8158 if (cwd == NULL)
8159 return got_error_from_errno("getcwd");
8160 error = got_worktree_open(&worktree, cwd, NULL);
8161 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8162 goto done;
8163 if (worktree)
8164 repo_path =
8165 strdup(got_worktree_get_repo_path(worktree));
8166 else
8167 repo_path = strdup(cwd);
8168 if (repo_path == NULL) {
8169 error = got_error_from_errno("strdup");
8170 goto done;
8174 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8175 if (error != NULL)
8176 goto done;
8178 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8179 repo, worktree);
8180 if (error)
8181 goto done;
8183 init_curses();
8185 error = apply_unveil(got_repo_get_path(repo), NULL);
8186 if (error)
8187 goto done;
8189 error = tog_load_refs(repo, 0);
8190 if (error)
8191 goto done;
8193 if (commit_id_arg == NULL) {
8194 error = got_repo_match_object_id(&commit_id, &label,
8195 worktree ? got_worktree_get_head_ref_name(worktree) :
8196 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8197 if (error)
8198 goto done;
8199 head_ref_name = label;
8200 } else {
8201 error = got_keyword_to_idstr(&keyword_idstr, commit_id_arg,
8202 repo, worktree);
8203 if (error != NULL)
8204 goto done;
8205 if (keyword_idstr != NULL)
8206 commit_id_arg = keyword_idstr;
8208 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8209 if (error == NULL)
8210 head_ref_name = got_ref_get_name(ref);
8211 else if (error->code != GOT_ERR_NOT_REF)
8212 goto done;
8213 error = got_repo_match_object_id(&commit_id, NULL,
8214 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8215 if (error)
8216 goto done;
8219 error = got_object_open_as_commit(&commit, repo, commit_id);
8220 if (error)
8221 goto done;
8223 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8224 if (view == NULL) {
8225 error = got_error_from_errno("view_open");
8226 goto done;
8228 error = open_tree_view(view, commit_id, head_ref_name, repo);
8229 if (error)
8230 goto done;
8231 if (!got_path_is_root_dir(in_repo_path)) {
8232 error = tree_view_walk_path(&view->state.tree, commit,
8233 in_repo_path);
8234 if (error)
8235 goto done;
8238 if (worktree) {
8239 error = set_tog_base_commit(repo, worktree);
8240 if (error != NULL)
8241 goto done;
8243 /* Release work tree lock. */
8244 got_worktree_close(worktree);
8245 worktree = NULL;
8248 error = view_loop(view);
8250 done:
8251 free(tog_base_commit.id);
8252 free(keyword_idstr);
8253 free(repo_path);
8254 free(cwd);
8255 free(commit_id);
8256 free(label);
8257 if (ref)
8258 got_ref_close(ref);
8259 if (worktree != NULL)
8260 got_worktree_close(worktree);
8261 if (repo) {
8262 const struct got_error *close_err = got_repo_close(repo);
8263 if (error == NULL)
8264 error = close_err;
8266 if (pack_fds) {
8267 const struct got_error *pack_err =
8268 got_repo_pack_fds_close(pack_fds);
8269 if (error == NULL)
8270 error = pack_err;
8272 tog_free_refs();
8273 return error;
8276 static const struct got_error *
8277 ref_view_load_refs(struct tog_ref_view_state *s)
8279 struct got_reflist_entry *sre;
8280 struct tog_reflist_entry *re;
8282 s->nrefs = 0;
8283 TAILQ_FOREACH(sre, &tog_refs, entry) {
8284 if (strncmp(got_ref_get_name(sre->ref),
8285 "refs/got/", 9) == 0 &&
8286 strncmp(got_ref_get_name(sre->ref),
8287 "refs/got/backup/", 16) != 0)
8288 continue;
8290 re = malloc(sizeof(*re));
8291 if (re == NULL)
8292 return got_error_from_errno("malloc");
8294 re->ref = got_ref_dup(sre->ref);
8295 if (re->ref == NULL)
8296 return got_error_from_errno("got_ref_dup");
8297 re->idx = s->nrefs++;
8298 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8301 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8302 return NULL;
8305 static void
8306 ref_view_free_refs(struct tog_ref_view_state *s)
8308 struct tog_reflist_entry *re;
8310 while (!TAILQ_EMPTY(&s->refs)) {
8311 re = TAILQ_FIRST(&s->refs);
8312 TAILQ_REMOVE(&s->refs, re, entry);
8313 got_ref_close(re->ref);
8314 free(re);
8318 static const struct got_error *
8319 open_ref_view(struct tog_view *view, struct got_repository *repo)
8321 const struct got_error *err = NULL;
8322 struct tog_ref_view_state *s = &view->state.ref;
8324 s->selected_entry = 0;
8325 s->repo = repo;
8327 TAILQ_INIT(&s->refs);
8328 STAILQ_INIT(&s->colors);
8330 err = ref_view_load_refs(s);
8331 if (err)
8332 goto done;
8334 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8335 err = add_color(&s->colors, "^refs/heads/",
8336 TOG_COLOR_REFS_HEADS,
8337 get_color_value("TOG_COLOR_REFS_HEADS"));
8338 if (err)
8339 goto done;
8341 err = add_color(&s->colors, "^refs/tags/",
8342 TOG_COLOR_REFS_TAGS,
8343 get_color_value("TOG_COLOR_REFS_TAGS"));
8344 if (err)
8345 goto done;
8347 err = add_color(&s->colors, "^refs/remotes/",
8348 TOG_COLOR_REFS_REMOTES,
8349 get_color_value("TOG_COLOR_REFS_REMOTES"));
8350 if (err)
8351 goto done;
8353 err = add_color(&s->colors, "^refs/got/backup/",
8354 TOG_COLOR_REFS_BACKUP,
8355 get_color_value("TOG_COLOR_REFS_BACKUP"));
8356 if (err)
8357 goto done;
8360 view->show = show_ref_view;
8361 view->input = input_ref_view;
8362 view->close = close_ref_view;
8363 view->search_start = search_start_ref_view;
8364 view->search_next = search_next_ref_view;
8365 done:
8366 if (err) {
8367 if (view->close == NULL)
8368 close_ref_view(view);
8369 view_close(view);
8371 return err;
8374 static const struct got_error *
8375 close_ref_view(struct tog_view *view)
8377 struct tog_ref_view_state *s = &view->state.ref;
8379 ref_view_free_refs(s);
8380 free_colors(&s->colors);
8382 return NULL;
8385 static const struct got_error *
8386 resolve_reflist_entry(struct got_object_id **commit_id,
8387 struct tog_reflist_entry *re, struct got_repository *repo)
8389 const struct got_error *err = NULL;
8390 struct got_object_id *obj_id;
8391 struct got_tag_object *tag = NULL;
8392 int obj_type;
8394 *commit_id = NULL;
8396 err = got_ref_resolve(&obj_id, repo, re->ref);
8397 if (err)
8398 return err;
8400 err = got_object_get_type(&obj_type, repo, obj_id);
8401 if (err)
8402 goto done;
8404 switch (obj_type) {
8405 case GOT_OBJ_TYPE_COMMIT:
8406 *commit_id = obj_id;
8407 break;
8408 case GOT_OBJ_TYPE_TAG:
8409 err = got_object_open_as_tag(&tag, repo, obj_id);
8410 if (err)
8411 goto done;
8412 free(obj_id);
8413 err = got_object_get_type(&obj_type, repo,
8414 got_object_tag_get_object_id(tag));
8415 if (err)
8416 goto done;
8417 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8418 err = got_error(GOT_ERR_OBJ_TYPE);
8419 goto done;
8421 *commit_id = got_object_id_dup(
8422 got_object_tag_get_object_id(tag));
8423 if (*commit_id == NULL) {
8424 err = got_error_from_errno("got_object_id_dup");
8425 goto done;
8427 break;
8428 default:
8429 err = got_error(GOT_ERR_OBJ_TYPE);
8430 break;
8433 done:
8434 if (tag)
8435 got_object_tag_close(tag);
8436 if (err) {
8437 free(*commit_id);
8438 *commit_id = NULL;
8440 return err;
8443 static const struct got_error *
8444 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8445 struct tog_reflist_entry *re, struct got_repository *repo)
8447 struct tog_view *log_view;
8448 const struct got_error *err = NULL;
8449 struct got_object_id *commit_id = NULL;
8451 *new_view = NULL;
8453 err = resolve_reflist_entry(&commit_id, re, repo);
8454 if (err) {
8455 if (err->code != GOT_ERR_OBJ_TYPE)
8456 return err;
8457 else
8458 return NULL;
8461 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8462 if (log_view == NULL) {
8463 err = got_error_from_errno("view_open");
8464 goto done;
8467 err = open_log_view(log_view, commit_id, repo,
8468 got_ref_get_name(re->ref), "", 0);
8469 done:
8470 if (err)
8471 view_close(log_view);
8472 else
8473 *new_view = log_view;
8474 free(commit_id);
8475 return err;
8478 static void
8479 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8481 struct tog_reflist_entry *re;
8482 int i = 0;
8484 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8485 return;
8487 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8488 while (i++ < maxscroll) {
8489 if (re == NULL)
8490 break;
8491 s->first_displayed_entry = re;
8492 re = TAILQ_PREV(re, tog_reflist_head, entry);
8496 static const struct got_error *
8497 ref_scroll_down(struct tog_view *view, int maxscroll)
8499 struct tog_ref_view_state *s = &view->state.ref;
8500 struct tog_reflist_entry *next, *last;
8501 int n = 0;
8503 if (s->first_displayed_entry)
8504 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8505 else
8506 next = TAILQ_FIRST(&s->refs);
8508 last = s->last_displayed_entry;
8509 while (next && n++ < maxscroll) {
8510 if (last) {
8511 s->last_displayed_entry = last;
8512 last = TAILQ_NEXT(last, entry);
8514 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8515 s->first_displayed_entry = next;
8516 next = TAILQ_NEXT(next, entry);
8520 return NULL;
8523 static const struct got_error *
8524 search_start_ref_view(struct tog_view *view)
8526 struct tog_ref_view_state *s = &view->state.ref;
8528 s->matched_entry = NULL;
8529 return NULL;
8532 static int
8533 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8535 regmatch_t regmatch;
8537 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8538 0) == 0;
8541 static const struct got_error *
8542 search_next_ref_view(struct tog_view *view)
8544 struct tog_ref_view_state *s = &view->state.ref;
8545 struct tog_reflist_entry *re = NULL;
8547 if (!view->searching) {
8548 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8549 return NULL;
8552 if (s->matched_entry) {
8553 if (view->searching == TOG_SEARCH_FORWARD) {
8554 if (s->selected_entry)
8555 re = TAILQ_NEXT(s->selected_entry, entry);
8556 else
8557 re = TAILQ_PREV(s->selected_entry,
8558 tog_reflist_head, entry);
8559 } else {
8560 if (s->selected_entry == NULL)
8561 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8562 else
8563 re = TAILQ_PREV(s->selected_entry,
8564 tog_reflist_head, entry);
8566 } else {
8567 if (s->selected_entry)
8568 re = s->selected_entry;
8569 else if (view->searching == TOG_SEARCH_FORWARD)
8570 re = TAILQ_FIRST(&s->refs);
8571 else
8572 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8575 while (1) {
8576 if (re == NULL) {
8577 if (s->matched_entry == NULL) {
8578 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8579 return NULL;
8581 if (view->searching == TOG_SEARCH_FORWARD)
8582 re = TAILQ_FIRST(&s->refs);
8583 else
8584 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8587 if (match_reflist_entry(re, &view->regex)) {
8588 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8589 s->matched_entry = re;
8590 break;
8593 if (view->searching == TOG_SEARCH_FORWARD)
8594 re = TAILQ_NEXT(re, entry);
8595 else
8596 re = TAILQ_PREV(re, tog_reflist_head, entry);
8599 if (s->matched_entry) {
8600 s->first_displayed_entry = s->matched_entry;
8601 s->selected = 0;
8604 return NULL;
8607 static const struct got_error *
8608 show_ref_view(struct tog_view *view)
8610 const struct got_error *err = NULL;
8611 struct tog_ref_view_state *s = &view->state.ref;
8612 struct tog_reflist_entry *re;
8613 char *line = NULL;
8614 wchar_t *wline;
8615 struct tog_color *tc;
8616 int width, n, scrollx;
8617 int limit = view->nlines;
8619 werase(view->window);
8621 s->ndisplayed = 0;
8622 if (view_is_hsplit_top(view))
8623 --limit; /* border */
8625 if (limit == 0)
8626 return NULL;
8628 re = s->first_displayed_entry;
8630 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8631 s->nrefs) == -1)
8632 return got_error_from_errno("asprintf");
8634 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8635 if (err) {
8636 free(line);
8637 return err;
8639 if (view_needs_focus_indication(view))
8640 wstandout(view->window);
8641 waddwstr(view->window, wline);
8642 while (width++ < view->ncols)
8643 waddch(view->window, ' ');
8644 if (view_needs_focus_indication(view))
8645 wstandend(view->window);
8646 free(wline);
8647 wline = NULL;
8648 free(line);
8649 line = NULL;
8650 if (--limit <= 0)
8651 return NULL;
8653 n = 0;
8654 view->maxx = 0;
8655 while (re && limit > 0) {
8656 char *line = NULL;
8657 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8659 if (s->show_date) {
8660 struct got_commit_object *ci;
8661 struct got_tag_object *tag;
8662 struct got_object_id *id;
8663 struct tm tm;
8664 time_t t;
8666 err = got_ref_resolve(&id, s->repo, re->ref);
8667 if (err)
8668 return err;
8669 err = got_object_open_as_tag(&tag, s->repo, id);
8670 if (err) {
8671 if (err->code != GOT_ERR_OBJ_TYPE) {
8672 free(id);
8673 return err;
8675 err = got_object_open_as_commit(&ci, s->repo,
8676 id);
8677 if (err) {
8678 free(id);
8679 return err;
8681 t = got_object_commit_get_committer_time(ci);
8682 got_object_commit_close(ci);
8683 } else {
8684 t = got_object_tag_get_tagger_time(tag);
8685 got_object_tag_close(tag);
8687 free(id);
8688 if (gmtime_r(&t, &tm) == NULL)
8689 return got_error_from_errno("gmtime_r");
8690 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8691 return got_error(GOT_ERR_NO_SPACE);
8693 if (got_ref_is_symbolic(re->ref)) {
8694 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8695 ymd : "", got_ref_get_name(re->ref),
8696 got_ref_get_symref_target(re->ref)) == -1)
8697 return got_error_from_errno("asprintf");
8698 } else if (s->show_ids) {
8699 struct got_object_id *id;
8700 char *id_str;
8701 err = got_ref_resolve(&id, s->repo, re->ref);
8702 if (err)
8703 return err;
8704 err = got_object_id_str(&id_str, id);
8705 if (err) {
8706 free(id);
8707 return err;
8709 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8710 got_ref_get_name(re->ref), id_str) == -1) {
8711 err = got_error_from_errno("asprintf");
8712 free(id);
8713 free(id_str);
8714 return err;
8716 free(id);
8717 free(id_str);
8718 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8719 got_ref_get_name(re->ref)) == -1)
8720 return got_error_from_errno("asprintf");
8722 /* use full line width to determine view->maxx */
8723 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8724 if (err) {
8725 free(line);
8726 return err;
8728 view->maxx = MAX(view->maxx, width);
8729 free(wline);
8730 wline = NULL;
8732 err = format_line(&wline, &width, &scrollx, line, view->x,
8733 view->ncols, 0, 0);
8734 if (err) {
8735 free(line);
8736 return err;
8738 if (n == s->selected) {
8739 if (view->focussed)
8740 wstandout(view->window);
8741 s->selected_entry = re;
8743 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8744 if (tc)
8745 wattr_on(view->window,
8746 COLOR_PAIR(tc->colorpair), NULL);
8747 waddwstr(view->window, &wline[scrollx]);
8748 if (tc)
8749 wattr_off(view->window,
8750 COLOR_PAIR(tc->colorpair), NULL);
8751 if (width < view->ncols)
8752 waddch(view->window, '\n');
8753 if (n == s->selected && view->focussed)
8754 wstandend(view->window);
8755 free(line);
8756 free(wline);
8757 wline = NULL;
8758 n++;
8759 s->ndisplayed++;
8760 s->last_displayed_entry = re;
8762 limit--;
8763 re = TAILQ_NEXT(re, entry);
8766 view_border(view);
8767 return err;
8770 static const struct got_error *
8771 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8772 struct tog_reflist_entry *re, struct got_repository *repo)
8774 const struct got_error *err = NULL;
8775 struct got_object_id *commit_id = NULL;
8776 struct tog_view *tree_view;
8778 *new_view = NULL;
8780 err = resolve_reflist_entry(&commit_id, re, repo);
8781 if (err) {
8782 if (err->code != GOT_ERR_OBJ_TYPE)
8783 return err;
8784 else
8785 return NULL;
8789 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8790 if (tree_view == NULL) {
8791 err = got_error_from_errno("view_open");
8792 goto done;
8795 err = open_tree_view(tree_view, commit_id,
8796 got_ref_get_name(re->ref), repo);
8797 if (err)
8798 goto done;
8800 *new_view = tree_view;
8801 done:
8802 free(commit_id);
8803 return err;
8806 static const struct got_error *
8807 ref_goto_line(struct tog_view *view, int nlines)
8809 const struct got_error *err = NULL;
8810 struct tog_ref_view_state *s = &view->state.ref;
8811 int g, idx = s->selected_entry->idx;
8813 g = view->gline;
8814 view->gline = 0;
8816 if (g == 0)
8817 g = 1;
8818 else if (g > s->nrefs)
8819 g = s->nrefs;
8821 if (g >= s->first_displayed_entry->idx + 1 &&
8822 g <= s->last_displayed_entry->idx + 1 &&
8823 g - s->first_displayed_entry->idx - 1 < nlines) {
8824 s->selected = g - s->first_displayed_entry->idx - 1;
8825 return NULL;
8828 if (idx + 1 < g) {
8829 err = ref_scroll_down(view, g - idx - 1);
8830 if (err)
8831 return err;
8832 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8833 s->first_displayed_entry->idx + s->selected < g &&
8834 s->selected < s->ndisplayed - 1)
8835 s->selected = g - s->first_displayed_entry->idx - 1;
8836 } else if (idx + 1 > g)
8837 ref_scroll_up(s, idx - g + 1);
8839 if (g < nlines && s->first_displayed_entry->idx == 0)
8840 s->selected = g - 1;
8842 return NULL;
8846 static const struct got_error *
8847 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8849 const struct got_error *err = NULL;
8850 struct tog_ref_view_state *s = &view->state.ref;
8851 struct tog_reflist_entry *re;
8852 int n, nscroll = view->nlines - 1;
8854 if (view->gline)
8855 return ref_goto_line(view, nscroll);
8857 switch (ch) {
8858 case '0':
8859 case '$':
8860 case KEY_RIGHT:
8861 case 'l':
8862 case KEY_LEFT:
8863 case 'h':
8864 horizontal_scroll_input(view, ch);
8865 break;
8866 case 'i':
8867 s->show_ids = !s->show_ids;
8868 view->count = 0;
8869 break;
8870 case 'm':
8871 s->show_date = !s->show_date;
8872 view->count = 0;
8873 break;
8874 case 'o':
8875 s->sort_by_date = !s->sort_by_date;
8876 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8877 view->count = 0;
8878 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8879 got_ref_cmp_by_commit_timestamp_descending :
8880 tog_ref_cmp_by_name, s->repo);
8881 if (err)
8882 break;
8883 got_reflist_object_id_map_free(tog_refs_idmap);
8884 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8885 &tog_refs, s->repo);
8886 if (err)
8887 break;
8888 ref_view_free_refs(s);
8889 err = ref_view_load_refs(s);
8890 break;
8891 case KEY_ENTER:
8892 case '\r':
8893 view->count = 0;
8894 if (!s->selected_entry)
8895 break;
8896 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8897 break;
8898 case 'T':
8899 view->count = 0;
8900 if (!s->selected_entry)
8901 break;
8902 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8903 break;
8904 case 'g':
8905 case '=':
8906 case KEY_HOME:
8907 s->selected = 0;
8908 view->count = 0;
8909 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8910 break;
8911 case 'G':
8912 case '*':
8913 case KEY_END: {
8914 int eos = view->nlines - 1;
8916 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8917 --eos; /* border */
8918 s->selected = 0;
8919 view->count = 0;
8920 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8921 for (n = 0; n < eos; n++) {
8922 if (re == NULL)
8923 break;
8924 s->first_displayed_entry = re;
8925 re = TAILQ_PREV(re, tog_reflist_head, entry);
8927 if (n > 0)
8928 s->selected = n - 1;
8929 break;
8931 case 'k':
8932 case KEY_UP:
8933 case CTRL('p'):
8934 if (s->selected > 0) {
8935 s->selected--;
8936 break;
8938 ref_scroll_up(s, 1);
8939 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8940 view->count = 0;
8941 break;
8942 case CTRL('u'):
8943 case 'u':
8944 nscroll /= 2;
8945 /* FALL THROUGH */
8946 case KEY_PPAGE:
8947 case CTRL('b'):
8948 case 'b':
8949 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8950 s->selected -= MIN(nscroll, s->selected);
8951 ref_scroll_up(s, MAX(0, nscroll));
8952 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8953 view->count = 0;
8954 break;
8955 case 'j':
8956 case KEY_DOWN:
8957 case CTRL('n'):
8958 if (s->selected < s->ndisplayed - 1) {
8959 s->selected++;
8960 break;
8962 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8963 /* can't scroll any further */
8964 view->count = 0;
8965 break;
8967 ref_scroll_down(view, 1);
8968 break;
8969 case CTRL('d'):
8970 case 'd':
8971 nscroll /= 2;
8972 /* FALL THROUGH */
8973 case KEY_NPAGE:
8974 case CTRL('f'):
8975 case 'f':
8976 case ' ':
8977 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8978 /* can't scroll any further; move cursor down */
8979 if (s->selected < s->ndisplayed - 1)
8980 s->selected += MIN(nscroll,
8981 s->ndisplayed - s->selected - 1);
8982 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8983 s->selected += s->ndisplayed - s->selected - 1;
8984 view->count = 0;
8985 break;
8987 ref_scroll_down(view, nscroll);
8988 break;
8989 case CTRL('l'):
8990 view->count = 0;
8991 tog_free_refs();
8992 err = tog_load_refs(s->repo, s->sort_by_date);
8993 if (err)
8994 break;
8995 ref_view_free_refs(s);
8996 err = ref_view_load_refs(s);
8997 break;
8998 case KEY_RESIZE:
8999 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
9000 s->selected = view->nlines - 2;
9001 break;
9002 default:
9003 view->count = 0;
9004 break;
9007 return err;
9010 __dead static void
9011 usage_ref(void)
9013 endwin();
9014 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
9015 getprogname());
9016 exit(1);
9019 static const struct got_error *
9020 cmd_ref(int argc, char *argv[])
9022 const struct got_error *error;
9023 struct got_repository *repo = NULL;
9024 struct got_worktree *worktree = NULL;
9025 char *cwd = NULL, *repo_path = NULL;
9026 int ch;
9027 struct tog_view *view;
9028 int *pack_fds = NULL;
9030 while ((ch = getopt(argc, argv, "r:")) != -1) {
9031 switch (ch) {
9032 case 'r':
9033 repo_path = realpath(optarg, NULL);
9034 if (repo_path == NULL)
9035 return got_error_from_errno2("realpath",
9036 optarg);
9037 break;
9038 default:
9039 usage_ref();
9040 /* NOTREACHED */
9044 argc -= optind;
9045 argv += optind;
9047 if (argc > 1)
9048 usage_ref();
9050 error = got_repo_pack_fds_open(&pack_fds);
9051 if (error != NULL)
9052 goto done;
9054 if (repo_path == NULL) {
9055 cwd = getcwd(NULL, 0);
9056 if (cwd == NULL)
9057 return got_error_from_errno("getcwd");
9058 error = got_worktree_open(&worktree, cwd, NULL);
9059 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9060 goto done;
9061 if (worktree)
9062 repo_path =
9063 strdup(got_worktree_get_repo_path(worktree));
9064 else
9065 repo_path = strdup(cwd);
9066 if (repo_path == NULL) {
9067 error = got_error_from_errno("strdup");
9068 goto done;
9072 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9073 if (error != NULL)
9074 goto done;
9076 init_curses();
9078 error = apply_unveil(got_repo_get_path(repo), NULL);
9079 if (error)
9080 goto done;
9082 error = tog_load_refs(repo, 0);
9083 if (error)
9084 goto done;
9086 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
9087 if (view == NULL) {
9088 error = got_error_from_errno("view_open");
9089 goto done;
9092 error = open_ref_view(view, repo);
9093 if (error)
9094 goto done;
9096 if (worktree) {
9097 error = set_tog_base_commit(repo, worktree);
9098 if (error != NULL)
9099 goto done;
9101 /* Release work tree lock. */
9102 got_worktree_close(worktree);
9103 worktree = NULL;
9106 error = view_loop(view);
9108 done:
9109 free(tog_base_commit.id);
9110 free(repo_path);
9111 free(cwd);
9112 if (worktree != NULL)
9113 got_worktree_close(worktree);
9114 if (repo) {
9115 const struct got_error *close_err = got_repo_close(repo);
9116 if (close_err)
9117 error = close_err;
9119 if (pack_fds) {
9120 const struct got_error *pack_err =
9121 got_repo_pack_fds_close(pack_fds);
9122 if (error == NULL)
9123 error = pack_err;
9125 tog_free_refs();
9126 return error;
9129 static const struct got_error*
9130 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
9131 const char *str)
9133 size_t len;
9135 if (win == NULL)
9136 win = stdscr;
9138 len = strlen(str);
9139 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
9141 if (focus)
9142 wstandout(win);
9143 if (mvwprintw(win, y, x, "%s", str) == ERR)
9144 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
9145 if (focus)
9146 wstandend(win);
9148 return NULL;
9151 static const struct got_error *
9152 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
9154 off_t *p;
9156 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
9157 if (p == NULL) {
9158 free(*line_offsets);
9159 *line_offsets = NULL;
9160 return got_error_from_errno("reallocarray");
9163 *line_offsets = p;
9164 (*line_offsets)[*nlines] = off;
9165 ++(*nlines);
9166 return NULL;
9169 static const struct got_error *
9170 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
9172 *ret = 0;
9174 for (;n > 0; --n, ++km) {
9175 char *t0, *t, *k;
9176 size_t len = 1;
9178 if (km->keys == NULL)
9179 continue;
9181 t = t0 = strdup(km->keys);
9182 if (t0 == NULL)
9183 return got_error_from_errno("strdup");
9185 len += strlen(t);
9186 while ((k = strsep(&t, " ")) != NULL)
9187 len += strlen(k) > 1 ? 2 : 0;
9188 free(t0);
9189 *ret = MAX(*ret, len);
9192 return NULL;
9196 * Write keymap section headers, keys, and key info in km to f.
9197 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9198 * wrap control and symbolic keys in guillemets, else use <>.
9200 static const struct got_error *
9201 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9203 int n, len = width;
9205 if (km->keys) {
9206 static const char *u8_glyph[] = {
9207 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9208 "\xe2\x80\xba" /* U+203A (utf8 >) */
9210 char *t0, *t, *k;
9211 int cs, s, first = 1;
9213 cs = got_locale_is_utf8();
9215 t = t0 = strdup(km->keys);
9216 if (t0 == NULL)
9217 return got_error_from_errno("strdup");
9219 len = strlen(km->keys);
9220 while ((k = strsep(&t, " ")) != NULL) {
9221 s = strlen(k) > 1; /* control or symbolic key */
9222 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9223 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9224 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9225 if (n < 0) {
9226 free(t0);
9227 return got_error_from_errno("fprintf");
9229 first = 0;
9230 len += s ? 2 : 0;
9231 *off += n;
9233 free(t0);
9235 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9236 if (n < 0)
9237 return got_error_from_errno("fprintf");
9238 *off += n;
9240 return NULL;
9243 static const struct got_error *
9244 format_help(struct tog_help_view_state *s)
9246 const struct got_error *err = NULL;
9247 off_t off = 0;
9248 int i, max, n, show = s->all;
9249 static const struct tog_key_map km[] = {
9250 #define KEYMAP_(info, type) { NULL, (info), type }
9251 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9252 GENERATE_HELP
9253 #undef KEYMAP_
9254 #undef KEY_
9257 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9258 if (err)
9259 return err;
9261 n = nitems(km);
9262 err = max_key_str(&max, km, n);
9263 if (err)
9264 return err;
9266 for (i = 0; i < n; ++i) {
9267 if (km[i].keys == NULL) {
9268 show = s->all;
9269 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9270 km[i].type == s->type || s->all)
9271 show = 1;
9273 if (show) {
9274 err = format_help_line(&off, s->f, &km[i], max);
9275 if (err)
9276 return err;
9277 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9278 if (err)
9279 return err;
9282 fputc('\n', s->f);
9283 ++off;
9284 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9285 return err;
9288 static const struct got_error *
9289 create_help(struct tog_help_view_state *s)
9291 FILE *f;
9292 const struct got_error *err;
9294 free(s->line_offsets);
9295 s->line_offsets = NULL;
9296 s->nlines = 0;
9298 f = got_opentemp();
9299 if (f == NULL)
9300 return got_error_from_errno("got_opentemp");
9301 s->f = f;
9303 err = format_help(s);
9304 if (err)
9305 return err;
9307 if (s->f && fflush(s->f) != 0)
9308 return got_error_from_errno("fflush");
9310 return NULL;
9313 static const struct got_error *
9314 search_start_help_view(struct tog_view *view)
9316 view->state.help.matched_line = 0;
9317 return NULL;
9320 static void
9321 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9322 size_t *nlines, int **first, int **last, int **match, int **selected)
9324 struct tog_help_view_state *s = &view->state.help;
9326 *f = s->f;
9327 *nlines = s->nlines;
9328 *line_offsets = s->line_offsets;
9329 *match = &s->matched_line;
9330 *first = &s->first_displayed_line;
9331 *last = &s->last_displayed_line;
9332 *selected = &s->selected_line;
9335 static const struct got_error *
9336 show_help_view(struct tog_view *view)
9338 struct tog_help_view_state *s = &view->state.help;
9339 const struct got_error *err;
9340 regmatch_t *regmatch = &view->regmatch;
9341 wchar_t *wline;
9342 char *line;
9343 ssize_t linelen;
9344 size_t linesz = 0;
9345 int width, nprinted = 0, rc = 0;
9346 int eos = view->nlines;
9348 if (view_is_hsplit_top(view))
9349 --eos; /* account for border */
9351 s->lineno = 0;
9352 rewind(s->f);
9353 werase(view->window);
9355 if (view->gline > s->nlines - 1)
9356 view->gline = s->nlines - 1;
9358 err = win_draw_center(view->window, 0, 0, view->ncols,
9359 view_needs_focus_indication(view),
9360 "tog help (press q to return to tog)");
9361 if (err)
9362 return err;
9363 if (eos <= 1)
9364 return NULL;
9365 waddstr(view->window, "\n\n");
9366 eos -= 2;
9368 s->eof = 0;
9369 view->maxx = 0;
9370 line = NULL;
9371 while (eos > 0 && nprinted < eos) {
9372 attr_t attr = 0;
9374 linelen = getline(&line, &linesz, s->f);
9375 if (linelen == -1) {
9376 if (!feof(s->f)) {
9377 free(line);
9378 return got_ferror(s->f, GOT_ERR_IO);
9380 s->eof = 1;
9381 break;
9383 if (++s->lineno < s->first_displayed_line)
9384 continue;
9385 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9386 continue;
9387 if (s->lineno == view->hiline)
9388 attr = A_STANDOUT;
9390 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9391 view->x ? 1 : 0);
9392 if (err) {
9393 free(line);
9394 return err;
9396 view->maxx = MAX(view->maxx, width);
9397 free(wline);
9398 wline = NULL;
9400 if (attr)
9401 wattron(view->window, attr);
9402 if (s->first_displayed_line + nprinted == s->matched_line &&
9403 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9404 err = add_matched_line(&width, line, view->ncols - 1, 0,
9405 view->window, view->x, regmatch);
9406 if (err) {
9407 free(line);
9408 return err;
9410 } else {
9411 int skip;
9413 err = format_line(&wline, &width, &skip, line,
9414 view->x, view->ncols, 0, view->x ? 1 : 0);
9415 if (err) {
9416 free(line);
9417 return err;
9419 waddwstr(view->window, &wline[skip]);
9420 free(wline);
9421 wline = NULL;
9423 if (s->lineno == view->hiline) {
9424 while (width++ < view->ncols)
9425 waddch(view->window, ' ');
9426 } else {
9427 if (width < view->ncols)
9428 waddch(view->window, '\n');
9430 if (attr)
9431 wattroff(view->window, attr);
9432 if (++nprinted == 1)
9433 s->first_displayed_line = s->lineno;
9435 free(line);
9436 if (nprinted > 0)
9437 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9438 else
9439 s->last_displayed_line = s->first_displayed_line;
9441 view_border(view);
9443 if (s->eof) {
9444 rc = waddnstr(view->window,
9445 "See the tog(1) manual page for full documentation",
9446 view->ncols - 1);
9447 if (rc == ERR)
9448 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9449 } else {
9450 wmove(view->window, view->nlines - 1, 0);
9451 wclrtoeol(view->window);
9452 wstandout(view->window);
9453 rc = waddnstr(view->window, "scroll down for more...",
9454 view->ncols - 1);
9455 if (rc == ERR)
9456 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9457 if (getcurx(view->window) < view->ncols - 6) {
9458 rc = wprintw(view->window, "[%.0f%%]",
9459 100.00 * s->last_displayed_line / s->nlines);
9460 if (rc == ERR)
9461 return got_error_msg(GOT_ERR_IO, "wprintw");
9463 wstandend(view->window);
9466 return NULL;
9469 static const struct got_error *
9470 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9472 struct tog_help_view_state *s = &view->state.help;
9473 const struct got_error *err = NULL;
9474 char *line = NULL;
9475 ssize_t linelen;
9476 size_t linesz = 0;
9477 int eos, nscroll;
9479 eos = nscroll = view->nlines;
9480 if (view_is_hsplit_top(view))
9481 --eos; /* border */
9483 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9485 switch (ch) {
9486 case '0':
9487 case '$':
9488 case KEY_RIGHT:
9489 case 'l':
9490 case KEY_LEFT:
9491 case 'h':
9492 horizontal_scroll_input(view, ch);
9493 break;
9494 case 'g':
9495 case KEY_HOME:
9496 s->first_displayed_line = 1;
9497 view->count = 0;
9498 break;
9499 case 'G':
9500 case KEY_END:
9501 view->count = 0;
9502 if (s->eof)
9503 break;
9504 s->first_displayed_line = (s->nlines - eos) + 3;
9505 s->eof = 1;
9506 break;
9507 case 'k':
9508 case KEY_UP:
9509 if (s->first_displayed_line > 1)
9510 --s->first_displayed_line;
9511 else
9512 view->count = 0;
9513 break;
9514 case CTRL('u'):
9515 case 'u':
9516 nscroll /= 2;
9517 /* FALL THROUGH */
9518 case KEY_PPAGE:
9519 case CTRL('b'):
9520 case 'b':
9521 if (s->first_displayed_line == 1) {
9522 view->count = 0;
9523 break;
9525 while (--nscroll > 0 && s->first_displayed_line > 1)
9526 s->first_displayed_line--;
9527 break;
9528 case 'j':
9529 case KEY_DOWN:
9530 case CTRL('n'):
9531 if (!s->eof)
9532 ++s->first_displayed_line;
9533 else
9534 view->count = 0;
9535 break;
9536 case CTRL('d'):
9537 case 'd':
9538 nscroll /= 2;
9539 /* FALL THROUGH */
9540 case KEY_NPAGE:
9541 case CTRL('f'):
9542 case 'f':
9543 case ' ':
9544 if (s->eof) {
9545 view->count = 0;
9546 break;
9548 while (!s->eof && --nscroll > 0) {
9549 linelen = getline(&line, &linesz, s->f);
9550 s->first_displayed_line++;
9551 if (linelen == -1) {
9552 if (feof(s->f))
9553 s->eof = 1;
9554 else
9555 err = got_ferror(s->f, GOT_ERR_IO);
9556 break;
9559 free(line);
9560 break;
9561 default:
9562 view->count = 0;
9563 break;
9566 return err;
9569 static const struct got_error *
9570 close_help_view(struct tog_view *view)
9572 struct tog_help_view_state *s = &view->state.help;
9574 free(s->line_offsets);
9575 s->line_offsets = NULL;
9576 if (fclose(s->f) == EOF)
9577 return got_error_from_errno("fclose");
9579 return NULL;
9582 static const struct got_error *
9583 reset_help_view(struct tog_view *view)
9585 struct tog_help_view_state *s = &view->state.help;
9588 if (s->f && fclose(s->f) == EOF)
9589 return got_error_from_errno("fclose");
9591 wclear(view->window);
9592 view->count = 0;
9593 view->x = 0;
9594 s->all = !s->all;
9595 s->first_displayed_line = 1;
9596 s->last_displayed_line = view->nlines;
9597 s->matched_line = 0;
9599 return create_help(s);
9602 static const struct got_error *
9603 open_help_view(struct tog_view *view, struct tog_view *parent)
9605 const struct got_error *err = NULL;
9606 struct tog_help_view_state *s = &view->state.help;
9608 s->type = (enum tog_keymap_type)parent->type;
9609 s->first_displayed_line = 1;
9610 s->last_displayed_line = view->nlines;
9611 s->selected_line = 1;
9613 view->show = show_help_view;
9614 view->input = input_help_view;
9615 view->reset = reset_help_view;
9616 view->close = close_help_view;
9617 view->search_start = search_start_help_view;
9618 view->search_setup = search_setup_help_view;
9619 view->search_next = search_next_view_match;
9621 err = create_help(s);
9622 return err;
9625 static const struct got_error *
9626 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9627 enum tog_view_type request, int y, int x)
9629 const struct got_error *err = NULL;
9631 *new_view = NULL;
9633 switch (request) {
9634 case TOG_VIEW_DIFF:
9635 if (view->type == TOG_VIEW_LOG) {
9636 struct tog_log_view_state *s = &view->state.log;
9638 err = open_diff_view_for_commit(new_view, y, x,
9639 s->selected_entry->commit, s->selected_entry->id,
9640 view, s->repo);
9641 } else
9642 return got_error_msg(GOT_ERR_NOT_IMPL,
9643 "parent/child view pair not supported");
9644 break;
9645 case TOG_VIEW_BLAME:
9646 if (view->type == TOG_VIEW_TREE) {
9647 struct tog_tree_view_state *s = &view->state.tree;
9649 err = blame_tree_entry(new_view, y, x,
9650 s->selected_entry, &s->parents, s->commit_id,
9651 s->repo);
9652 } else
9653 return got_error_msg(GOT_ERR_NOT_IMPL,
9654 "parent/child view pair not supported");
9655 break;
9656 case TOG_VIEW_LOG:
9657 if (view->type == TOG_VIEW_BLAME)
9658 err = log_annotated_line(new_view, y, x,
9659 view->state.blame.repo, view->state.blame.id_to_log);
9660 else if (view->type == TOG_VIEW_TREE)
9661 err = log_selected_tree_entry(new_view, y, x,
9662 &view->state.tree);
9663 else if (view->type == TOG_VIEW_REF)
9664 err = log_ref_entry(new_view, y, x,
9665 view->state.ref.selected_entry,
9666 view->state.ref.repo);
9667 else
9668 return got_error_msg(GOT_ERR_NOT_IMPL,
9669 "parent/child view pair not supported");
9670 break;
9671 case TOG_VIEW_TREE:
9672 if (view->type == TOG_VIEW_LOG)
9673 err = browse_commit_tree(new_view, y, x,
9674 view->state.log.selected_entry,
9675 view->state.log.in_repo_path,
9676 view->state.log.head_ref_name,
9677 view->state.log.repo);
9678 else if (view->type == TOG_VIEW_REF)
9679 err = browse_ref_tree(new_view, y, x,
9680 view->state.ref.selected_entry,
9681 view->state.ref.repo);
9682 else
9683 return got_error_msg(GOT_ERR_NOT_IMPL,
9684 "parent/child view pair not supported");
9685 break;
9686 case TOG_VIEW_REF:
9687 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9688 if (*new_view == NULL)
9689 return got_error_from_errno("view_open");
9690 if (view->type == TOG_VIEW_LOG)
9691 err = open_ref_view(*new_view, view->state.log.repo);
9692 else if (view->type == TOG_VIEW_TREE)
9693 err = open_ref_view(*new_view, view->state.tree.repo);
9694 else
9695 err = got_error_msg(GOT_ERR_NOT_IMPL,
9696 "parent/child view pair not supported");
9697 if (err)
9698 view_close(*new_view);
9699 break;
9700 case TOG_VIEW_HELP:
9701 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9702 if (*new_view == NULL)
9703 return got_error_from_errno("view_open");
9704 err = open_help_view(*new_view, view);
9705 if (err)
9706 view_close(*new_view);
9707 break;
9708 default:
9709 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9712 return err;
9716 * If view was scrolled down to move the selected line into view when opening a
9717 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9719 static void
9720 offset_selection_up(struct tog_view *view)
9722 switch (view->type) {
9723 case TOG_VIEW_BLAME: {
9724 struct tog_blame_view_state *s = &view->state.blame;
9725 if (s->first_displayed_line == 1) {
9726 s->selected_line = MAX(s->selected_line - view->offset,
9727 1);
9728 break;
9730 if (s->first_displayed_line > view->offset)
9731 s->first_displayed_line -= view->offset;
9732 else
9733 s->first_displayed_line = 1;
9734 s->selected_line += view->offset;
9735 break;
9737 case TOG_VIEW_LOG:
9738 log_scroll_up(&view->state.log, view->offset);
9739 view->state.log.selected += view->offset;
9740 break;
9741 case TOG_VIEW_REF:
9742 ref_scroll_up(&view->state.ref, view->offset);
9743 view->state.ref.selected += view->offset;
9744 break;
9745 case TOG_VIEW_TREE:
9746 tree_scroll_up(&view->state.tree, view->offset);
9747 view->state.tree.selected += view->offset;
9748 break;
9749 default:
9750 break;
9753 view->offset = 0;
9757 * If the selected line is in the section of screen covered by the bottom split,
9758 * scroll down offset lines to move it into view and index its new position.
9760 static const struct got_error *
9761 offset_selection_down(struct tog_view *view)
9763 const struct got_error *err = NULL;
9764 const struct got_error *(*scrolld)(struct tog_view *, int);
9765 int *selected = NULL;
9766 int header, offset;
9768 switch (view->type) {
9769 case TOG_VIEW_BLAME: {
9770 struct tog_blame_view_state *s = &view->state.blame;
9771 header = 3;
9772 scrolld = NULL;
9773 if (s->selected_line > view->nlines - header) {
9774 offset = abs(view->nlines - s->selected_line - header);
9775 s->first_displayed_line += offset;
9776 s->selected_line -= offset;
9777 view->offset = offset;
9779 break;
9781 case TOG_VIEW_LOG: {
9782 struct tog_log_view_state *s = &view->state.log;
9783 scrolld = &log_scroll_down;
9784 header = view_is_parent_view(view) ? 3 : 2;
9785 selected = &s->selected;
9786 break;
9788 case TOG_VIEW_REF: {
9789 struct tog_ref_view_state *s = &view->state.ref;
9790 scrolld = &ref_scroll_down;
9791 header = 3;
9792 selected = &s->selected;
9793 break;
9795 case TOG_VIEW_TREE: {
9796 struct tog_tree_view_state *s = &view->state.tree;
9797 scrolld = &tree_scroll_down;
9798 header = 5;
9799 selected = &s->selected;
9800 break;
9802 default:
9803 selected = NULL;
9804 scrolld = NULL;
9805 header = 0;
9806 break;
9809 if (selected && *selected > view->nlines - header) {
9810 offset = abs(view->nlines - *selected - header);
9811 view->offset = offset;
9812 if (scrolld && offset) {
9813 err = scrolld(view, offset);
9814 *selected -= offset;
9818 return err;
9821 static void
9822 list_commands(FILE *fp)
9824 size_t i;
9826 fprintf(fp, "commands:");
9827 for (i = 0; i < nitems(tog_commands); i++) {
9828 const struct tog_cmd *cmd = &tog_commands[i];
9829 fprintf(fp, " %s", cmd->name);
9831 fputc('\n', fp);
9834 __dead static void
9835 usage(int hflag, int status)
9837 FILE *fp = (status == 0) ? stdout : stderr;
9839 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9840 getprogname());
9841 if (hflag) {
9842 fprintf(fp, "lazy usage: %s path\n", getprogname());
9843 list_commands(fp);
9845 exit(status);
9848 static char **
9849 make_argv(int argc, ...)
9851 va_list ap;
9852 char **argv;
9853 int i;
9855 va_start(ap, argc);
9857 argv = calloc(argc, sizeof(char *));
9858 if (argv == NULL)
9859 err(1, "calloc");
9860 for (i = 0; i < argc; i++) {
9861 argv[i] = strdup(va_arg(ap, char *));
9862 if (argv[i] == NULL)
9863 err(1, "strdup");
9866 va_end(ap);
9867 return argv;
9871 * Try to convert 'tog path' into a 'tog log path' command.
9872 * The user could simply have mistyped the command rather than knowingly
9873 * provided a path. So check whether argv[0] can in fact be resolved
9874 * to a path in the HEAD commit and print a special error if not.
9875 * This hack is for mpi@ <3
9877 static const struct got_error *
9878 tog_log_with_path(int argc, char *argv[])
9880 const struct got_error *error = NULL, *close_err;
9881 const struct tog_cmd *cmd = NULL;
9882 struct got_repository *repo = NULL;
9883 struct got_worktree *worktree = NULL;
9884 struct got_object_id *commit_id = NULL, *id = NULL;
9885 struct got_commit_object *commit = NULL;
9886 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9887 char *commit_id_str = NULL, **cmd_argv = NULL;
9888 int *pack_fds = NULL;
9890 cwd = getcwd(NULL, 0);
9891 if (cwd == NULL)
9892 return got_error_from_errno("getcwd");
9894 error = got_repo_pack_fds_open(&pack_fds);
9895 if (error != NULL)
9896 goto done;
9898 error = got_worktree_open(&worktree, cwd, NULL);
9899 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9900 goto done;
9902 if (worktree)
9903 repo_path = strdup(got_worktree_get_repo_path(worktree));
9904 else
9905 repo_path = strdup(cwd);
9906 if (repo_path == NULL) {
9907 error = got_error_from_errno("strdup");
9908 goto done;
9911 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9912 if (error != NULL)
9913 goto done;
9915 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9916 repo, worktree);
9917 if (error)
9918 goto done;
9920 error = tog_load_refs(repo, 0);
9921 if (error)
9922 goto done;
9923 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9924 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9925 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9926 if (error)
9927 goto done;
9929 if (worktree) {
9930 got_worktree_close(worktree);
9931 worktree = NULL;
9934 error = got_object_open_as_commit(&commit, repo, commit_id);
9935 if (error)
9936 goto done;
9938 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9939 if (error) {
9940 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9941 goto done;
9942 fprintf(stderr, "%s: '%s' is no known command or path\n",
9943 getprogname(), argv[0]);
9944 usage(1, 1);
9945 /* not reached */
9948 error = got_object_id_str(&commit_id_str, commit_id);
9949 if (error)
9950 goto done;
9952 cmd = &tog_commands[0]; /* log */
9953 argc = 4;
9954 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9955 error = cmd->cmd_main(argc, cmd_argv);
9956 done:
9957 if (repo) {
9958 close_err = got_repo_close(repo);
9959 if (error == NULL)
9960 error = close_err;
9962 if (commit)
9963 got_object_commit_close(commit);
9964 if (worktree)
9965 got_worktree_close(worktree);
9966 if (pack_fds) {
9967 const struct got_error *pack_err =
9968 got_repo_pack_fds_close(pack_fds);
9969 if (error == NULL)
9970 error = pack_err;
9972 free(id);
9973 free(commit_id_str);
9974 free(commit_id);
9975 free(cwd);
9976 free(repo_path);
9977 free(in_repo_path);
9978 if (cmd_argv) {
9979 int i;
9980 for (i = 0; i < argc; i++)
9981 free(cmd_argv[i]);
9982 free(cmd_argv);
9984 tog_free_refs();
9985 return error;
9988 int
9989 main(int argc, char *argv[])
9991 const struct got_error *io_err, *error = NULL;
9992 const struct tog_cmd *cmd = NULL;
9993 int ch, hflag = 0, Vflag = 0;
9994 char **cmd_argv = NULL;
9995 static const struct option longopts[] = {
9996 { "version", no_argument, NULL, 'V' },
9997 { NULL, 0, NULL, 0}
9999 char *diff_algo_str = NULL;
10000 const char *test_script_path;
10002 setlocale(LC_CTYPE, "");
10005 * Test mode init must happen before pledge() because "tty" will
10006 * not allow TTY-related ioctls to occur via regular files.
10008 test_script_path = getenv("TOG_TEST_SCRIPT");
10009 if (test_script_path != NULL) {
10010 error = init_mock_term(test_script_path);
10011 if (error) {
10012 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10013 return 1;
10015 } else if (!isatty(STDIN_FILENO))
10016 errx(1, "standard input is not a tty");
10018 #if !defined(PROFILE)
10019 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
10020 NULL) == -1)
10021 err(1, "pledge");
10022 #endif
10024 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
10025 switch (ch) {
10026 case 'h':
10027 hflag = 1;
10028 break;
10029 case 'V':
10030 Vflag = 1;
10031 break;
10032 default:
10033 usage(hflag, 1);
10034 /* NOTREACHED */
10038 argc -= optind;
10039 argv += optind;
10040 optind = 1;
10041 optreset = 1;
10043 if (Vflag) {
10044 got_version_print_str();
10045 return 0;
10048 if (argc == 0) {
10049 if (hflag)
10050 usage(hflag, 0);
10051 /* Build an argument vector which runs a default command. */
10052 cmd = &tog_commands[0];
10053 argc = 1;
10054 cmd_argv = make_argv(argc, cmd->name);
10055 } else {
10056 size_t i;
10058 /* Did the user specify a command? */
10059 for (i = 0; i < nitems(tog_commands); i++) {
10060 if (strncmp(tog_commands[i].name, argv[0],
10061 strlen(argv[0])) == 0) {
10062 cmd = &tog_commands[i];
10063 break;
10068 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
10069 if (diff_algo_str) {
10070 if (strcasecmp(diff_algo_str, "patience") == 0)
10071 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
10072 if (strcasecmp(diff_algo_str, "myers") == 0)
10073 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
10076 if (cmd == NULL) {
10077 if (argc != 1)
10078 usage(0, 1);
10079 /* No command specified; try log with a path */
10080 error = tog_log_with_path(argc, argv);
10081 } else {
10082 if (hflag)
10083 cmd->cmd_usage();
10084 else
10085 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
10088 if (using_mock_io) {
10089 io_err = tog_io_close();
10090 if (error == NULL)
10091 error = io_err;
10093 endwin();
10094 if (cmd_argv) {
10095 int i;
10096 for (i = 0; i < argc; i++)
10097 free(cmd_argv[i]);
10098 free(cmd_argv);
10101 if (error && error->code != GOT_ERR_CANCELLED &&
10102 error->code != GOT_ERR_EOF &&
10103 error->code != GOT_ERR_PRIVSEP_EXIT &&
10104 error->code != GOT_ERR_PRIVSEP_PIPE &&
10105 !(error->code == GOT_ERR_ERRNO && errno == EINTR)) {
10106 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10107 return 1;
10109 return 0;