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 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2489 if (tc)
2490 wattr_on(view->window,
2491 COLOR_PAIR(tc->colorpair), NULL);
2492 waddch(view->window, tog_base_commit.marker);
2493 if (tc)
2494 wattr_off(view->window,
2495 COLOR_PAIR(tc->colorpair), NULL);
2496 } else
2497 waddch(view->window, ' ');
2498 col++;
2499 author_width++;
2501 if (tc)
2502 wattr_off(view->window,
2503 COLOR_PAIR(tc->colorpair), NULL);
2504 if (col > avail)
2505 goto done;
2507 err = got_object_commit_get_logmsg(&logmsg0, commit);
2508 if (err)
2509 goto done;
2510 logmsg = logmsg0;
2511 while (*logmsg == '\n')
2512 logmsg++;
2513 newline = strchr(logmsg, '\n');
2514 if (newline)
2515 *newline = '\0';
2517 limit = avail - col;
2518 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2519 limit--; /* for the border */
2521 /* Prepend reference labels to log message if possible .*/
2522 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, id);
2523 err = build_refs_str(&refs_str, refs, id, s->repo);
2524 if (err)
2525 goto done;
2526 if (refs_str) {
2527 char *rs;
2529 if (asprintf(&rs, "[%s]", refs_str) == -1) {
2530 err = got_error_from_errno("asprintf");
2531 goto done;
2533 err = format_line(&wrefstr, &refstr_width,
2534 &scrollx, rs, view->x, limit, col, 1);
2535 free(rs);
2536 if (err)
2537 goto done;
2538 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2539 if (tc)
2540 wattr_on(view->window,
2541 COLOR_PAIR(tc->colorpair), NULL);
2542 waddwstr(view->window, &wrefstr[scrollx]);
2543 if (tc)
2544 wattr_off(view->window,
2545 COLOR_PAIR(tc->colorpair), NULL);
2546 col += MAX(refstr_width, 0);
2547 if (col > avail)
2548 goto done;
2550 if (col < avail) {
2551 waddch(view->window, ' ');
2552 col++;
2555 if (refstr_width > 0)
2556 logmsg_x = 0;
2557 else {
2558 int unscrolled_refstr_width;
2559 size_t len = wcslen(wrefstr);
2562 * No need to check for -1 return value here since
2563 * unprintables have been replaced by span_wline().
2565 unscrolled_refstr_width = wcswidth(wrefstr, len);
2566 unscrolled_refstr_width += 1; /* trailing space */
2567 logmsg_x = view->x - unscrolled_refstr_width;
2570 limit = avail - col;
2571 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2572 limit--; /* for the border */
2573 } else
2574 logmsg_x = view->x;
2576 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, logmsg_x,
2577 limit, col, 1);
2578 if (err)
2579 goto done;
2580 waddwstr(view->window, &wlogmsg[scrollx]);
2581 col += MAX(logmsg_width, 0);
2582 while (col < avail) {
2583 waddch(view->window, ' ');
2584 col++;
2586 done:
2587 free(logmsg0);
2588 free(wlogmsg);
2589 free(wrefstr);
2590 free(refs_str);
2591 free(author);
2592 free(wauthor);
2593 free(line);
2594 return err;
2597 static struct commit_queue_entry *
2598 alloc_commit_queue_entry(struct got_commit_object *commit,
2599 struct got_object_id *id)
2601 struct commit_queue_entry *entry;
2602 struct got_object_id *dup;
2604 entry = calloc(1, sizeof(*entry));
2605 if (entry == NULL)
2606 return NULL;
2608 dup = got_object_id_dup(id);
2609 if (dup == NULL) {
2610 free(entry);
2611 return NULL;
2614 entry->id = dup;
2615 entry->commit = commit;
2616 return entry;
2619 static void
2620 pop_commit(struct commit_queue *commits)
2622 struct commit_queue_entry *entry;
2624 entry = TAILQ_FIRST(&commits->head);
2625 TAILQ_REMOVE(&commits->head, entry, entry);
2626 got_object_commit_close(entry->commit);
2627 commits->ncommits--;
2628 free(entry->id);
2629 free(entry);
2632 static void
2633 free_commits(struct commit_queue *commits)
2635 while (!TAILQ_EMPTY(&commits->head))
2636 pop_commit(commits);
2639 static const struct got_error *
2640 match_commit(int *have_match, struct got_object_id *id,
2641 struct got_commit_object *commit, regex_t *regex)
2643 const struct got_error *err = NULL;
2644 regmatch_t regmatch;
2645 char *id_str = NULL, *logmsg = NULL;
2647 *have_match = 0;
2649 err = got_object_id_str(&id_str, id);
2650 if (err)
2651 return err;
2653 err = got_object_commit_get_logmsg(&logmsg, commit);
2654 if (err)
2655 goto done;
2657 if (regexec(regex, got_object_commit_get_author(commit), 1,
2658 &regmatch, 0) == 0 ||
2659 regexec(regex, got_object_commit_get_committer(commit), 1,
2660 &regmatch, 0) == 0 ||
2661 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2662 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2663 *have_match = 1;
2664 done:
2665 free(id_str);
2666 free(logmsg);
2667 return err;
2670 static const struct got_error *
2671 queue_commits(struct tog_log_thread_args *a)
2673 const struct got_error *err = NULL;
2676 * We keep all commits open throughout the lifetime of the log
2677 * view in order to avoid having to re-fetch commits from disk
2678 * while updating the display.
2680 do {
2681 struct got_object_id id;
2682 struct got_commit_object *commit;
2683 struct commit_queue_entry *entry;
2684 int limit_match = 0;
2685 int errcode;
2687 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2688 NULL, NULL);
2689 if (err)
2690 break;
2692 err = got_object_open_as_commit(&commit, a->repo, &id);
2693 if (err)
2694 break;
2695 entry = alloc_commit_queue_entry(commit, &id);
2696 if (entry == NULL) {
2697 err = got_error_from_errno("alloc_commit_queue_entry");
2698 break;
2701 errcode = pthread_mutex_lock(&tog_mutex);
2702 if (errcode) {
2703 err = got_error_set_errno(errcode,
2704 "pthread_mutex_lock");
2705 break;
2708 entry->idx = a->real_commits->ncommits;
2709 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2710 a->real_commits->ncommits++;
2712 if (tog_base_commit.id != NULL && tog_base_commit.idx == -1 &&
2713 got_object_id_cmp(&id, tog_base_commit.id) == 0)
2714 tog_base_commit.idx = entry->idx;
2716 if (*a->limiting) {
2717 err = match_commit(&limit_match, &id, commit,
2718 a->limit_regex);
2719 if (err)
2720 break;
2722 if (limit_match) {
2723 struct commit_queue_entry *matched;
2725 matched = alloc_commit_queue_entry(
2726 entry->commit, entry->id);
2727 if (matched == NULL) {
2728 err = got_error_from_errno(
2729 "alloc_commit_queue_entry");
2730 break;
2732 matched->commit = entry->commit;
2733 got_object_commit_retain(entry->commit);
2735 matched->idx = a->limit_commits->ncommits;
2736 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2737 matched, entry);
2738 a->limit_commits->ncommits++;
2742 * This is how we signal log_thread() that we
2743 * have found a match, and that it should be
2744 * counted as a new entry for the view.
2746 a->limit_match = limit_match;
2749 if (*a->searching == TOG_SEARCH_FORWARD &&
2750 !*a->search_next_done) {
2751 int have_match;
2752 err = match_commit(&have_match, &id, commit, a->regex);
2753 if (err)
2754 break;
2756 if (*a->limiting) {
2757 if (limit_match && have_match)
2758 *a->search_next_done =
2759 TOG_SEARCH_HAVE_MORE;
2760 } else if (have_match)
2761 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2764 errcode = pthread_mutex_unlock(&tog_mutex);
2765 if (errcode && err == NULL)
2766 err = got_error_set_errno(errcode,
2767 "pthread_mutex_unlock");
2768 if (err)
2769 break;
2770 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2772 return err;
2775 static void
2776 select_commit(struct tog_log_view_state *s)
2778 struct commit_queue_entry *entry;
2779 int ncommits = 0;
2781 entry = s->first_displayed_entry;
2782 while (entry) {
2783 if (ncommits == s->selected) {
2784 s->selected_entry = entry;
2785 break;
2787 entry = TAILQ_NEXT(entry, entry);
2788 ncommits++;
2792 static const struct got_error *
2793 draw_commits(struct tog_view *view)
2795 const struct got_error *err = NULL;
2796 struct tog_log_view_state *s = &view->state.log;
2797 struct commit_queue_entry *entry = s->selected_entry;
2798 int limit = view->nlines;
2799 int width;
2800 int ncommits, author_cols = 4, refstr_cols;
2801 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2802 char *refs_str = NULL;
2803 wchar_t *wline;
2804 struct tog_color *tc;
2805 static const size_t date_display_cols = 12;
2806 struct got_reflist_head *refs;
2808 if (view_is_hsplit_top(view))
2809 --limit; /* account for border */
2811 if (s->selected_entry &&
2812 !(view->searching && view->search_next_done == 0)) {
2813 err = got_object_id_str(&id_str, s->selected_entry->id);
2814 if (err)
2815 return err;
2816 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2817 s->selected_entry->id);
2818 err = build_refs_str(&refs_str, refs, s->selected_entry->id,
2819 s->repo);
2820 if (err)
2821 goto done;
2824 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2825 halfdelay(10); /* disable fast refresh */
2827 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2828 if (asprintf(&ncommits_str, " [%d/%d] %s",
2829 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2830 (view->searching && !view->search_next_done) ?
2831 "searching..." : "loading...") == -1) {
2832 err = got_error_from_errno("asprintf");
2833 goto done;
2835 } else {
2836 const char *search_str = NULL;
2837 const char *limit_str = NULL;
2839 if (view->searching) {
2840 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2841 search_str = "no more matches";
2842 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2843 search_str = "no matches found";
2844 else if (!view->search_next_done)
2845 search_str = "searching...";
2848 if (s->limit_view && s->commits->ncommits == 0)
2849 limit_str = "no matches found";
2851 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2852 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2853 search_str ? search_str : (refs_str ? refs_str : ""),
2854 limit_str ? limit_str : "") == -1) {
2855 err = got_error_from_errno("asprintf");
2856 goto done;
2860 free(refs_str);
2861 refs_str = NULL;
2863 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2864 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2865 "........................................",
2866 s->in_repo_path, ncommits_str) == -1) {
2867 err = got_error_from_errno("asprintf");
2868 header = NULL;
2869 goto done;
2871 } else if (asprintf(&header, "commit %s%s",
2872 id_str ? id_str : "........................................",
2873 ncommits_str) == -1) {
2874 err = got_error_from_errno("asprintf");
2875 header = NULL;
2876 goto done;
2878 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2879 if (err)
2880 goto done;
2882 werase(view->window);
2884 if (view_needs_focus_indication(view))
2885 wstandout(view->window);
2886 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2887 if (tc)
2888 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2889 waddwstr(view->window, wline);
2890 while (width < view->ncols) {
2891 waddch(view->window, ' ');
2892 width++;
2894 if (tc)
2895 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2896 if (view_needs_focus_indication(view))
2897 wstandend(view->window);
2898 free(wline);
2899 if (limit <= 1)
2900 goto done;
2902 /* Grow author column size if necessary, and set view->maxx. */
2903 entry = s->first_displayed_entry;
2904 ncommits = 0;
2905 view->maxx = 0;
2906 while (entry) {
2907 struct got_commit_object *c = entry->commit;
2908 char *author, *eol, *msg, *msg0;
2909 wchar_t *wauthor, *wmsg;
2910 int width;
2911 if (ncommits >= limit - 1)
2912 break;
2913 if (s->use_committer)
2914 author = strdup(got_object_commit_get_committer(c));
2915 else
2916 author = strdup(got_object_commit_get_author(c));
2917 if (author == NULL) {
2918 err = got_error_from_errno("strdup");
2919 goto done;
2921 err = format_author(&wauthor, &width, author, COLS,
2922 date_display_cols);
2923 if (author_cols < width)
2924 author_cols = width;
2925 free(wauthor);
2926 free(author);
2927 if (err)
2928 goto done;
2929 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2930 entry->id);
2931 err = build_refs_str(&refs_str, refs, entry->id, s->repo);
2932 if (err)
2933 goto done;
2934 if (refs_str) {
2935 wchar_t *ws;
2936 err = format_line(&ws, &width, NULL, refs_str,
2937 0, INT_MAX, date_display_cols + author_cols, 0);
2938 free(ws);
2939 free(refs_str);
2940 refs_str = NULL;
2941 if (err)
2942 goto done;
2943 refstr_cols = width + 3; /* account for [ ] + space */
2944 } else
2945 refstr_cols = 0;
2946 err = got_object_commit_get_logmsg(&msg0, c);
2947 if (err)
2948 goto done;
2949 msg = msg0;
2950 while (*msg == '\n')
2951 ++msg;
2952 if ((eol = strchr(msg, '\n')))
2953 *eol = '\0';
2954 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2955 date_display_cols + author_cols + refstr_cols, 0);
2956 if (err)
2957 goto done;
2958 view->maxx = MAX(view->maxx, width + refstr_cols);
2959 free(msg0);
2960 free(wmsg);
2961 ncommits++;
2962 entry = TAILQ_NEXT(entry, entry);
2965 entry = s->first_displayed_entry;
2966 s->last_displayed_entry = s->first_displayed_entry;
2967 ncommits = 0;
2968 while (entry) {
2969 if (ncommits >= limit - 1)
2970 break;
2971 if (ncommits == s->selected)
2972 wstandout(view->window);
2973 err = draw_commit(view, entry, date_display_cols, author_cols);
2974 if (ncommits == s->selected)
2975 wstandend(view->window);
2976 if (err)
2977 goto done;
2978 ncommits++;
2979 s->last_displayed_entry = entry;
2980 entry = TAILQ_NEXT(entry, entry);
2983 view_border(view);
2984 done:
2985 free(id_str);
2986 free(refs_str);
2987 free(ncommits_str);
2988 free(header);
2989 return err;
2992 static void
2993 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2995 struct commit_queue_entry *entry;
2996 int nscrolled = 0;
2998 entry = TAILQ_FIRST(&s->commits->head);
2999 if (s->first_displayed_entry == entry)
3000 return;
3002 entry = s->first_displayed_entry;
3003 while (entry && nscrolled < maxscroll) {
3004 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3005 if (entry) {
3006 s->first_displayed_entry = entry;
3007 nscrolled++;
3012 static const struct got_error *
3013 trigger_log_thread(struct tog_view *view, int wait)
3015 struct tog_log_thread_args *ta = &view->state.log.thread_args;
3016 int errcode;
3018 if (!using_mock_io)
3019 halfdelay(1); /* fast refresh while loading commits */
3021 while (!ta->log_complete && !tog_thread_error &&
3022 (ta->commits_needed > 0 || ta->load_all)) {
3023 /* Wake the log thread. */
3024 errcode = pthread_cond_signal(&ta->need_commits);
3025 if (errcode)
3026 return got_error_set_errno(errcode,
3027 "pthread_cond_signal");
3030 * The mutex will be released while the view loop waits
3031 * in wgetch(), at which time the log thread will run.
3033 if (!wait)
3034 break;
3036 /* Display progress update in log view. */
3037 show_log_view(view);
3038 update_panels();
3039 doupdate();
3041 /* Wait right here while next commit is being loaded. */
3042 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
3043 if (errcode)
3044 return got_error_set_errno(errcode,
3045 "pthread_cond_wait");
3047 /* Display progress update in log view. */
3048 show_log_view(view);
3049 update_panels();
3050 doupdate();
3053 return NULL;
3056 static const struct got_error *
3057 request_log_commits(struct tog_view *view)
3059 struct tog_log_view_state *state = &view->state.log;
3060 const struct got_error *err = NULL;
3062 if (state->thread_args.log_complete)
3063 return NULL;
3065 state->thread_args.commits_needed += view->nscrolled;
3066 err = trigger_log_thread(view, 1);
3067 view->nscrolled = 0;
3069 return err;
3072 static const struct got_error *
3073 log_scroll_down(struct tog_view *view, int maxscroll)
3075 struct tog_log_view_state *s = &view->state.log;
3076 const struct got_error *err = NULL;
3077 struct commit_queue_entry *pentry;
3078 int nscrolled = 0, ncommits_needed;
3080 if (s->last_displayed_entry == NULL)
3081 return NULL;
3083 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
3084 if (s->commits->ncommits < ncommits_needed &&
3085 !s->thread_args.log_complete) {
3087 * Ask the log thread for required amount of commits.
3089 s->thread_args.commits_needed +=
3090 ncommits_needed - s->commits->ncommits;
3091 err = trigger_log_thread(view, 1);
3092 if (err)
3093 return err;
3096 do {
3097 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
3098 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
3099 break;
3101 s->last_displayed_entry = pentry ?
3102 pentry : s->last_displayed_entry;
3104 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3105 if (pentry == NULL)
3106 break;
3107 s->first_displayed_entry = pentry;
3108 } while (++nscrolled < maxscroll);
3110 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3111 view->nscrolled += nscrolled;
3112 else
3113 view->nscrolled = 0;
3115 return err;
3118 static const struct got_error *
3119 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3120 struct got_commit_object *commit, struct got_object_id *commit_id,
3121 struct tog_view *log_view, struct got_repository *repo)
3123 const struct got_error *err;
3124 struct got_object_qid *parent_id;
3125 struct tog_view *diff_view;
3127 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3128 if (diff_view == NULL)
3129 return got_error_from_errno("view_open");
3131 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3132 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3133 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3134 if (err == NULL)
3135 *new_view = diff_view;
3136 return err;
3139 static const struct got_error *
3140 tree_view_visit_subtree(struct tog_tree_view_state *s,
3141 struct got_tree_object *subtree)
3143 struct tog_parent_tree *parent;
3145 parent = calloc(1, sizeof(*parent));
3146 if (parent == NULL)
3147 return got_error_from_errno("calloc");
3149 parent->tree = s->tree;
3150 parent->first_displayed_entry = s->first_displayed_entry;
3151 parent->selected_entry = s->selected_entry;
3152 parent->selected = s->selected;
3153 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3154 s->tree = subtree;
3155 s->selected = 0;
3156 s->first_displayed_entry = NULL;
3157 return NULL;
3160 static const struct got_error *
3161 tree_view_walk_path(struct tog_tree_view_state *s,
3162 struct got_commit_object *commit, const char *path)
3164 const struct got_error *err = NULL;
3165 struct got_tree_object *tree = NULL;
3166 const char *p;
3167 char *slash, *subpath = NULL;
3169 /* Walk the path and open corresponding tree objects. */
3170 p = path;
3171 while (*p) {
3172 struct got_tree_entry *te;
3173 struct got_object_id *tree_id;
3174 char *te_name;
3176 while (p[0] == '/')
3177 p++;
3179 /* Ensure the correct subtree entry is selected. */
3180 slash = strchr(p, '/');
3181 if (slash == NULL)
3182 te_name = strdup(p);
3183 else
3184 te_name = strndup(p, slash - p);
3185 if (te_name == NULL) {
3186 err = got_error_from_errno("strndup");
3187 break;
3189 te = got_object_tree_find_entry(s->tree, te_name);
3190 if (te == NULL) {
3191 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3192 free(te_name);
3193 break;
3195 free(te_name);
3196 s->first_displayed_entry = s->selected_entry = te;
3198 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3199 break; /* jump to this file's entry */
3201 slash = strchr(p, '/');
3202 if (slash)
3203 subpath = strndup(path, slash - path);
3204 else
3205 subpath = strdup(path);
3206 if (subpath == NULL) {
3207 err = got_error_from_errno("strdup");
3208 break;
3211 err = got_object_id_by_path(&tree_id, s->repo, commit,
3212 subpath);
3213 if (err)
3214 break;
3216 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3217 free(tree_id);
3218 if (err)
3219 break;
3221 err = tree_view_visit_subtree(s, tree);
3222 if (err) {
3223 got_object_tree_close(tree);
3224 break;
3226 if (slash == NULL)
3227 break;
3228 free(subpath);
3229 subpath = NULL;
3230 p = slash;
3233 free(subpath);
3234 return err;
3237 static const struct got_error *
3238 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3239 struct commit_queue_entry *entry, const char *path,
3240 const char *head_ref_name, struct got_repository *repo)
3242 const struct got_error *err = NULL;
3243 struct tog_tree_view_state *s;
3244 struct tog_view *tree_view;
3246 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3247 if (tree_view == NULL)
3248 return got_error_from_errno("view_open");
3250 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3251 if (err)
3252 return err;
3253 s = &tree_view->state.tree;
3255 *new_view = tree_view;
3257 if (got_path_is_root_dir(path))
3258 return NULL;
3260 return tree_view_walk_path(s, entry->commit, path);
3263 static const struct got_error *
3264 block_signals_used_by_main_thread(void)
3266 sigset_t sigset;
3267 int errcode;
3269 if (sigemptyset(&sigset) == -1)
3270 return got_error_from_errno("sigemptyset");
3272 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3273 if (sigaddset(&sigset, SIGWINCH) == -1)
3274 return got_error_from_errno("sigaddset");
3275 if (sigaddset(&sigset, SIGCONT) == -1)
3276 return got_error_from_errno("sigaddset");
3277 if (sigaddset(&sigset, SIGINT) == -1)
3278 return got_error_from_errno("sigaddset");
3279 if (sigaddset(&sigset, SIGTERM) == -1)
3280 return got_error_from_errno("sigaddset");
3282 /* ncurses handles SIGTSTP */
3283 if (sigaddset(&sigset, SIGTSTP) == -1)
3284 return got_error_from_errno("sigaddset");
3286 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3287 if (errcode)
3288 return got_error_set_errno(errcode, "pthread_sigmask");
3290 return NULL;
3293 static void *
3294 log_thread(void *arg)
3296 const struct got_error *err = NULL;
3297 int errcode = 0;
3298 struct tog_log_thread_args *a = arg;
3299 int done = 0;
3302 * Sync startup with main thread such that we begin our
3303 * work once view_input() has released the mutex.
3305 errcode = pthread_mutex_lock(&tog_mutex);
3306 if (errcode) {
3307 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3308 return (void *)err;
3311 err = block_signals_used_by_main_thread();
3312 if (err) {
3313 pthread_mutex_unlock(&tog_mutex);
3314 goto done;
3317 while (!done && !err && !tog_fatal_signal_received()) {
3318 errcode = pthread_mutex_unlock(&tog_mutex);
3319 if (errcode) {
3320 err = got_error_set_errno(errcode,
3321 "pthread_mutex_unlock");
3322 goto done;
3324 err = queue_commits(a);
3325 if (err) {
3326 if (err->code != GOT_ERR_ITER_COMPLETED)
3327 goto done;
3328 err = NULL;
3329 done = 1;
3330 } else if (a->commits_needed > 0 && !a->load_all) {
3331 if (*a->limiting) {
3332 if (a->limit_match)
3333 a->commits_needed--;
3334 } else
3335 a->commits_needed--;
3338 errcode = pthread_mutex_lock(&tog_mutex);
3339 if (errcode) {
3340 err = got_error_set_errno(errcode,
3341 "pthread_mutex_lock");
3342 goto done;
3343 } else if (*a->quit)
3344 done = 1;
3345 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3346 *a->first_displayed_entry =
3347 TAILQ_FIRST(&a->limit_commits->head);
3348 *a->selected_entry = *a->first_displayed_entry;
3349 } else if (*a->first_displayed_entry == NULL) {
3350 *a->first_displayed_entry =
3351 TAILQ_FIRST(&a->real_commits->head);
3352 *a->selected_entry = *a->first_displayed_entry;
3355 errcode = pthread_cond_signal(&a->commit_loaded);
3356 if (errcode) {
3357 err = got_error_set_errno(errcode,
3358 "pthread_cond_signal");
3359 pthread_mutex_unlock(&tog_mutex);
3360 goto done;
3363 if (done)
3364 a->commits_needed = 0;
3365 else {
3366 if (a->commits_needed == 0 && !a->load_all) {
3367 errcode = pthread_cond_wait(&a->need_commits,
3368 &tog_mutex);
3369 if (errcode) {
3370 err = got_error_set_errno(errcode,
3371 "pthread_cond_wait");
3372 pthread_mutex_unlock(&tog_mutex);
3373 goto done;
3375 if (*a->quit)
3376 done = 1;
3380 a->log_complete = 1;
3381 errcode = pthread_mutex_unlock(&tog_mutex);
3382 if (errcode)
3383 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3384 done:
3385 if (err) {
3386 tog_thread_error = 1;
3387 pthread_cond_signal(&a->commit_loaded);
3389 return (void *)err;
3392 static const struct got_error *
3393 stop_log_thread(struct tog_log_view_state *s)
3395 const struct got_error *err = NULL, *thread_err = NULL;
3396 int errcode;
3398 if (s->thread) {
3399 s->quit = 1;
3400 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3401 if (errcode)
3402 return got_error_set_errno(errcode,
3403 "pthread_cond_signal");
3404 errcode = pthread_mutex_unlock(&tog_mutex);
3405 if (errcode)
3406 return got_error_set_errno(errcode,
3407 "pthread_mutex_unlock");
3408 errcode = pthread_join(s->thread, (void **)&thread_err);
3409 if (errcode)
3410 return got_error_set_errno(errcode, "pthread_join");
3411 errcode = pthread_mutex_lock(&tog_mutex);
3412 if (errcode)
3413 return got_error_set_errno(errcode,
3414 "pthread_mutex_lock");
3415 s->thread = NULL;
3418 if (s->thread_args.repo) {
3419 err = got_repo_close(s->thread_args.repo);
3420 s->thread_args.repo = NULL;
3423 if (s->thread_args.pack_fds) {
3424 const struct got_error *pack_err =
3425 got_repo_pack_fds_close(s->thread_args.pack_fds);
3426 if (err == NULL)
3427 err = pack_err;
3428 s->thread_args.pack_fds = NULL;
3431 if (s->thread_args.graph) {
3432 got_commit_graph_close(s->thread_args.graph);
3433 s->thread_args.graph = NULL;
3436 return err ? err : thread_err;
3439 static const struct got_error *
3440 close_log_view(struct tog_view *view)
3442 const struct got_error *err = NULL;
3443 struct tog_log_view_state *s = &view->state.log;
3444 int errcode;
3446 err = stop_log_thread(s);
3448 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3449 if (errcode && err == NULL)
3450 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3452 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3453 if (errcode && err == NULL)
3454 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3456 free_commits(&s->limit_commits);
3457 free_commits(&s->real_commits);
3458 free(s->in_repo_path);
3459 s->in_repo_path = NULL;
3460 free(s->start_id);
3461 s->start_id = NULL;
3462 free(s->head_ref_name);
3463 s->head_ref_name = NULL;
3464 return err;
3468 * We use two queues to implement the limit feature: first consists of
3469 * commits matching the current limit_regex; second is the real queue
3470 * of all known commits (real_commits). When the user starts limiting,
3471 * we swap queues such that all movement and displaying functionality
3472 * works with very slight change.
3474 static const struct got_error *
3475 limit_log_view(struct tog_view *view)
3477 struct tog_log_view_state *s = &view->state.log;
3478 struct commit_queue_entry *entry;
3479 struct tog_view *v = view;
3480 const struct got_error *err = NULL;
3481 char pattern[1024];
3482 int ret;
3484 if (view_is_hsplit_top(view))
3485 v = view->child;
3486 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3487 v = view->parent;
3489 /* Get the pattern */
3490 wmove(v->window, v->nlines - 1, 0);
3491 wclrtoeol(v->window);
3492 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3493 nodelay(v->window, FALSE);
3494 nocbreak();
3495 echo();
3496 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3497 cbreak();
3498 noecho();
3499 nodelay(v->window, TRUE);
3500 if (ret == ERR)
3501 return NULL;
3503 if (*pattern == '\0') {
3505 * Safety measure for the situation where the user
3506 * resets limit without previously limiting anything.
3508 if (!s->limit_view)
3509 return NULL;
3512 * User could have pressed Ctrl+L, which refreshed the
3513 * commit queues, it means we can't save previously
3514 * (before limit took place) displayed entries,
3515 * because they would point to already free'ed memory,
3516 * so we are forced to always select first entry of
3517 * the queue.
3519 s->commits = &s->real_commits;
3520 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3521 s->selected_entry = s->first_displayed_entry;
3522 s->selected = 0;
3523 s->limit_view = 0;
3525 return NULL;
3528 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3529 return NULL;
3531 s->limit_view = 1;
3533 /* Clear the screen while loading limit view */
3534 s->first_displayed_entry = NULL;
3535 s->last_displayed_entry = NULL;
3536 s->selected_entry = NULL;
3537 s->commits = &s->limit_commits;
3539 /* Prepare limit queue for new search */
3540 free_commits(&s->limit_commits);
3541 s->limit_commits.ncommits = 0;
3543 /* First process commits, which are in queue already */
3544 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3545 int have_match = 0;
3547 err = match_commit(&have_match, entry->id,
3548 entry->commit, &s->limit_regex);
3549 if (err)
3550 return err;
3552 if (have_match) {
3553 struct commit_queue_entry *matched;
3555 matched = alloc_commit_queue_entry(entry->commit,
3556 entry->id);
3557 if (matched == NULL) {
3558 err = got_error_from_errno(
3559 "alloc_commit_queue_entry");
3560 break;
3562 matched->commit = entry->commit;
3563 got_object_commit_retain(entry->commit);
3565 matched->idx = s->limit_commits.ncommits;
3566 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3567 matched, entry);
3568 s->limit_commits.ncommits++;
3572 /* Second process all the commits, until we fill the screen */
3573 if (s->limit_commits.ncommits < view->nlines - 1 &&
3574 !s->thread_args.log_complete) {
3575 s->thread_args.commits_needed +=
3576 view->nlines - s->limit_commits.ncommits - 1;
3577 err = trigger_log_thread(view, 1);
3578 if (err)
3579 return err;
3582 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3583 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3584 s->selected = 0;
3586 return NULL;
3589 static const struct got_error *
3590 search_start_log_view(struct tog_view *view)
3592 struct tog_log_view_state *s = &view->state.log;
3594 s->matched_entry = NULL;
3595 s->search_entry = NULL;
3596 return NULL;
3599 static const struct got_error *
3600 search_next_log_view(struct tog_view *view)
3602 const struct got_error *err = NULL;
3603 struct tog_log_view_state *s = &view->state.log;
3604 struct commit_queue_entry *entry;
3606 /* Display progress update in log view. */
3607 show_log_view(view);
3608 update_panels();
3609 doupdate();
3611 if (s->search_entry) {
3612 int errcode, ch;
3613 errcode = pthread_mutex_unlock(&tog_mutex);
3614 if (errcode)
3615 return got_error_set_errno(errcode,
3616 "pthread_mutex_unlock");
3617 ch = wgetch(view->window);
3618 errcode = pthread_mutex_lock(&tog_mutex);
3619 if (errcode)
3620 return got_error_set_errno(errcode,
3621 "pthread_mutex_lock");
3622 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3623 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3624 return NULL;
3626 if (view->searching == TOG_SEARCH_FORWARD)
3627 entry = TAILQ_NEXT(s->search_entry, entry);
3628 else
3629 entry = TAILQ_PREV(s->search_entry,
3630 commit_queue_head, entry);
3631 } else if (s->matched_entry) {
3633 * If the user has moved the cursor after we hit a match,
3634 * the position from where we should continue searching
3635 * might have changed.
3637 if (view->searching == TOG_SEARCH_FORWARD)
3638 entry = TAILQ_NEXT(s->selected_entry, entry);
3639 else
3640 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3641 entry);
3642 } else {
3643 entry = s->selected_entry;
3646 while (1) {
3647 int have_match = 0;
3649 if (entry == NULL) {
3650 if (s->thread_args.log_complete ||
3651 view->searching == TOG_SEARCH_BACKWARD) {
3652 view->search_next_done =
3653 (s->matched_entry == NULL ?
3654 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3655 s->search_entry = NULL;
3656 return NULL;
3659 * Poke the log thread for more commits and return,
3660 * allowing the main loop to make progress. Search
3661 * will resume at s->search_entry once we come back.
3663 s->thread_args.commits_needed++;
3664 return trigger_log_thread(view, 0);
3667 err = match_commit(&have_match, entry->id, entry->commit,
3668 &view->regex);
3669 if (err)
3670 break;
3671 if (have_match) {
3672 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3673 s->matched_entry = entry;
3674 break;
3677 s->search_entry = entry;
3678 if (view->searching == TOG_SEARCH_FORWARD)
3679 entry = TAILQ_NEXT(entry, entry);
3680 else
3681 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3684 if (s->matched_entry) {
3685 int cur = s->selected_entry->idx;
3686 while (cur < s->matched_entry->idx) {
3687 err = input_log_view(NULL, view, KEY_DOWN);
3688 if (err)
3689 return err;
3690 cur++;
3692 while (cur > s->matched_entry->idx) {
3693 err = input_log_view(NULL, view, KEY_UP);
3694 if (err)
3695 return err;
3696 cur--;
3700 s->search_entry = NULL;
3702 return NULL;
3705 static const struct got_error *
3706 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3707 struct got_repository *repo, const char *head_ref_name,
3708 const char *in_repo_path, int log_branches)
3710 const struct got_error *err = NULL;
3711 struct tog_log_view_state *s = &view->state.log;
3712 struct got_repository *thread_repo = NULL;
3713 struct got_commit_graph *thread_graph = NULL;
3714 int errcode;
3716 if (in_repo_path != s->in_repo_path) {
3717 free(s->in_repo_path);
3718 s->in_repo_path = strdup(in_repo_path);
3719 if (s->in_repo_path == NULL) {
3720 err = got_error_from_errno("strdup");
3721 goto done;
3725 /* The commit queue only contains commits being displayed. */
3726 TAILQ_INIT(&s->real_commits.head);
3727 s->real_commits.ncommits = 0;
3728 s->commits = &s->real_commits;
3730 TAILQ_INIT(&s->limit_commits.head);
3731 s->limit_view = 0;
3732 s->limit_commits.ncommits = 0;
3734 s->repo = repo;
3735 if (head_ref_name) {
3736 s->head_ref_name = strdup(head_ref_name);
3737 if (s->head_ref_name == NULL) {
3738 err = got_error_from_errno("strdup");
3739 goto done;
3742 s->start_id = got_object_id_dup(start_id);
3743 if (s->start_id == NULL) {
3744 err = got_error_from_errno("got_object_id_dup");
3745 goto done;
3747 s->log_branches = log_branches;
3748 s->use_committer = 1;
3750 STAILQ_INIT(&s->colors);
3751 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3752 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3753 get_color_value("TOG_COLOR_COMMIT"));
3754 if (err)
3755 goto done;
3756 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3757 get_color_value("TOG_COLOR_AUTHOR"));
3758 if (err) {
3759 free_colors(&s->colors);
3760 goto done;
3762 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3763 get_color_value("TOG_COLOR_DATE"));
3764 if (err) {
3765 free_colors(&s->colors);
3766 goto done;
3770 view->show = show_log_view;
3771 view->input = input_log_view;
3772 view->resize = resize_log_view;
3773 view->close = close_log_view;
3774 view->search_start = search_start_log_view;
3775 view->search_next = search_next_log_view;
3777 if (s->thread_args.pack_fds == NULL) {
3778 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3779 if (err)
3780 goto done;
3782 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3783 s->thread_args.pack_fds);
3784 if (err)
3785 goto done;
3786 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3787 !s->log_branches);
3788 if (err)
3789 goto done;
3790 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3791 s->repo, NULL, NULL);
3792 if (err)
3793 goto done;
3795 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3796 if (errcode) {
3797 err = got_error_set_errno(errcode, "pthread_cond_init");
3798 goto done;
3800 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3801 if (errcode) {
3802 err = got_error_set_errno(errcode, "pthread_cond_init");
3803 goto done;
3806 s->thread_args.commits_needed = view->nlines;
3807 s->thread_args.graph = thread_graph;
3808 s->thread_args.real_commits = &s->real_commits;
3809 s->thread_args.limit_commits = &s->limit_commits;
3810 s->thread_args.in_repo_path = s->in_repo_path;
3811 s->thread_args.start_id = s->start_id;
3812 s->thread_args.repo = thread_repo;
3813 s->thread_args.log_complete = 0;
3814 s->thread_args.quit = &s->quit;
3815 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3816 s->thread_args.selected_entry = &s->selected_entry;
3817 s->thread_args.searching = &view->searching;
3818 s->thread_args.search_next_done = &view->search_next_done;
3819 s->thread_args.regex = &view->regex;
3820 s->thread_args.limiting = &s->limit_view;
3821 s->thread_args.limit_regex = &s->limit_regex;
3822 s->thread_args.limit_commits = &s->limit_commits;
3823 done:
3824 if (err) {
3825 if (view->close == NULL)
3826 close_log_view(view);
3827 view_close(view);
3829 return err;
3832 static const struct got_error *
3833 show_log_view(struct tog_view *view)
3835 const struct got_error *err;
3836 struct tog_log_view_state *s = &view->state.log;
3838 if (s->thread == NULL) {
3839 int errcode = pthread_create(&s->thread, NULL, log_thread,
3840 &s->thread_args);
3841 if (errcode)
3842 return got_error_set_errno(errcode, "pthread_create");
3843 if (s->thread_args.commits_needed > 0) {
3844 err = trigger_log_thread(view, 1);
3845 if (err)
3846 return err;
3850 return draw_commits(view);
3853 static void
3854 log_move_cursor_up(struct tog_view *view, int page, int home)
3856 struct tog_log_view_state *s = &view->state.log;
3858 if (s->first_displayed_entry == NULL)
3859 return;
3860 if (s->selected_entry->idx == 0)
3861 view->count = 0;
3863 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3864 || home)
3865 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3867 if (!page && !home && s->selected > 0)
3868 --s->selected;
3869 else
3870 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3872 select_commit(s);
3873 return;
3876 static const struct got_error *
3877 log_move_cursor_down(struct tog_view *view, int page)
3879 struct tog_log_view_state *s = &view->state.log;
3880 const struct got_error *err = NULL;
3881 int eos = view->nlines - 2;
3883 if (s->first_displayed_entry == NULL)
3884 return NULL;
3886 if (s->thread_args.log_complete &&
3887 s->selected_entry->idx >= s->commits->ncommits - 1)
3888 return NULL;
3890 if (view_is_hsplit_top(view))
3891 --eos; /* border consumes the last line */
3893 if (!page) {
3894 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3895 ++s->selected;
3896 else
3897 err = log_scroll_down(view, 1);
3898 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3899 struct commit_queue_entry *entry;
3900 int n;
3902 s->selected = 0;
3903 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3904 s->last_displayed_entry = entry;
3905 for (n = 0; n <= eos; n++) {
3906 if (entry == NULL)
3907 break;
3908 s->first_displayed_entry = entry;
3909 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3911 if (n > 0)
3912 s->selected = n - 1;
3913 } else {
3914 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3915 s->thread_args.log_complete)
3916 s->selected += MIN(page,
3917 s->commits->ncommits - s->selected_entry->idx - 1);
3918 else
3919 err = log_scroll_down(view, page);
3921 if (err)
3922 return err;
3925 * We might necessarily overshoot in horizontal
3926 * splits; if so, select the last displayed commit.
3928 if (s->first_displayed_entry && s->last_displayed_entry) {
3929 s->selected = MIN(s->selected,
3930 s->last_displayed_entry->idx -
3931 s->first_displayed_entry->idx);
3934 select_commit(s);
3936 if (s->thread_args.log_complete &&
3937 s->selected_entry->idx == s->commits->ncommits - 1)
3938 view->count = 0;
3940 return NULL;
3943 static void
3944 view_get_split(struct tog_view *view, int *y, int *x)
3946 *x = 0;
3947 *y = 0;
3949 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3950 if (view->child && view->child->resized_y)
3951 *y = view->child->resized_y;
3952 else if (view->resized_y)
3953 *y = view->resized_y;
3954 else
3955 *y = view_split_begin_y(view->lines);
3956 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3957 if (view->child && view->child->resized_x)
3958 *x = view->child->resized_x;
3959 else if (view->resized_x)
3960 *x = view->resized_x;
3961 else
3962 *x = view_split_begin_x(view->begin_x);
3966 /* Split view horizontally at y and offset view->state->selected line. */
3967 static const struct got_error *
3968 view_init_hsplit(struct tog_view *view, int y)
3970 const struct got_error *err = NULL;
3972 view->nlines = y;
3973 view->ncols = COLS;
3974 err = view_resize(view);
3975 if (err)
3976 return err;
3978 err = offset_selection_down(view);
3980 return err;
3983 static const struct got_error *
3984 log_goto_line(struct tog_view *view, int nlines)
3986 const struct got_error *err = NULL;
3987 struct tog_log_view_state *s = &view->state.log;
3988 int g, idx = s->selected_entry->idx;
3990 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3991 return NULL;
3993 g = view->gline;
3994 view->gline = 0;
3996 if (g >= s->first_displayed_entry->idx + 1 &&
3997 g <= s->last_displayed_entry->idx + 1 &&
3998 g - s->first_displayed_entry->idx - 1 < nlines) {
3999 s->selected = g - s->first_displayed_entry->idx - 1;
4000 select_commit(s);
4001 return NULL;
4004 if (idx + 1 < g) {
4005 err = log_move_cursor_down(view, g - idx - 1);
4006 if (!err && g > s->selected_entry->idx + 1)
4007 err = log_move_cursor_down(view,
4008 g - s->first_displayed_entry->idx - 1);
4009 if (err)
4010 return err;
4011 } else if (idx + 1 > g)
4012 log_move_cursor_up(view, idx - g + 1, 0);
4014 if (g < nlines && s->first_displayed_entry->idx == 0)
4015 s->selected = g - 1;
4017 select_commit(s);
4018 return NULL;
4022 static void
4023 horizontal_scroll_input(struct tog_view *view, int ch)
4026 switch (ch) {
4027 case KEY_LEFT:
4028 case 'h':
4029 view->x -= MIN(view->x, 2);
4030 if (view->x <= 0)
4031 view->count = 0;
4032 break;
4033 case KEY_RIGHT:
4034 case 'l':
4035 if (view->x + view->ncols / 2 < view->maxx)
4036 view->x += 2;
4037 else
4038 view->count = 0;
4039 break;
4040 case '0':
4041 view->x = 0;
4042 break;
4043 case '$':
4044 view->x = MAX(view->maxx - view->ncols / 2, 0);
4045 view->count = 0;
4046 break;
4047 default:
4048 break;
4052 static const struct got_error *
4053 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
4055 const struct got_error *err = NULL;
4056 struct tog_log_view_state *s = &view->state.log;
4057 int eos, nscroll;
4059 if (s->thread_args.load_all) {
4060 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
4061 s->thread_args.load_all = 0;
4062 else if (s->thread_args.log_complete) {
4063 err = log_move_cursor_down(view, s->commits->ncommits);
4064 s->thread_args.load_all = 0;
4066 if (err)
4067 return err;
4070 eos = nscroll = view->nlines - 1;
4071 if (view_is_hsplit_top(view))
4072 --eos; /* border */
4074 if (view->gline)
4075 return log_goto_line(view, eos);
4077 switch (ch) {
4078 case '&':
4079 err = limit_log_view(view);
4080 break;
4081 case 'q':
4082 s->quit = 1;
4083 break;
4084 case '0':
4085 case '$':
4086 case KEY_RIGHT:
4087 case 'l':
4088 case KEY_LEFT:
4089 case 'h':
4090 horizontal_scroll_input(view, ch);
4091 break;
4092 case 'k':
4093 case KEY_UP:
4094 case '<':
4095 case ',':
4096 case CTRL('p'):
4097 log_move_cursor_up(view, 0, 0);
4098 break;
4099 case 'g':
4100 case '=':
4101 case KEY_HOME:
4102 log_move_cursor_up(view, 0, 1);
4103 view->count = 0;
4104 break;
4105 case CTRL('u'):
4106 case 'u':
4107 nscroll /= 2;
4108 /* FALL THROUGH */
4109 case KEY_PPAGE:
4110 case CTRL('b'):
4111 case 'b':
4112 log_move_cursor_up(view, nscroll, 0);
4113 break;
4114 case 'j':
4115 case KEY_DOWN:
4116 case '>':
4117 case '.':
4118 case CTRL('n'):
4119 err = log_move_cursor_down(view, 0);
4120 break;
4121 case '@':
4122 s->use_committer = !s->use_committer;
4123 view->action = s->use_committer ?
4124 "show committer" : "show commit author";
4125 break;
4126 case 'G':
4127 case '*':
4128 case KEY_END: {
4129 /* We don't know yet how many commits, so we're forced to
4130 * traverse them all. */
4131 view->count = 0;
4132 s->thread_args.load_all = 1;
4133 if (!s->thread_args.log_complete)
4134 return trigger_log_thread(view, 0);
4135 err = log_move_cursor_down(view, s->commits->ncommits);
4136 s->thread_args.load_all = 0;
4137 break;
4139 case CTRL('d'):
4140 case 'd':
4141 nscroll /= 2;
4142 /* FALL THROUGH */
4143 case KEY_NPAGE:
4144 case CTRL('f'):
4145 case 'f':
4146 case ' ':
4147 err = log_move_cursor_down(view, nscroll);
4148 break;
4149 case KEY_RESIZE:
4150 if (s->selected > view->nlines - 2)
4151 s->selected = view->nlines - 2;
4152 if (s->selected > s->commits->ncommits - 1)
4153 s->selected = s->commits->ncommits - 1;
4154 select_commit(s);
4155 if (s->commits->ncommits < view->nlines - 1 &&
4156 !s->thread_args.log_complete) {
4157 s->thread_args.commits_needed += (view->nlines - 1) -
4158 s->commits->ncommits;
4159 err = trigger_log_thread(view, 1);
4161 break;
4162 case KEY_ENTER:
4163 case '\r':
4164 view->count = 0;
4165 if (s->selected_entry == NULL)
4166 break;
4167 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4168 break;
4169 case 'T':
4170 view->count = 0;
4171 if (s->selected_entry == NULL)
4172 break;
4173 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4174 break;
4175 case KEY_BACKSPACE:
4176 case CTRL('l'):
4177 case 'B':
4178 view->count = 0;
4179 if (ch == KEY_BACKSPACE &&
4180 got_path_is_root_dir(s->in_repo_path))
4181 break;
4182 err = stop_log_thread(s);
4183 if (err)
4184 return err;
4185 if (ch == KEY_BACKSPACE) {
4186 char *parent_path;
4187 err = got_path_dirname(&parent_path, s->in_repo_path);
4188 if (err)
4189 return err;
4190 free(s->in_repo_path);
4191 s->in_repo_path = parent_path;
4192 s->thread_args.in_repo_path = s->in_repo_path;
4193 } else if (ch == CTRL('l')) {
4194 struct got_object_id *start_id;
4195 err = got_repo_match_object_id(&start_id, NULL,
4196 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4197 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4198 if (err) {
4199 if (s->head_ref_name == NULL ||
4200 err->code != GOT_ERR_NOT_REF)
4201 return err;
4202 /* Try to cope with deleted references. */
4203 free(s->head_ref_name);
4204 s->head_ref_name = NULL;
4205 err = got_repo_match_object_id(&start_id,
4206 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4207 &tog_refs, s->repo);
4208 if (err)
4209 return err;
4211 free(s->start_id);
4212 s->start_id = start_id;
4213 s->thread_args.start_id = s->start_id;
4214 } else /* 'B' */
4215 s->log_branches = !s->log_branches;
4217 if (s->thread_args.pack_fds == NULL) {
4218 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4219 if (err)
4220 return err;
4222 err = got_repo_open(&s->thread_args.repo,
4223 got_repo_get_path(s->repo), NULL,
4224 s->thread_args.pack_fds);
4225 if (err)
4226 return err;
4227 tog_free_refs();
4228 err = tog_load_refs(s->repo, 0);
4229 if (err)
4230 return err;
4231 err = got_commit_graph_open(&s->thread_args.graph,
4232 s->in_repo_path, !s->log_branches);
4233 if (err)
4234 return err;
4235 err = got_commit_graph_iter_start(s->thread_args.graph,
4236 s->start_id, s->repo, NULL, NULL);
4237 if (err)
4238 return err;
4239 free_commits(&s->real_commits);
4240 free_commits(&s->limit_commits);
4241 s->first_displayed_entry = NULL;
4242 s->last_displayed_entry = NULL;
4243 s->selected_entry = NULL;
4244 s->selected = 0;
4245 s->thread_args.log_complete = 0;
4246 s->quit = 0;
4247 s->thread_args.commits_needed = view->lines;
4248 s->matched_entry = NULL;
4249 s->search_entry = NULL;
4250 view->offset = 0;
4251 break;
4252 case 'R':
4253 view->count = 0;
4254 err = view_request_new(new_view, view, TOG_VIEW_REF);
4255 break;
4256 default:
4257 view->count = 0;
4258 break;
4261 return err;
4264 static const struct got_error *
4265 apply_unveil(const char *repo_path, const char *worktree_path)
4267 const struct got_error *error;
4269 #ifdef PROFILE
4270 if (unveil("gmon.out", "rwc") != 0)
4271 return got_error_from_errno2("unveil", "gmon.out");
4272 #endif
4273 if (repo_path && unveil(repo_path, "r") != 0)
4274 return got_error_from_errno2("unveil", repo_path);
4276 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4277 return got_error_from_errno2("unveil", worktree_path);
4279 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4280 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4282 error = got_privsep_unveil_exec_helpers();
4283 if (error != NULL)
4284 return error;
4286 if (unveil(NULL, NULL) != 0)
4287 return got_error_from_errno("unveil");
4289 return NULL;
4292 static const struct got_error *
4293 init_mock_term(const char *test_script_path)
4295 const struct got_error *err = NULL;
4296 const char *screen_dump_path;
4297 int in;
4299 if (test_script_path == NULL || *test_script_path == '\0')
4300 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4302 tog_io.f = fopen(test_script_path, "re");
4303 if (tog_io.f == NULL) {
4304 err = got_error_from_errno_fmt("fopen: %s",
4305 test_script_path);
4306 goto done;
4309 /* test mode, we don't want any output */
4310 tog_io.cout = fopen("/dev/null", "w+");
4311 if (tog_io.cout == NULL) {
4312 err = got_error_from_errno2("fopen", "/dev/null");
4313 goto done;
4316 in = dup(fileno(tog_io.cout));
4317 if (in == -1) {
4318 err = got_error_from_errno("dup");
4319 goto done;
4321 tog_io.cin = fdopen(in, "r");
4322 if (tog_io.cin == NULL) {
4323 err = got_error_from_errno("fdopen");
4324 close(in);
4325 goto done;
4328 screen_dump_path = getenv("TOG_SCR_DUMP");
4329 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4330 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4331 tog_io.sdump = fopen(screen_dump_path, "we");
4332 if (tog_io.sdump == NULL) {
4333 err = got_error_from_errno2("fopen", screen_dump_path);
4334 goto done;
4337 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4338 err = got_error_from_errno("fseeko");
4339 goto done;
4342 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4343 err = got_error_msg(GOT_ERR_IO,
4344 "newterm: failed to initialise curses");
4346 using_mock_io = 1;
4348 done:
4349 if (err)
4350 tog_io_close();
4351 return err;
4354 static void
4355 init_curses(void)
4358 * Override default signal handlers before starting ncurses.
4359 * This should prevent ncurses from installing its own
4360 * broken cleanup() signal handler.
4362 signal(SIGWINCH, tog_sigwinch);
4363 signal(SIGPIPE, tog_sigpipe);
4364 signal(SIGCONT, tog_sigcont);
4365 signal(SIGINT, tog_sigint);
4366 signal(SIGTERM, tog_sigterm);
4368 if (using_mock_io) /* In test mode we use a fake terminal */
4369 return;
4371 initscr();
4373 cbreak();
4374 halfdelay(1); /* Fast refresh while initial view is loading. */
4375 noecho();
4376 nonl();
4377 intrflush(stdscr, FALSE);
4378 keypad(stdscr, TRUE);
4379 curs_set(0);
4380 if (getenv("TOG_COLORS") != NULL) {
4381 start_color();
4382 use_default_colors();
4385 return;
4388 static const struct got_error *
4389 set_tog_base_commit(struct got_repository *repo, struct got_worktree *worktree)
4391 tog_base_commit.id = got_object_id_dup(
4392 got_worktree_get_base_commit_id(worktree));
4393 if (tog_base_commit.id == NULL)
4394 return got_error_from_errno( "got_object_id_dup");
4396 tog_base_commit.idx = -1;
4398 return got_worktree_get_state(&tog_base_commit.marker, repo,
4399 worktree);
4402 static const struct got_error *
4403 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4404 struct got_repository *repo, struct got_worktree *worktree)
4406 const struct got_error *err = NULL;
4408 if (argc == 0) {
4409 *in_repo_path = strdup("/");
4410 if (*in_repo_path == NULL)
4411 return got_error_from_errno("strdup");
4412 return NULL;
4415 if (worktree) {
4416 const char *prefix = got_worktree_get_path_prefix(worktree);
4417 char *p;
4419 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4420 if (err)
4421 return err;
4422 if (asprintf(in_repo_path, "%s%s%s", prefix,
4423 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4424 p) == -1) {
4425 err = got_error_from_errno("asprintf");
4426 *in_repo_path = NULL;
4428 free(p);
4429 } else
4430 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4432 return err;
4435 static const struct got_error *
4436 cmd_log(int argc, char *argv[])
4438 const struct got_error *error;
4439 struct got_repository *repo = NULL;
4440 struct got_worktree *worktree = NULL;
4441 struct got_object_id *start_id = NULL;
4442 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4443 char *keyword_idstr = NULL, *start_commit = NULL, *label = NULL;
4444 struct got_reference *ref = NULL;
4445 const char *head_ref_name = NULL;
4446 int ch, log_branches = 0;
4447 struct tog_view *view;
4448 int *pack_fds = NULL;
4450 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4451 switch (ch) {
4452 case 'b':
4453 log_branches = 1;
4454 break;
4455 case 'c':
4456 start_commit = optarg;
4457 break;
4458 case 'r':
4459 repo_path = realpath(optarg, NULL);
4460 if (repo_path == NULL)
4461 return got_error_from_errno2("realpath",
4462 optarg);
4463 break;
4464 default:
4465 usage_log();
4466 /* NOTREACHED */
4470 argc -= optind;
4471 argv += optind;
4473 if (argc > 1)
4474 usage_log();
4476 error = got_repo_pack_fds_open(&pack_fds);
4477 if (error != NULL)
4478 goto done;
4480 if (repo_path == NULL) {
4481 cwd = getcwd(NULL, 0);
4482 if (cwd == NULL) {
4483 error = got_error_from_errno("getcwd");
4484 goto done;
4486 error = got_worktree_open(&worktree, cwd, NULL);
4487 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4488 goto done;
4489 if (worktree)
4490 repo_path =
4491 strdup(got_worktree_get_repo_path(worktree));
4492 else
4493 repo_path = strdup(cwd);
4494 if (repo_path == NULL) {
4495 error = got_error_from_errno("strdup");
4496 goto done;
4500 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4501 if (error != NULL)
4502 goto done;
4504 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4505 repo, worktree);
4506 if (error)
4507 goto done;
4509 init_curses();
4511 error = apply_unveil(got_repo_get_path(repo),
4512 worktree ? got_worktree_get_root_path(worktree) : NULL);
4513 if (error)
4514 goto done;
4516 /* already loaded by tog_log_with_path()? */
4517 if (TAILQ_EMPTY(&tog_refs)) {
4518 error = tog_load_refs(repo, 0);
4519 if (error)
4520 goto done;
4523 if (start_commit == NULL) {
4524 error = got_repo_match_object_id(&start_id, &label,
4525 worktree ? got_worktree_get_head_ref_name(worktree) :
4526 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4527 if (error)
4528 goto done;
4529 head_ref_name = label;
4530 } else {
4531 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4532 repo, worktree);
4533 if (error != NULL)
4534 goto done;
4535 if (keyword_idstr != NULL)
4536 start_commit = keyword_idstr;
4538 error = got_ref_open(&ref, repo, start_commit, 0);
4539 if (error == NULL)
4540 head_ref_name = got_ref_get_name(ref);
4541 else if (error->code != GOT_ERR_NOT_REF)
4542 goto done;
4543 error = got_repo_match_object_id(&start_id, NULL,
4544 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4545 if (error)
4546 goto done;
4549 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4550 if (view == NULL) {
4551 error = got_error_from_errno("view_open");
4552 goto done;
4554 error = open_log_view(view, start_id, repo, head_ref_name,
4555 in_repo_path, log_branches);
4556 if (error)
4557 goto done;
4559 if (worktree) {
4560 error = set_tog_base_commit(repo, worktree);
4561 if (error != NULL)
4562 goto done;
4564 /* Release work tree lock. */
4565 got_worktree_close(worktree);
4566 worktree = NULL;
4569 error = view_loop(view);
4571 done:
4572 free(tog_base_commit.id);
4573 free(keyword_idstr);
4574 free(in_repo_path);
4575 free(repo_path);
4576 free(cwd);
4577 free(start_id);
4578 free(label);
4579 if (ref)
4580 got_ref_close(ref);
4581 if (repo) {
4582 const struct got_error *close_err = got_repo_close(repo);
4583 if (error == NULL)
4584 error = close_err;
4586 if (worktree)
4587 got_worktree_close(worktree);
4588 if (pack_fds) {
4589 const struct got_error *pack_err =
4590 got_repo_pack_fds_close(pack_fds);
4591 if (error == NULL)
4592 error = pack_err;
4594 tog_free_refs();
4595 return error;
4598 __dead static void
4599 usage_diff(void)
4601 endwin();
4602 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4603 "object1 object2\n", getprogname());
4604 exit(1);
4607 static int
4608 match_line(const char *line, regex_t *regex, size_t nmatch,
4609 regmatch_t *regmatch)
4611 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4614 static struct tog_color *
4615 match_color(struct tog_colors *colors, const char *line)
4617 struct tog_color *tc = NULL;
4619 STAILQ_FOREACH(tc, colors, entry) {
4620 if (match_line(line, &tc->regex, 0, NULL))
4621 return tc;
4624 return NULL;
4627 static const struct got_error *
4628 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4629 WINDOW *window, int skipcol, regmatch_t *regmatch)
4631 const struct got_error *err = NULL;
4632 char *exstr = NULL;
4633 wchar_t *wline = NULL;
4634 int rme, rms, n, width, scrollx;
4635 int width0 = 0, width1 = 0, width2 = 0;
4636 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4638 *wtotal = 0;
4640 rms = regmatch->rm_so;
4641 rme = regmatch->rm_eo;
4643 err = expand_tab(&exstr, line);
4644 if (err)
4645 return err;
4647 /* Split the line into 3 segments, according to match offsets. */
4648 seg0 = strndup(exstr, rms);
4649 if (seg0 == NULL) {
4650 err = got_error_from_errno("strndup");
4651 goto done;
4653 seg1 = strndup(exstr + rms, rme - rms);
4654 if (seg1 == NULL) {
4655 err = got_error_from_errno("strndup");
4656 goto done;
4658 seg2 = strdup(exstr + rme);
4659 if (seg2 == NULL) {
4660 err = got_error_from_errno("strndup");
4661 goto done;
4664 /* draw up to matched token if we haven't scrolled past it */
4665 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4666 col_tab_align, 1);
4667 if (err)
4668 goto done;
4669 n = MAX(width0 - skipcol, 0);
4670 if (n) {
4671 free(wline);
4672 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4673 wlimit, col_tab_align, 1);
4674 if (err)
4675 goto done;
4676 waddwstr(window, &wline[scrollx]);
4677 wlimit -= width;
4678 *wtotal += width;
4681 if (wlimit > 0) {
4682 int i = 0, w = 0;
4683 size_t wlen;
4685 free(wline);
4686 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4687 col_tab_align, 1);
4688 if (err)
4689 goto done;
4690 wlen = wcslen(wline);
4691 while (i < wlen) {
4692 width = wcwidth(wline[i]);
4693 if (width == -1) {
4694 /* should not happen, tabs are expanded */
4695 err = got_error(GOT_ERR_RANGE);
4696 goto done;
4698 if (width0 + w + width > skipcol)
4699 break;
4700 w += width;
4701 i++;
4703 /* draw (visible part of) matched token (if scrolled into it) */
4704 if (width1 - w > 0) {
4705 wattron(window, A_STANDOUT);
4706 waddwstr(window, &wline[i]);
4707 wattroff(window, A_STANDOUT);
4708 wlimit -= (width1 - w);
4709 *wtotal += (width1 - w);
4713 if (wlimit > 0) { /* draw rest of line */
4714 free(wline);
4715 if (skipcol > width0 + width1) {
4716 err = format_line(&wline, &width2, &scrollx, seg2,
4717 skipcol - (width0 + width1), wlimit,
4718 col_tab_align, 1);
4719 if (err)
4720 goto done;
4721 waddwstr(window, &wline[scrollx]);
4722 } else {
4723 err = format_line(&wline, &width2, NULL, seg2, 0,
4724 wlimit, col_tab_align, 1);
4725 if (err)
4726 goto done;
4727 waddwstr(window, wline);
4729 *wtotal += width2;
4731 done:
4732 free(wline);
4733 free(exstr);
4734 free(seg0);
4735 free(seg1);
4736 free(seg2);
4737 return err;
4740 static int
4741 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4743 FILE *f = NULL;
4744 int *eof, *first, *selected;
4746 if (view->type == TOG_VIEW_DIFF) {
4747 struct tog_diff_view_state *s = &view->state.diff;
4749 first = &s->first_displayed_line;
4750 selected = first;
4751 eof = &s->eof;
4752 f = s->f;
4753 } else if (view->type == TOG_VIEW_HELP) {
4754 struct tog_help_view_state *s = &view->state.help;
4756 first = &s->first_displayed_line;
4757 selected = first;
4758 eof = &s->eof;
4759 f = s->f;
4760 } else if (view->type == TOG_VIEW_BLAME) {
4761 struct tog_blame_view_state *s = &view->state.blame;
4763 first = &s->first_displayed_line;
4764 selected = &s->selected_line;
4765 eof = &s->eof;
4766 f = s->blame.f;
4767 } else
4768 return 0;
4770 /* Center gline in the middle of the page like vi(1). */
4771 if (*lineno < view->gline - (view->nlines - 3) / 2)
4772 return 0;
4773 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4774 rewind(f);
4775 *eof = 0;
4776 *first = 1;
4777 *lineno = 0;
4778 *nprinted = 0;
4779 return 0;
4782 *selected = view->gline <= (view->nlines - 3) / 2 ?
4783 view->gline : (view->nlines - 3) / 2 + 1;
4784 view->gline = 0;
4786 return 1;
4789 static const struct got_error *
4790 draw_file(struct tog_view *view, const char *header)
4792 struct tog_diff_view_state *s = &view->state.diff;
4793 regmatch_t *regmatch = &view->regmatch;
4794 const struct got_error *err;
4795 int nprinted = 0;
4796 char *line;
4797 size_t linesize = 0;
4798 ssize_t linelen;
4799 wchar_t *wline;
4800 int width;
4801 int max_lines = view->nlines;
4802 int nlines = s->nlines;
4803 off_t line_offset;
4805 s->lineno = s->first_displayed_line - 1;
4806 line_offset = s->lines[s->first_displayed_line - 1].offset;
4807 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4808 return got_error_from_errno("fseek");
4810 werase(view->window);
4812 if (view->gline > s->nlines - 1)
4813 view->gline = s->nlines - 1;
4815 if (header) {
4816 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4817 1 : view->gline - (view->nlines - 3) / 2 :
4818 s->lineno + s->selected_line;
4820 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4821 return got_error_from_errno("asprintf");
4822 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4823 0, 0);
4824 free(line);
4825 if (err)
4826 return err;
4828 if (view_needs_focus_indication(view))
4829 wstandout(view->window);
4830 waddwstr(view->window, wline);
4831 free(wline);
4832 wline = NULL;
4833 while (width++ < view->ncols)
4834 waddch(view->window, ' ');
4835 if (view_needs_focus_indication(view))
4836 wstandend(view->window);
4838 if (max_lines <= 1)
4839 return NULL;
4840 max_lines--;
4843 s->eof = 0;
4844 view->maxx = 0;
4845 line = NULL;
4846 while (max_lines > 0 && nprinted < max_lines) {
4847 enum got_diff_line_type linetype;
4848 attr_t attr = 0;
4850 linelen = getline(&line, &linesize, s->f);
4851 if (linelen == -1) {
4852 if (feof(s->f)) {
4853 s->eof = 1;
4854 break;
4856 free(line);
4857 return got_ferror(s->f, GOT_ERR_IO);
4860 if (++s->lineno < s->first_displayed_line)
4861 continue;
4862 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4863 continue;
4864 if (s->lineno == view->hiline)
4865 attr = A_STANDOUT;
4867 /* Set view->maxx based on full line length. */
4868 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4869 view->x ? 1 : 0);
4870 if (err) {
4871 free(line);
4872 return err;
4874 view->maxx = MAX(view->maxx, width);
4875 free(wline);
4876 wline = NULL;
4878 linetype = s->lines[s->lineno].type;
4879 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4880 linetype < GOT_DIFF_LINE_CONTEXT)
4881 attr |= COLOR_PAIR(linetype);
4882 if (attr)
4883 wattron(view->window, attr);
4884 if (s->first_displayed_line + nprinted == s->matched_line &&
4885 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4886 err = add_matched_line(&width, line, view->ncols, 0,
4887 view->window, view->x, regmatch);
4888 if (err) {
4889 free(line);
4890 return err;
4892 } else {
4893 int skip;
4894 err = format_line(&wline, &width, &skip, line,
4895 view->x, view->ncols, 0, view->x ? 1 : 0);
4896 if (err) {
4897 free(line);
4898 return err;
4900 waddwstr(view->window, &wline[skip]);
4901 free(wline);
4902 wline = NULL;
4904 if (s->lineno == view->hiline) {
4905 /* highlight full gline length */
4906 while (width++ < view->ncols)
4907 waddch(view->window, ' ');
4908 } else {
4909 if (width <= view->ncols - 1)
4910 waddch(view->window, '\n');
4912 if (attr)
4913 wattroff(view->window, attr);
4914 if (++nprinted == 1)
4915 s->first_displayed_line = s->lineno;
4917 free(line);
4918 if (nprinted >= 1)
4919 s->last_displayed_line = s->first_displayed_line +
4920 (nprinted - 1);
4921 else
4922 s->last_displayed_line = s->first_displayed_line;
4924 view_border(view);
4926 if (s->eof) {
4927 while (nprinted < view->nlines) {
4928 waddch(view->window, '\n');
4929 nprinted++;
4932 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4933 view->ncols, 0, 0);
4934 if (err) {
4935 return err;
4938 wstandout(view->window);
4939 waddwstr(view->window, wline);
4940 free(wline);
4941 wline = NULL;
4942 wstandend(view->window);
4945 return NULL;
4948 static char *
4949 get_datestr(time_t *time, char *datebuf)
4951 struct tm mytm, *tm;
4952 char *p, *s;
4954 tm = gmtime_r(time, &mytm);
4955 if (tm == NULL)
4956 return NULL;
4957 s = asctime_r(tm, datebuf);
4958 if (s == NULL)
4959 return NULL;
4960 p = strchr(s, '\n');
4961 if (p)
4962 *p = '\0';
4963 return s;
4966 static const struct got_error *
4967 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4968 off_t off, uint8_t type)
4970 struct got_diff_line *p;
4972 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4973 if (p == NULL)
4974 return got_error_from_errno("reallocarray");
4975 *lines = p;
4976 (*lines)[*nlines].offset = off;
4977 (*lines)[*nlines].type = type;
4978 (*nlines)++;
4980 return NULL;
4983 static const struct got_error *
4984 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4985 struct got_diff_line *s_lines, size_t s_nlines)
4987 struct got_diff_line *p;
4988 char buf[BUFSIZ];
4989 size_t i, r;
4991 if (fseeko(src, 0L, SEEK_SET) == -1)
4992 return got_error_from_errno("fseeko");
4994 for (;;) {
4995 r = fread(buf, 1, sizeof(buf), src);
4996 if (r == 0) {
4997 if (ferror(src))
4998 return got_error_from_errno("fread");
4999 if (feof(src))
5000 break;
5002 if (fwrite(buf, 1, r, dst) != r)
5003 return got_ferror(dst, GOT_ERR_IO);
5006 if (s_nlines == 0 && *d_nlines == 0)
5007 return NULL;
5010 * If commit info was in dst, increment line offsets
5011 * of the appended diff content, but skip s_lines[0]
5012 * because offset zero is already in *d_lines.
5014 if (*d_nlines > 0) {
5015 for (i = 1; i < s_nlines; ++i)
5016 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
5018 if (s_nlines > 0) {
5019 --s_nlines;
5020 ++s_lines;
5024 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
5025 if (p == NULL) {
5026 /* d_lines is freed in close_diff_view() */
5027 return got_error_from_errno("reallocarray");
5030 *d_lines = p;
5032 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
5033 *d_nlines += s_nlines;
5035 return NULL;
5038 static const struct got_error *
5039 write_commit_info(struct got_diff_line **lines, size_t *nlines,
5040 struct got_object_id *commit_id, struct got_reflist_head *refs,
5041 struct got_repository *repo, int ignore_ws, int force_text_diff,
5042 struct got_diffstat_cb_arg *dsa, FILE *outfile)
5044 const struct got_error *err = NULL;
5045 char datebuf[26], *datestr;
5046 struct got_commit_object *commit;
5047 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
5048 time_t committer_time;
5049 const char *author, *committer;
5050 char *refs_str = NULL;
5051 struct got_pathlist_entry *pe;
5052 off_t outoff = 0;
5053 int n;
5055 err = build_refs_str(&refs_str, refs, commit_id, repo);
5056 if (err)
5057 return err;
5059 err = got_object_open_as_commit(&commit, repo, commit_id);
5060 if (err)
5061 return err;
5063 err = got_object_id_str(&id_str, commit_id);
5064 if (err) {
5065 err = got_error_from_errno("got_object_id_str");
5066 goto done;
5069 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
5070 if (err)
5071 goto done;
5073 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
5074 refs_str ? refs_str : "", refs_str ? ")" : "");
5075 if (n < 0) {
5076 err = got_error_from_errno("fprintf");
5077 goto done;
5079 outoff += n;
5080 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
5081 if (err)
5082 goto done;
5084 n = fprintf(outfile, "from: %s\n",
5085 got_object_commit_get_author(commit));
5086 if (n < 0) {
5087 err = got_error_from_errno("fprintf");
5088 goto done;
5090 outoff += n;
5091 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
5092 if (err)
5093 goto done;
5095 author = got_object_commit_get_author(commit);
5096 committer = got_object_commit_get_committer(commit);
5097 if (strcmp(author, committer) != 0) {
5098 n = fprintf(outfile, "via: %s\n", committer);
5099 if (n < 0) {
5100 err = got_error_from_errno("fprintf");
5101 goto done;
5103 outoff += n;
5104 err = add_line_metadata(lines, nlines, outoff,
5105 GOT_DIFF_LINE_AUTHOR);
5106 if (err)
5107 goto done;
5109 committer_time = got_object_commit_get_committer_time(commit);
5110 datestr = get_datestr(&committer_time, datebuf);
5111 if (datestr) {
5112 n = fprintf(outfile, "date: %s UTC\n", datestr);
5113 if (n < 0) {
5114 err = got_error_from_errno("fprintf");
5115 goto done;
5117 outoff += n;
5118 err = add_line_metadata(lines, nlines, outoff,
5119 GOT_DIFF_LINE_DATE);
5120 if (err)
5121 goto done;
5123 if (got_object_commit_get_nparents(commit) > 1) {
5124 const struct got_object_id_queue *parent_ids;
5125 struct got_object_qid *qid;
5126 int pn = 1;
5127 parent_ids = got_object_commit_get_parent_ids(commit);
5128 STAILQ_FOREACH(qid, parent_ids, entry) {
5129 err = got_object_id_str(&id_str, &qid->id);
5130 if (err)
5131 goto done;
5132 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5133 if (n < 0) {
5134 err = got_error_from_errno("fprintf");
5135 goto done;
5137 outoff += n;
5138 err = add_line_metadata(lines, nlines, outoff,
5139 GOT_DIFF_LINE_META);
5140 if (err)
5141 goto done;
5142 free(id_str);
5143 id_str = NULL;
5147 err = got_object_commit_get_logmsg(&logmsg, commit);
5148 if (err)
5149 goto done;
5150 s = logmsg;
5151 while ((line = strsep(&s, "\n")) != NULL) {
5152 n = fprintf(outfile, "%s\n", line);
5153 if (n < 0) {
5154 err = got_error_from_errno("fprintf");
5155 goto done;
5157 outoff += n;
5158 err = add_line_metadata(lines, nlines, outoff,
5159 GOT_DIFF_LINE_LOGMSG);
5160 if (err)
5161 goto done;
5164 TAILQ_FOREACH(pe, dsa->paths, entry) {
5165 struct got_diff_changed_path *cp = pe->data;
5166 int pad = dsa->max_path_len - pe->path_len + 1;
5168 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5169 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5170 dsa->rm_cols + 1, cp->rm);
5171 if (n < 0) {
5172 err = got_error_from_errno("fprintf");
5173 goto done;
5175 outoff += n;
5176 err = add_line_metadata(lines, nlines, outoff,
5177 GOT_DIFF_LINE_CHANGES);
5178 if (err)
5179 goto done;
5182 fputc('\n', outfile);
5183 outoff++;
5184 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5185 if (err)
5186 goto done;
5188 n = fprintf(outfile,
5189 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5190 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5191 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5192 if (n < 0) {
5193 err = got_error_from_errno("fprintf");
5194 goto done;
5196 outoff += n;
5197 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5198 if (err)
5199 goto done;
5201 fputc('\n', outfile);
5202 outoff++;
5203 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5204 done:
5205 free(id_str);
5206 free(logmsg);
5207 free(refs_str);
5208 got_object_commit_close(commit);
5209 if (err) {
5210 free(*lines);
5211 *lines = NULL;
5212 *nlines = 0;
5214 return err;
5217 static const struct got_error *
5218 create_diff(struct tog_diff_view_state *s)
5220 const struct got_error *err = NULL;
5221 FILE *f = NULL, *tmp_diff_file = NULL;
5222 int obj_type;
5223 struct got_diff_line *lines = NULL;
5224 struct got_pathlist_head changed_paths;
5226 TAILQ_INIT(&changed_paths);
5228 free(s->lines);
5229 s->lines = malloc(sizeof(*s->lines));
5230 if (s->lines == NULL)
5231 return got_error_from_errno("malloc");
5232 s->nlines = 0;
5234 f = got_opentemp();
5235 if (f == NULL) {
5236 err = got_error_from_errno("got_opentemp");
5237 goto done;
5239 tmp_diff_file = got_opentemp();
5240 if (tmp_diff_file == NULL) {
5241 err = got_error_from_errno("got_opentemp");
5242 goto done;
5244 if (s->f && fclose(s->f) == EOF) {
5245 err = got_error_from_errno("fclose");
5246 goto done;
5248 s->f = f;
5250 if (s->id1)
5251 err = got_object_get_type(&obj_type, s->repo, s->id1);
5252 else
5253 err = got_object_get_type(&obj_type, s->repo, s->id2);
5254 if (err)
5255 goto done;
5257 switch (obj_type) {
5258 case GOT_OBJ_TYPE_BLOB:
5259 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5260 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5261 s->label1, s->label2, tog_diff_algo, s->diff_context,
5262 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5263 s->f);
5264 break;
5265 case GOT_OBJ_TYPE_TREE:
5266 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5267 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5268 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5269 s->force_text_diff, NULL, s->repo, s->f);
5270 break;
5271 case GOT_OBJ_TYPE_COMMIT: {
5272 const struct got_object_id_queue *parent_ids;
5273 struct got_object_qid *pid;
5274 struct got_commit_object *commit2;
5275 struct got_reflist_head *refs;
5276 size_t nlines = 0;
5277 struct got_diffstat_cb_arg dsa = {
5278 0, 0, 0, 0, 0, 0,
5279 &changed_paths,
5280 s->ignore_whitespace,
5281 s->force_text_diff,
5282 tog_diff_algo
5285 lines = malloc(sizeof(*lines));
5286 if (lines == NULL) {
5287 err = got_error_from_errno("malloc");
5288 goto done;
5291 /* build diff first in tmp file then append to commit info */
5292 err = got_diff_objects_as_commits(&lines, &nlines,
5293 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5294 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5295 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5296 if (err)
5297 break;
5299 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5300 if (err)
5301 goto done;
5302 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5303 /* Show commit info if we're diffing to a parent/root commit. */
5304 if (s->id1 == NULL) {
5305 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5306 refs, s->repo, s->ignore_whitespace,
5307 s->force_text_diff, &dsa, s->f);
5308 if (err)
5309 goto done;
5310 } else {
5311 parent_ids = got_object_commit_get_parent_ids(commit2);
5312 STAILQ_FOREACH(pid, parent_ids, entry) {
5313 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5314 err = write_commit_info(&s->lines,
5315 &s->nlines, s->id2, refs, s->repo,
5316 s->ignore_whitespace,
5317 s->force_text_diff, &dsa, s->f);
5318 if (err)
5319 goto done;
5320 break;
5324 got_object_commit_close(commit2);
5326 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5327 lines, nlines);
5328 break;
5330 default:
5331 err = got_error(GOT_ERR_OBJ_TYPE);
5332 break;
5334 done:
5335 free(lines);
5336 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5337 if (s->f && fflush(s->f) != 0 && err == NULL)
5338 err = got_error_from_errno("fflush");
5339 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5340 err = got_error_from_errno("fclose");
5341 return err;
5344 static void
5345 diff_view_indicate_progress(struct tog_view *view)
5347 mvwaddstr(view->window, 0, 0, "diffing...");
5348 update_panels();
5349 doupdate();
5352 static const struct got_error *
5353 search_start_diff_view(struct tog_view *view)
5355 struct tog_diff_view_state *s = &view->state.diff;
5357 s->matched_line = 0;
5358 return NULL;
5361 static void
5362 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5363 size_t *nlines, int **first, int **last, int **match, int **selected)
5365 struct tog_diff_view_state *s = &view->state.diff;
5367 *f = s->f;
5368 *nlines = s->nlines;
5369 *line_offsets = NULL;
5370 *match = &s->matched_line;
5371 *first = &s->first_displayed_line;
5372 *last = &s->last_displayed_line;
5373 *selected = &s->selected_line;
5376 static const struct got_error *
5377 search_next_view_match(struct tog_view *view)
5379 const struct got_error *err = NULL;
5380 FILE *f;
5381 int lineno;
5382 char *line = NULL;
5383 size_t linesize = 0;
5384 ssize_t linelen;
5385 off_t *line_offsets;
5386 size_t nlines = 0;
5387 int *first, *last, *match, *selected;
5389 if (!view->search_setup)
5390 return got_error_msg(GOT_ERR_NOT_IMPL,
5391 "view search not supported");
5392 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5393 &match, &selected);
5395 if (!view->searching) {
5396 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5397 return NULL;
5400 if (*match) {
5401 if (view->searching == TOG_SEARCH_FORWARD)
5402 lineno = *first + 1;
5403 else
5404 lineno = *first - 1;
5405 } else
5406 lineno = *first - 1 + *selected;
5408 while (1) {
5409 off_t offset;
5411 if (lineno <= 0 || lineno > nlines) {
5412 if (*match == 0) {
5413 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5414 break;
5417 if (view->searching == TOG_SEARCH_FORWARD)
5418 lineno = 1;
5419 else
5420 lineno = nlines;
5423 offset = view->type == TOG_VIEW_DIFF ?
5424 view->state.diff.lines[lineno - 1].offset :
5425 line_offsets[lineno - 1];
5426 if (fseeko(f, offset, SEEK_SET) != 0) {
5427 free(line);
5428 return got_error_from_errno("fseeko");
5430 linelen = getline(&line, &linesize, f);
5431 if (linelen != -1) {
5432 char *exstr;
5433 err = expand_tab(&exstr, line);
5434 if (err)
5435 break;
5436 if (match_line(exstr, &view->regex, 1,
5437 &view->regmatch)) {
5438 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5439 *match = lineno;
5440 free(exstr);
5441 break;
5443 free(exstr);
5445 if (view->searching == TOG_SEARCH_FORWARD)
5446 lineno++;
5447 else
5448 lineno--;
5450 free(line);
5452 if (*match) {
5453 *first = *match;
5454 *selected = 1;
5457 return err;
5460 static const struct got_error *
5461 close_diff_view(struct tog_view *view)
5463 const struct got_error *err = NULL;
5464 struct tog_diff_view_state *s = &view->state.diff;
5466 free(s->id1);
5467 s->id1 = NULL;
5468 free(s->id2);
5469 s->id2 = NULL;
5470 if (s->f && fclose(s->f) == EOF)
5471 err = got_error_from_errno("fclose");
5472 s->f = NULL;
5473 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5474 err = got_error_from_errno("fclose");
5475 s->f1 = NULL;
5476 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5477 err = got_error_from_errno("fclose");
5478 s->f2 = NULL;
5479 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5480 err = got_error_from_errno("close");
5481 s->fd1 = -1;
5482 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5483 err = got_error_from_errno("close");
5484 s->fd2 = -1;
5485 free(s->lines);
5486 s->lines = NULL;
5487 s->nlines = 0;
5488 return err;
5491 static const struct got_error *
5492 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5493 struct got_object_id *id2, const char *label1, const char *label2,
5494 int diff_context, int ignore_whitespace, int force_text_diff,
5495 struct tog_view *parent_view, struct got_repository *repo)
5497 const struct got_error *err;
5498 struct tog_diff_view_state *s = &view->state.diff;
5500 memset(s, 0, sizeof(*s));
5501 s->fd1 = -1;
5502 s->fd2 = -1;
5504 if (id1 != NULL && id2 != NULL) {
5505 int type1, type2;
5507 err = got_object_get_type(&type1, repo, id1);
5508 if (err)
5509 goto done;
5510 err = got_object_get_type(&type2, repo, id2);
5511 if (err)
5512 goto done;
5514 if (type1 != type2) {
5515 err = got_error(GOT_ERR_OBJ_TYPE);
5516 goto done;
5519 s->first_displayed_line = 1;
5520 s->last_displayed_line = view->nlines;
5521 s->selected_line = 1;
5522 s->repo = repo;
5523 s->id1 = id1;
5524 s->id2 = id2;
5525 s->label1 = label1;
5526 s->label2 = label2;
5528 if (id1) {
5529 s->id1 = got_object_id_dup(id1);
5530 if (s->id1 == NULL) {
5531 err = got_error_from_errno("got_object_id_dup");
5532 goto done;
5534 } else
5535 s->id1 = NULL;
5537 s->id2 = got_object_id_dup(id2);
5538 if (s->id2 == NULL) {
5539 err = got_error_from_errno("got_object_id_dup");
5540 goto done;
5543 s->f1 = got_opentemp();
5544 if (s->f1 == NULL) {
5545 err = got_error_from_errno("got_opentemp");
5546 goto done;
5549 s->f2 = got_opentemp();
5550 if (s->f2 == NULL) {
5551 err = got_error_from_errno("got_opentemp");
5552 goto done;
5555 s->fd1 = got_opentempfd();
5556 if (s->fd1 == -1) {
5557 err = got_error_from_errno("got_opentempfd");
5558 goto done;
5561 s->fd2 = got_opentempfd();
5562 if (s->fd2 == -1) {
5563 err = got_error_from_errno("got_opentempfd");
5564 goto done;
5567 s->diff_context = diff_context;
5568 s->ignore_whitespace = ignore_whitespace;
5569 s->force_text_diff = force_text_diff;
5570 s->parent_view = parent_view;
5571 s->repo = repo;
5573 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5574 int rc;
5576 rc = init_pair(GOT_DIFF_LINE_MINUS,
5577 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5578 if (rc != ERR)
5579 rc = init_pair(GOT_DIFF_LINE_PLUS,
5580 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5581 if (rc != ERR)
5582 rc = init_pair(GOT_DIFF_LINE_HUNK,
5583 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5584 if (rc != ERR)
5585 rc = init_pair(GOT_DIFF_LINE_META,
5586 get_color_value("TOG_COLOR_DIFF_META"), -1);
5587 if (rc != ERR)
5588 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5589 get_color_value("TOG_COLOR_DIFF_META"), -1);
5590 if (rc != ERR)
5591 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5592 get_color_value("TOG_COLOR_DIFF_META"), -1);
5593 if (rc != ERR)
5594 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5595 get_color_value("TOG_COLOR_DIFF_META"), -1);
5596 if (rc != ERR)
5597 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5598 get_color_value("TOG_COLOR_AUTHOR"), -1);
5599 if (rc != ERR)
5600 rc = init_pair(GOT_DIFF_LINE_DATE,
5601 get_color_value("TOG_COLOR_DATE"), -1);
5602 if (rc == ERR) {
5603 err = got_error(GOT_ERR_RANGE);
5604 goto done;
5608 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5609 view_is_splitscreen(view))
5610 show_log_view(parent_view); /* draw border */
5611 diff_view_indicate_progress(view);
5613 err = create_diff(s);
5615 view->show = show_diff_view;
5616 view->input = input_diff_view;
5617 view->reset = reset_diff_view;
5618 view->close = close_diff_view;
5619 view->search_start = search_start_diff_view;
5620 view->search_setup = search_setup_diff_view;
5621 view->search_next = search_next_view_match;
5622 done:
5623 if (err) {
5624 if (view->close == NULL)
5625 close_diff_view(view);
5626 view_close(view);
5628 return err;
5631 static const struct got_error *
5632 show_diff_view(struct tog_view *view)
5634 const struct got_error *err;
5635 struct tog_diff_view_state *s = &view->state.diff;
5636 char *id_str1 = NULL, *id_str2, *header;
5637 const char *label1, *label2;
5639 if (s->id1) {
5640 err = got_object_id_str(&id_str1, s->id1);
5641 if (err)
5642 return err;
5643 label1 = s->label1 ? s->label1 : id_str1;
5644 } else
5645 label1 = "/dev/null";
5647 err = got_object_id_str(&id_str2, s->id2);
5648 if (err)
5649 return err;
5650 label2 = s->label2 ? s->label2 : id_str2;
5652 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5653 err = got_error_from_errno("asprintf");
5654 free(id_str1);
5655 free(id_str2);
5656 return err;
5658 free(id_str1);
5659 free(id_str2);
5661 err = draw_file(view, header);
5662 free(header);
5663 return err;
5666 static const struct got_error *
5667 set_selected_commit(struct tog_diff_view_state *s,
5668 struct commit_queue_entry *entry)
5670 const struct got_error *err;
5671 const struct got_object_id_queue *parent_ids;
5672 struct got_commit_object *selected_commit;
5673 struct got_object_qid *pid;
5675 free(s->id2);
5676 s->id2 = got_object_id_dup(entry->id);
5677 if (s->id2 == NULL)
5678 return got_error_from_errno("got_object_id_dup");
5680 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5681 if (err)
5682 return err;
5683 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5684 free(s->id1);
5685 pid = STAILQ_FIRST(parent_ids);
5686 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5687 got_object_commit_close(selected_commit);
5688 return NULL;
5691 static const struct got_error *
5692 reset_diff_view(struct tog_view *view)
5694 struct tog_diff_view_state *s = &view->state.diff;
5696 view->count = 0;
5697 wclear(view->window);
5698 s->first_displayed_line = 1;
5699 s->last_displayed_line = view->nlines;
5700 s->matched_line = 0;
5701 diff_view_indicate_progress(view);
5702 return create_diff(s);
5705 static void
5706 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5708 int start, i;
5710 i = start = s->first_displayed_line - 1;
5712 while (s->lines[i].type != type) {
5713 if (i == 0)
5714 i = s->nlines - 1;
5715 if (--i == start)
5716 return; /* do nothing, requested type not in file */
5719 s->selected_line = 1;
5720 s->first_displayed_line = i;
5723 static void
5724 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5726 int start, i;
5728 i = start = s->first_displayed_line + 1;
5730 while (s->lines[i].type != type) {
5731 if (i == s->nlines - 1)
5732 i = 0;
5733 if (++i == start)
5734 return; /* do nothing, requested type not in file */
5737 s->selected_line = 1;
5738 s->first_displayed_line = i;
5741 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5742 int, int, int);
5743 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5744 int, int);
5746 static const struct got_error *
5747 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5749 const struct got_error *err = NULL;
5750 struct tog_diff_view_state *s = &view->state.diff;
5751 struct tog_log_view_state *ls;
5752 struct commit_queue_entry *old_selected_entry;
5753 char *line = NULL;
5754 size_t linesize = 0;
5755 ssize_t linelen;
5756 int i, nscroll = view->nlines - 1, up = 0;
5758 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5760 switch (ch) {
5761 case '0':
5762 case '$':
5763 case KEY_RIGHT:
5764 case 'l':
5765 case KEY_LEFT:
5766 case 'h':
5767 horizontal_scroll_input(view, ch);
5768 break;
5769 case 'a':
5770 case 'w':
5771 if (ch == 'a') {
5772 s->force_text_diff = !s->force_text_diff;
5773 view->action = s->force_text_diff ?
5774 "force ASCII text enabled" :
5775 "force ASCII text disabled";
5777 else if (ch == 'w') {
5778 s->ignore_whitespace = !s->ignore_whitespace;
5779 view->action = s->ignore_whitespace ?
5780 "ignore whitespace enabled" :
5781 "ignore whitespace disabled";
5783 err = reset_diff_view(view);
5784 break;
5785 case 'g':
5786 case KEY_HOME:
5787 s->first_displayed_line = 1;
5788 view->count = 0;
5789 break;
5790 case 'G':
5791 case KEY_END:
5792 view->count = 0;
5793 if (s->eof)
5794 break;
5796 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5797 s->eof = 1;
5798 break;
5799 case 'k':
5800 case KEY_UP:
5801 case CTRL('p'):
5802 if (s->first_displayed_line > 1)
5803 s->first_displayed_line--;
5804 else
5805 view->count = 0;
5806 break;
5807 case CTRL('u'):
5808 case 'u':
5809 nscroll /= 2;
5810 /* FALL THROUGH */
5811 case KEY_PPAGE:
5812 case CTRL('b'):
5813 case 'b':
5814 if (s->first_displayed_line == 1) {
5815 view->count = 0;
5816 break;
5818 i = 0;
5819 while (i++ < nscroll && s->first_displayed_line > 1)
5820 s->first_displayed_line--;
5821 break;
5822 case 'j':
5823 case KEY_DOWN:
5824 case CTRL('n'):
5825 if (!s->eof)
5826 s->first_displayed_line++;
5827 else
5828 view->count = 0;
5829 break;
5830 case CTRL('d'):
5831 case 'd':
5832 nscroll /= 2;
5833 /* FALL THROUGH */
5834 case KEY_NPAGE:
5835 case CTRL('f'):
5836 case 'f':
5837 case ' ':
5838 if (s->eof) {
5839 view->count = 0;
5840 break;
5842 i = 0;
5843 while (!s->eof && i++ < nscroll) {
5844 linelen = getline(&line, &linesize, s->f);
5845 s->first_displayed_line++;
5846 if (linelen == -1) {
5847 if (feof(s->f)) {
5848 s->eof = 1;
5849 } else
5850 err = got_ferror(s->f, GOT_ERR_IO);
5851 break;
5854 free(line);
5855 break;
5856 case '(':
5857 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5858 break;
5859 case ')':
5860 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5861 break;
5862 case '{':
5863 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5864 break;
5865 case '}':
5866 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5867 break;
5868 case '[':
5869 if (s->diff_context > 0) {
5870 s->diff_context--;
5871 s->matched_line = 0;
5872 diff_view_indicate_progress(view);
5873 err = create_diff(s);
5874 if (s->first_displayed_line + view->nlines - 1 >
5875 s->nlines) {
5876 s->first_displayed_line = 1;
5877 s->last_displayed_line = view->nlines;
5879 } else
5880 view->count = 0;
5881 break;
5882 case ']':
5883 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5884 s->diff_context++;
5885 s->matched_line = 0;
5886 diff_view_indicate_progress(view);
5887 err = create_diff(s);
5888 } else
5889 view->count = 0;
5890 break;
5891 case '<':
5892 case ',':
5893 case 'K':
5894 up = 1;
5895 /* FALL THROUGH */
5896 case '>':
5897 case '.':
5898 case 'J':
5899 if (s->parent_view == NULL) {
5900 view->count = 0;
5901 break;
5903 s->parent_view->count = view->count;
5905 if (s->parent_view->type == TOG_VIEW_LOG) {
5906 ls = &s->parent_view->state.log;
5907 old_selected_entry = ls->selected_entry;
5909 err = input_log_view(NULL, s->parent_view,
5910 up ? KEY_UP : KEY_DOWN);
5911 if (err)
5912 break;
5913 view->count = s->parent_view->count;
5915 if (old_selected_entry == ls->selected_entry)
5916 break;
5918 err = set_selected_commit(s, ls->selected_entry);
5919 if (err)
5920 break;
5921 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5922 struct tog_blame_view_state *bs;
5923 struct got_object_id *id, *prev_id;
5925 bs = &s->parent_view->state.blame;
5926 prev_id = get_annotation_for_line(bs->blame.lines,
5927 bs->blame.nlines, bs->last_diffed_line);
5929 err = input_blame_view(&view, s->parent_view,
5930 up ? KEY_UP : KEY_DOWN);
5931 if (err)
5932 break;
5933 view->count = s->parent_view->count;
5935 if (prev_id == NULL)
5936 break;
5937 id = get_selected_commit_id(bs->blame.lines,
5938 bs->blame.nlines, bs->first_displayed_line,
5939 bs->selected_line);
5940 if (id == NULL)
5941 break;
5943 if (!got_object_id_cmp(prev_id, id))
5944 break;
5946 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5947 if (err)
5948 break;
5950 s->first_displayed_line = 1;
5951 s->last_displayed_line = view->nlines;
5952 s->matched_line = 0;
5953 view->x = 0;
5955 diff_view_indicate_progress(view);
5956 err = create_diff(s);
5957 break;
5958 default:
5959 view->count = 0;
5960 break;
5963 return err;
5966 static const struct got_error *
5967 cmd_diff(int argc, char *argv[])
5969 const struct got_error *error;
5970 struct got_repository *repo = NULL;
5971 struct got_worktree *worktree = NULL;
5972 struct got_object_id *id1 = NULL, *id2 = NULL;
5973 char *repo_path = NULL, *cwd = NULL;
5974 char *id_str1 = NULL, *id_str2 = NULL;
5975 char *keyword_idstr1 = NULL, *keyword_idstr2 = NULL;
5976 char *label1 = NULL, *label2 = NULL;
5977 int diff_context = 3, ignore_whitespace = 0;
5978 int ch, force_text_diff = 0;
5979 const char *errstr;
5980 struct tog_view *view;
5981 int *pack_fds = NULL;
5983 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5984 switch (ch) {
5985 case 'a':
5986 force_text_diff = 1;
5987 break;
5988 case 'C':
5989 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5990 &errstr);
5991 if (errstr != NULL)
5992 errx(1, "number of context lines is %s: %s",
5993 errstr, errstr);
5994 break;
5995 case 'r':
5996 repo_path = realpath(optarg, NULL);
5997 if (repo_path == NULL)
5998 return got_error_from_errno2("realpath",
5999 optarg);
6000 got_path_strip_trailing_slashes(repo_path);
6001 break;
6002 case 'w':
6003 ignore_whitespace = 1;
6004 break;
6005 default:
6006 usage_diff();
6007 /* NOTREACHED */
6011 argc -= optind;
6012 argv += optind;
6014 if (argc == 0) {
6015 usage_diff(); /* TODO show local worktree changes */
6016 } else if (argc == 2) {
6017 id_str1 = argv[0];
6018 id_str2 = argv[1];
6019 } else
6020 usage_diff();
6022 error = got_repo_pack_fds_open(&pack_fds);
6023 if (error)
6024 goto done;
6026 if (repo_path == NULL) {
6027 cwd = getcwd(NULL, 0);
6028 if (cwd == NULL)
6029 return got_error_from_errno("getcwd");
6030 error = got_worktree_open(&worktree, cwd, NULL);
6031 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6032 goto done;
6033 if (worktree)
6034 repo_path =
6035 strdup(got_worktree_get_repo_path(worktree));
6036 else
6037 repo_path = strdup(cwd);
6038 if (repo_path == NULL) {
6039 error = got_error_from_errno("strdup");
6040 goto done;
6044 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6045 if (error)
6046 goto done;
6048 init_curses();
6050 error = apply_unveil(got_repo_get_path(repo), NULL);
6051 if (error)
6052 goto done;
6054 error = tog_load_refs(repo, 0);
6055 if (error)
6056 goto done;
6058 if (id_str1 != NULL) {
6059 error = got_keyword_to_idstr(&keyword_idstr1, id_str1,
6060 repo, worktree);
6061 if (error != NULL)
6062 goto done;
6063 if (keyword_idstr1 != NULL)
6064 id_str1 = keyword_idstr1;
6066 if (id_str2 != NULL) {
6067 error = got_keyword_to_idstr(&keyword_idstr2, id_str2,
6068 repo, worktree);
6069 if (error != NULL)
6070 goto done;
6071 if (keyword_idstr2 != NULL)
6072 id_str2 = keyword_idstr2;
6075 error = got_repo_match_object_id(&id1, &label1, id_str1,
6076 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6077 if (error)
6078 goto done;
6080 error = got_repo_match_object_id(&id2, &label2, id_str2,
6081 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6082 if (error)
6083 goto done;
6085 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
6086 if (view == NULL) {
6087 error = got_error_from_errno("view_open");
6088 goto done;
6090 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
6091 ignore_whitespace, force_text_diff, NULL, repo);
6092 if (error)
6093 goto done;
6095 if (worktree) {
6096 error = set_tog_base_commit(repo, worktree);
6097 if (error != NULL)
6098 goto done;
6101 error = view_loop(view);
6103 done:
6104 free(tog_base_commit.id);
6105 free(keyword_idstr1);
6106 free(keyword_idstr2);
6107 free(label1);
6108 free(label2);
6109 free(repo_path);
6110 free(cwd);
6111 if (repo) {
6112 const struct got_error *close_err = got_repo_close(repo);
6113 if (error == NULL)
6114 error = close_err;
6116 if (worktree)
6117 got_worktree_close(worktree);
6118 if (pack_fds) {
6119 const struct got_error *pack_err =
6120 got_repo_pack_fds_close(pack_fds);
6121 if (error == NULL)
6122 error = pack_err;
6124 tog_free_refs();
6125 return error;
6128 __dead static void
6129 usage_blame(void)
6131 endwin();
6132 fprintf(stderr,
6133 "usage: %s blame [-c commit] [-r repository-path] path\n",
6134 getprogname());
6135 exit(1);
6138 struct tog_blame_line {
6139 int annotated;
6140 struct got_object_id *id;
6143 static const struct got_error *
6144 draw_blame(struct tog_view *view)
6146 struct tog_blame_view_state *s = &view->state.blame;
6147 struct tog_blame *blame = &s->blame;
6148 regmatch_t *regmatch = &view->regmatch;
6149 const struct got_error *err;
6150 int lineno = 0, nprinted = 0;
6151 char *line = NULL;
6152 size_t linesize = 0;
6153 ssize_t linelen;
6154 wchar_t *wline;
6155 int width;
6156 struct tog_blame_line *blame_line;
6157 struct got_object_id *prev_id = NULL;
6158 char *id_str;
6159 struct tog_color *tc;
6161 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6162 if (err)
6163 return err;
6165 rewind(blame->f);
6166 werase(view->window);
6168 if (asprintf(&line, "commit %s", id_str) == -1) {
6169 err = got_error_from_errno("asprintf");
6170 free(id_str);
6171 return err;
6174 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6175 free(line);
6176 line = NULL;
6177 if (err)
6178 return err;
6179 if (view_needs_focus_indication(view))
6180 wstandout(view->window);
6181 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6182 if (tc)
6183 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6184 waddwstr(view->window, wline);
6185 while (width++ < view->ncols)
6186 waddch(view->window, ' ');
6187 if (tc)
6188 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6189 if (view_needs_focus_indication(view))
6190 wstandend(view->window);
6191 free(wline);
6192 wline = NULL;
6194 if (view->gline > blame->nlines)
6195 view->gline = blame->nlines;
6197 if (tog_io.wait_for_ui) {
6198 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6199 int rc;
6201 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6202 if (rc)
6203 return got_error_set_errno(rc, "pthread_cond_wait");
6204 tog_io.wait_for_ui = 0;
6207 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6208 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6209 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6210 free(id_str);
6211 return got_error_from_errno("asprintf");
6213 free(id_str);
6214 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6215 free(line);
6216 line = NULL;
6217 if (err)
6218 return err;
6219 waddwstr(view->window, wline);
6220 free(wline);
6221 wline = NULL;
6222 if (width < view->ncols - 1)
6223 waddch(view->window, '\n');
6225 s->eof = 0;
6226 view->maxx = 0;
6227 while (nprinted < view->nlines - 2) {
6228 linelen = getline(&line, &linesize, blame->f);
6229 if (linelen == -1) {
6230 if (feof(blame->f)) {
6231 s->eof = 1;
6232 break;
6234 free(line);
6235 return got_ferror(blame->f, GOT_ERR_IO);
6237 if (++lineno < s->first_displayed_line)
6238 continue;
6239 if (view->gline && !gotoline(view, &lineno, &nprinted))
6240 continue;
6242 /* Set view->maxx based on full line length. */
6243 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6244 if (err) {
6245 free(line);
6246 return err;
6248 free(wline);
6249 wline = NULL;
6250 view->maxx = MAX(view->maxx, width);
6252 if (nprinted == s->selected_line - 1)
6253 wstandout(view->window);
6255 if (blame->nlines > 0) {
6256 blame_line = &blame->lines[lineno - 1];
6257 if (blame_line->annotated && prev_id &&
6258 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6259 !(nprinted == s->selected_line - 1)) {
6260 waddstr(view->window, " ");
6261 } else if (blame_line->annotated) {
6262 char *id_str;
6263 err = got_object_id_str(&id_str,
6264 blame_line->id);
6265 if (err) {
6266 free(line);
6267 return err;
6269 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6270 if (tc)
6271 wattr_on(view->window,
6272 COLOR_PAIR(tc->colorpair), NULL);
6273 wprintw(view->window, "%.8s", id_str);
6274 if (tc)
6275 wattr_off(view->window,
6276 COLOR_PAIR(tc->colorpair), NULL);
6277 free(id_str);
6278 prev_id = blame_line->id;
6279 } else {
6280 waddstr(view->window, "........");
6281 prev_id = NULL;
6283 } else {
6284 waddstr(view->window, "........");
6285 prev_id = NULL;
6288 if (nprinted == s->selected_line - 1)
6289 wstandend(view->window);
6290 waddstr(view->window, " ");
6292 if (view->ncols <= 9) {
6293 width = 9;
6294 } else if (s->first_displayed_line + nprinted ==
6295 s->matched_line &&
6296 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6297 err = add_matched_line(&width, line, view->ncols - 9, 9,
6298 view->window, view->x, regmatch);
6299 if (err) {
6300 free(line);
6301 return err;
6303 width += 9;
6304 } else {
6305 int skip;
6306 err = format_line(&wline, &width, &skip, line,
6307 view->x, view->ncols - 9, 9, 1);
6308 if (err) {
6309 free(line);
6310 return err;
6312 waddwstr(view->window, &wline[skip]);
6313 width += 9;
6314 free(wline);
6315 wline = NULL;
6318 if (width <= view->ncols - 1)
6319 waddch(view->window, '\n');
6320 if (++nprinted == 1)
6321 s->first_displayed_line = lineno;
6323 free(line);
6324 s->last_displayed_line = lineno;
6326 view_border(view);
6328 return NULL;
6331 static const struct got_error *
6332 blame_cb(void *arg, int nlines, int lineno,
6333 struct got_commit_object *commit, struct got_object_id *id)
6335 const struct got_error *err = NULL;
6336 struct tog_blame_cb_args *a = arg;
6337 struct tog_blame_line *line;
6338 int errcode;
6340 if (nlines != a->nlines ||
6341 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6342 return got_error(GOT_ERR_RANGE);
6344 errcode = pthread_mutex_lock(&tog_mutex);
6345 if (errcode)
6346 return got_error_set_errno(errcode, "pthread_mutex_lock");
6348 if (*a->quit) { /* user has quit the blame view */
6349 err = got_error(GOT_ERR_ITER_COMPLETED);
6350 goto done;
6353 if (lineno == -1)
6354 goto done; /* no change in this commit */
6356 line = &a->lines[lineno - 1];
6357 if (line->annotated)
6358 goto done;
6360 line->id = got_object_id_dup(id);
6361 if (line->id == NULL) {
6362 err = got_error_from_errno("got_object_id_dup");
6363 goto done;
6365 line->annotated = 1;
6366 done:
6367 errcode = pthread_mutex_unlock(&tog_mutex);
6368 if (errcode)
6369 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6370 return err;
6373 static void *
6374 blame_thread(void *arg)
6376 const struct got_error *err, *close_err;
6377 struct tog_blame_thread_args *ta = arg;
6378 struct tog_blame_cb_args *a = ta->cb_args;
6379 int errcode, fd1 = -1, fd2 = -1;
6380 FILE *f1 = NULL, *f2 = NULL;
6382 fd1 = got_opentempfd();
6383 if (fd1 == -1)
6384 return (void *)got_error_from_errno("got_opentempfd");
6386 fd2 = got_opentempfd();
6387 if (fd2 == -1) {
6388 err = got_error_from_errno("got_opentempfd");
6389 goto done;
6392 f1 = got_opentemp();
6393 if (f1 == NULL) {
6394 err = (void *)got_error_from_errno("got_opentemp");
6395 goto done;
6397 f2 = got_opentemp();
6398 if (f2 == NULL) {
6399 err = (void *)got_error_from_errno("got_opentemp");
6400 goto done;
6403 err = block_signals_used_by_main_thread();
6404 if (err)
6405 goto done;
6407 err = got_blame(ta->path, a->commit_id, ta->repo,
6408 tog_diff_algo, blame_cb, ta->cb_args,
6409 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6410 if (err && err->code == GOT_ERR_CANCELLED)
6411 err = NULL;
6413 errcode = pthread_mutex_lock(&tog_mutex);
6414 if (errcode) {
6415 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6416 goto done;
6419 close_err = got_repo_close(ta->repo);
6420 if (err == NULL)
6421 err = close_err;
6422 ta->repo = NULL;
6423 *ta->complete = 1;
6425 if (tog_io.wait_for_ui) {
6426 errcode = pthread_cond_signal(&ta->blame_complete);
6427 if (errcode && err == NULL)
6428 err = got_error_set_errno(errcode,
6429 "pthread_cond_signal");
6432 errcode = pthread_mutex_unlock(&tog_mutex);
6433 if (errcode && err == NULL)
6434 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6436 done:
6437 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6438 err = got_error_from_errno("close");
6439 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6440 err = got_error_from_errno("close");
6441 if (f1 && fclose(f1) == EOF && err == NULL)
6442 err = got_error_from_errno("fclose");
6443 if (f2 && fclose(f2) == EOF && err == NULL)
6444 err = got_error_from_errno("fclose");
6446 return (void *)err;
6449 static struct got_object_id *
6450 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6451 int first_displayed_line, int selected_line)
6453 struct tog_blame_line *line;
6455 if (nlines <= 0)
6456 return NULL;
6458 line = &lines[first_displayed_line - 1 + selected_line - 1];
6459 if (!line->annotated)
6460 return NULL;
6462 return line->id;
6465 static struct got_object_id *
6466 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6467 int lineno)
6469 struct tog_blame_line *line;
6471 if (nlines <= 0 || lineno >= nlines)
6472 return NULL;
6474 line = &lines[lineno - 1];
6475 if (!line->annotated)
6476 return NULL;
6478 return line->id;
6481 static const struct got_error *
6482 stop_blame(struct tog_blame *blame)
6484 const struct got_error *err = NULL;
6485 int i;
6487 if (blame->thread) {
6488 int errcode;
6489 errcode = pthread_mutex_unlock(&tog_mutex);
6490 if (errcode)
6491 return got_error_set_errno(errcode,
6492 "pthread_mutex_unlock");
6493 errcode = pthread_join(blame->thread, (void **)&err);
6494 if (errcode)
6495 return got_error_set_errno(errcode, "pthread_join");
6496 errcode = pthread_mutex_lock(&tog_mutex);
6497 if (errcode)
6498 return got_error_set_errno(errcode,
6499 "pthread_mutex_lock");
6500 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6501 err = NULL;
6502 blame->thread = NULL;
6504 if (blame->thread_args.repo) {
6505 const struct got_error *close_err;
6506 close_err = got_repo_close(blame->thread_args.repo);
6507 if (err == NULL)
6508 err = close_err;
6509 blame->thread_args.repo = NULL;
6511 if (blame->f) {
6512 if (fclose(blame->f) == EOF && err == NULL)
6513 err = got_error_from_errno("fclose");
6514 blame->f = NULL;
6516 if (blame->lines) {
6517 for (i = 0; i < blame->nlines; i++)
6518 free(blame->lines[i].id);
6519 free(blame->lines);
6520 blame->lines = NULL;
6522 free(blame->cb_args.commit_id);
6523 blame->cb_args.commit_id = NULL;
6524 if (blame->pack_fds) {
6525 const struct got_error *pack_err =
6526 got_repo_pack_fds_close(blame->pack_fds);
6527 if (err == NULL)
6528 err = pack_err;
6529 blame->pack_fds = NULL;
6531 return err;
6534 static const struct got_error *
6535 cancel_blame_view(void *arg)
6537 const struct got_error *err = NULL;
6538 int *done = arg;
6539 int errcode;
6541 errcode = pthread_mutex_lock(&tog_mutex);
6542 if (errcode)
6543 return got_error_set_errno(errcode,
6544 "pthread_mutex_unlock");
6546 if (*done)
6547 err = got_error(GOT_ERR_CANCELLED);
6549 errcode = pthread_mutex_unlock(&tog_mutex);
6550 if (errcode)
6551 return got_error_set_errno(errcode,
6552 "pthread_mutex_lock");
6554 return err;
6557 static const struct got_error *
6558 run_blame(struct tog_view *view)
6560 struct tog_blame_view_state *s = &view->state.blame;
6561 struct tog_blame *blame = &s->blame;
6562 const struct got_error *err = NULL;
6563 struct got_commit_object *commit = NULL;
6564 struct got_blob_object *blob = NULL;
6565 struct got_repository *thread_repo = NULL;
6566 struct got_object_id *obj_id = NULL;
6567 int obj_type, fd = -1;
6568 int *pack_fds = NULL;
6570 err = got_object_open_as_commit(&commit, s->repo,
6571 &s->blamed_commit->id);
6572 if (err)
6573 return err;
6575 fd = got_opentempfd();
6576 if (fd == -1) {
6577 err = got_error_from_errno("got_opentempfd");
6578 goto done;
6581 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6582 if (err)
6583 goto done;
6585 err = got_object_get_type(&obj_type, s->repo, obj_id);
6586 if (err)
6587 goto done;
6589 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6590 err = got_error(GOT_ERR_OBJ_TYPE);
6591 goto done;
6594 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6595 if (err)
6596 goto done;
6597 blame->f = got_opentemp();
6598 if (blame->f == NULL) {
6599 err = got_error_from_errno("got_opentemp");
6600 goto done;
6602 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6603 &blame->line_offsets, blame->f, blob);
6604 if (err)
6605 goto done;
6606 if (blame->nlines == 0) {
6607 s->blame_complete = 1;
6608 goto done;
6611 /* Don't include \n at EOF in the blame line count. */
6612 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6613 blame->nlines--;
6615 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6616 if (blame->lines == NULL) {
6617 err = got_error_from_errno("calloc");
6618 goto done;
6621 err = got_repo_pack_fds_open(&pack_fds);
6622 if (err)
6623 goto done;
6624 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6625 pack_fds);
6626 if (err)
6627 goto done;
6629 blame->pack_fds = pack_fds;
6630 blame->cb_args.view = view;
6631 blame->cb_args.lines = blame->lines;
6632 blame->cb_args.nlines = blame->nlines;
6633 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6634 if (blame->cb_args.commit_id == NULL) {
6635 err = got_error_from_errno("got_object_id_dup");
6636 goto done;
6638 blame->cb_args.quit = &s->done;
6640 blame->thread_args.path = s->path;
6641 blame->thread_args.repo = thread_repo;
6642 blame->thread_args.cb_args = &blame->cb_args;
6643 blame->thread_args.complete = &s->blame_complete;
6644 blame->thread_args.cancel_cb = cancel_blame_view;
6645 blame->thread_args.cancel_arg = &s->done;
6646 s->blame_complete = 0;
6648 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6649 s->first_displayed_line = 1;
6650 s->last_displayed_line = view->nlines;
6651 s->selected_line = 1;
6653 s->matched_line = 0;
6655 done:
6656 if (commit)
6657 got_object_commit_close(commit);
6658 if (fd != -1 && close(fd) == -1 && err == NULL)
6659 err = got_error_from_errno("close");
6660 if (blob)
6661 got_object_blob_close(blob);
6662 free(obj_id);
6663 if (err)
6664 stop_blame(blame);
6665 return err;
6668 static const struct got_error *
6669 open_blame_view(struct tog_view *view, char *path,
6670 struct got_object_id *commit_id, struct got_repository *repo)
6672 const struct got_error *err = NULL;
6673 struct tog_blame_view_state *s = &view->state.blame;
6675 STAILQ_INIT(&s->blamed_commits);
6677 s->path = strdup(path);
6678 if (s->path == NULL)
6679 return got_error_from_errno("strdup");
6681 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6682 if (err) {
6683 free(s->path);
6684 return err;
6687 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6688 s->first_displayed_line = 1;
6689 s->last_displayed_line = view->nlines;
6690 s->selected_line = 1;
6691 s->blame_complete = 0;
6692 s->repo = repo;
6693 s->commit_id = commit_id;
6694 memset(&s->blame, 0, sizeof(s->blame));
6696 STAILQ_INIT(&s->colors);
6697 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6698 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6699 get_color_value("TOG_COLOR_COMMIT"));
6700 if (err)
6701 return err;
6704 view->show = show_blame_view;
6705 view->input = input_blame_view;
6706 view->reset = reset_blame_view;
6707 view->close = close_blame_view;
6708 view->search_start = search_start_blame_view;
6709 view->search_setup = search_setup_blame_view;
6710 view->search_next = search_next_view_match;
6712 if (using_mock_io) {
6713 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6714 int rc;
6716 rc = pthread_cond_init(&bta->blame_complete, NULL);
6717 if (rc)
6718 return got_error_set_errno(rc, "pthread_cond_init");
6721 return run_blame(view);
6724 static const struct got_error *
6725 close_blame_view(struct tog_view *view)
6727 const struct got_error *err = NULL;
6728 struct tog_blame_view_state *s = &view->state.blame;
6730 if (s->blame.thread)
6731 err = stop_blame(&s->blame);
6733 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6734 struct got_object_qid *blamed_commit;
6735 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6736 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6737 got_object_qid_free(blamed_commit);
6740 if (using_mock_io) {
6741 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6742 int rc;
6744 rc = pthread_cond_destroy(&bta->blame_complete);
6745 if (rc && err == NULL)
6746 err = got_error_set_errno(rc, "pthread_cond_destroy");
6749 free(s->path);
6750 free_colors(&s->colors);
6751 return err;
6754 static const struct got_error *
6755 search_start_blame_view(struct tog_view *view)
6757 struct tog_blame_view_state *s = &view->state.blame;
6759 s->matched_line = 0;
6760 return NULL;
6763 static void
6764 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6765 size_t *nlines, int **first, int **last, int **match, int **selected)
6767 struct tog_blame_view_state *s = &view->state.blame;
6769 *f = s->blame.f;
6770 *nlines = s->blame.nlines;
6771 *line_offsets = s->blame.line_offsets;
6772 *match = &s->matched_line;
6773 *first = &s->first_displayed_line;
6774 *last = &s->last_displayed_line;
6775 *selected = &s->selected_line;
6778 static const struct got_error *
6779 show_blame_view(struct tog_view *view)
6781 const struct got_error *err = NULL;
6782 struct tog_blame_view_state *s = &view->state.blame;
6783 int errcode;
6785 if (s->blame.thread == NULL && !s->blame_complete) {
6786 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6787 &s->blame.thread_args);
6788 if (errcode)
6789 return got_error_set_errno(errcode, "pthread_create");
6791 if (!using_mock_io)
6792 halfdelay(1); /* fast refresh while annotating */
6795 if (s->blame_complete && !using_mock_io)
6796 halfdelay(10); /* disable fast refresh */
6798 err = draw_blame(view);
6800 view_border(view);
6801 return err;
6804 static const struct got_error *
6805 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6806 struct got_repository *repo, struct got_object_id *id)
6808 struct tog_view *log_view;
6809 const struct got_error *err = NULL;
6811 *new_view = NULL;
6813 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6814 if (log_view == NULL)
6815 return got_error_from_errno("view_open");
6817 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6818 if (err)
6819 view_close(log_view);
6820 else
6821 *new_view = log_view;
6823 return err;
6826 static const struct got_error *
6827 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6829 const struct got_error *err = NULL, *thread_err = NULL;
6830 struct tog_view *diff_view;
6831 struct tog_blame_view_state *s = &view->state.blame;
6832 int eos, nscroll, begin_y = 0, begin_x = 0;
6834 eos = nscroll = view->nlines - 2;
6835 if (view_is_hsplit_top(view))
6836 --eos; /* border */
6838 switch (ch) {
6839 case '0':
6840 case '$':
6841 case KEY_RIGHT:
6842 case 'l':
6843 case KEY_LEFT:
6844 case 'h':
6845 horizontal_scroll_input(view, ch);
6846 break;
6847 case 'q':
6848 s->done = 1;
6849 break;
6850 case 'g':
6851 case KEY_HOME:
6852 s->selected_line = 1;
6853 s->first_displayed_line = 1;
6854 view->count = 0;
6855 break;
6856 case 'G':
6857 case KEY_END:
6858 if (s->blame.nlines < eos) {
6859 s->selected_line = s->blame.nlines;
6860 s->first_displayed_line = 1;
6861 } else {
6862 s->selected_line = eos;
6863 s->first_displayed_line = s->blame.nlines - (eos - 1);
6865 view->count = 0;
6866 break;
6867 case 'k':
6868 case KEY_UP:
6869 case CTRL('p'):
6870 if (s->selected_line > 1)
6871 s->selected_line--;
6872 else if (s->selected_line == 1 &&
6873 s->first_displayed_line > 1)
6874 s->first_displayed_line--;
6875 else
6876 view->count = 0;
6877 break;
6878 case CTRL('u'):
6879 case 'u':
6880 nscroll /= 2;
6881 /* FALL THROUGH */
6882 case KEY_PPAGE:
6883 case CTRL('b'):
6884 case 'b':
6885 if (s->first_displayed_line == 1) {
6886 if (view->count > 1)
6887 nscroll += nscroll;
6888 s->selected_line = MAX(1, s->selected_line - nscroll);
6889 view->count = 0;
6890 break;
6892 if (s->first_displayed_line > nscroll)
6893 s->first_displayed_line -= nscroll;
6894 else
6895 s->first_displayed_line = 1;
6896 break;
6897 case 'j':
6898 case KEY_DOWN:
6899 case CTRL('n'):
6900 if (s->selected_line < eos && s->first_displayed_line +
6901 s->selected_line <= s->blame.nlines)
6902 s->selected_line++;
6903 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6904 s->first_displayed_line++;
6905 else
6906 view->count = 0;
6907 break;
6908 case 'c':
6909 case 'p': {
6910 struct got_object_id *id = NULL;
6912 view->count = 0;
6913 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6914 s->first_displayed_line, s->selected_line);
6915 if (id == NULL)
6916 break;
6917 if (ch == 'p') {
6918 struct got_commit_object *commit, *pcommit;
6919 struct got_object_qid *pid;
6920 struct got_object_id *blob_id = NULL;
6921 int obj_type;
6922 err = got_object_open_as_commit(&commit,
6923 s->repo, id);
6924 if (err)
6925 break;
6926 pid = STAILQ_FIRST(
6927 got_object_commit_get_parent_ids(commit));
6928 if (pid == NULL) {
6929 got_object_commit_close(commit);
6930 break;
6932 /* Check if path history ends here. */
6933 err = got_object_open_as_commit(&pcommit,
6934 s->repo, &pid->id);
6935 if (err)
6936 break;
6937 err = got_object_id_by_path(&blob_id, s->repo,
6938 pcommit, s->path);
6939 got_object_commit_close(pcommit);
6940 if (err) {
6941 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6942 err = NULL;
6943 got_object_commit_close(commit);
6944 break;
6946 err = got_object_get_type(&obj_type, s->repo,
6947 blob_id);
6948 free(blob_id);
6949 /* Can't blame non-blob type objects. */
6950 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6951 got_object_commit_close(commit);
6952 break;
6954 err = got_object_qid_alloc(&s->blamed_commit,
6955 &pid->id);
6956 got_object_commit_close(commit);
6957 } else {
6958 if (got_object_id_cmp(id,
6959 &s->blamed_commit->id) == 0)
6960 break;
6961 err = got_object_qid_alloc(&s->blamed_commit,
6962 id);
6964 if (err)
6965 break;
6966 s->done = 1;
6967 thread_err = stop_blame(&s->blame);
6968 s->done = 0;
6969 if (thread_err)
6970 break;
6971 STAILQ_INSERT_HEAD(&s->blamed_commits,
6972 s->blamed_commit, entry);
6973 err = run_blame(view);
6974 if (err)
6975 break;
6976 break;
6978 case 'C': {
6979 struct got_object_qid *first;
6981 view->count = 0;
6982 first = STAILQ_FIRST(&s->blamed_commits);
6983 if (!got_object_id_cmp(&first->id, s->commit_id))
6984 break;
6985 s->done = 1;
6986 thread_err = stop_blame(&s->blame);
6987 s->done = 0;
6988 if (thread_err)
6989 break;
6990 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6991 got_object_qid_free(s->blamed_commit);
6992 s->blamed_commit =
6993 STAILQ_FIRST(&s->blamed_commits);
6994 err = run_blame(view);
6995 if (err)
6996 break;
6997 break;
6999 case 'L':
7000 view->count = 0;
7001 s->id_to_log = get_selected_commit_id(s->blame.lines,
7002 s->blame.nlines, s->first_displayed_line, s->selected_line);
7003 if (s->id_to_log)
7004 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7005 break;
7006 case KEY_ENTER:
7007 case '\r': {
7008 struct got_object_id *id = NULL;
7009 struct got_object_qid *pid;
7010 struct got_commit_object *commit = NULL;
7012 view->count = 0;
7013 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
7014 s->first_displayed_line, s->selected_line);
7015 if (id == NULL)
7016 break;
7017 err = got_object_open_as_commit(&commit, s->repo, id);
7018 if (err)
7019 break;
7020 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7021 if (*new_view) {
7022 /* traversed from diff view, release diff resources */
7023 err = close_diff_view(*new_view);
7024 if (err)
7025 break;
7026 diff_view = *new_view;
7027 } else {
7028 if (view_is_parent_view(view))
7029 view_get_split(view, &begin_y, &begin_x);
7031 diff_view = view_open(0, 0, begin_y, begin_x,
7032 TOG_VIEW_DIFF);
7033 if (diff_view == NULL) {
7034 got_object_commit_close(commit);
7035 err = got_error_from_errno("view_open");
7036 break;
7039 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
7040 id, NULL, NULL, 3, 0, 0, view, s->repo);
7041 got_object_commit_close(commit);
7042 if (err)
7043 break;
7044 s->last_diffed_line = s->first_displayed_line - 1 +
7045 s->selected_line;
7046 if (*new_view)
7047 break; /* still open from active diff view */
7048 if (view_is_parent_view(view) &&
7049 view->mode == TOG_VIEW_SPLIT_HRZN) {
7050 err = view_init_hsplit(view, begin_y);
7051 if (err)
7052 break;
7055 view->focussed = 0;
7056 diff_view->focussed = 1;
7057 diff_view->mode = view->mode;
7058 diff_view->nlines = view->lines - begin_y;
7059 if (view_is_parent_view(view)) {
7060 view_transfer_size(diff_view, view);
7061 err = view_close_child(view);
7062 if (err)
7063 break;
7064 err = view_set_child(view, diff_view);
7065 if (err)
7066 break;
7067 view->focus_child = 1;
7068 } else
7069 *new_view = diff_view;
7070 if (err)
7071 break;
7072 break;
7074 case CTRL('d'):
7075 case 'd':
7076 nscroll /= 2;
7077 /* FALL THROUGH */
7078 case KEY_NPAGE:
7079 case CTRL('f'):
7080 case 'f':
7081 case ' ':
7082 if (s->last_displayed_line >= s->blame.nlines &&
7083 s->selected_line >= MIN(s->blame.nlines,
7084 view->nlines - 2)) {
7085 view->count = 0;
7086 break;
7088 if (s->last_displayed_line >= s->blame.nlines &&
7089 s->selected_line < view->nlines - 2) {
7090 s->selected_line +=
7091 MIN(nscroll, s->last_displayed_line -
7092 s->first_displayed_line - s->selected_line + 1);
7094 if (s->last_displayed_line + nscroll <= s->blame.nlines)
7095 s->first_displayed_line += nscroll;
7096 else
7097 s->first_displayed_line =
7098 s->blame.nlines - (view->nlines - 3);
7099 break;
7100 case KEY_RESIZE:
7101 if (s->selected_line > view->nlines - 2) {
7102 s->selected_line = MIN(s->blame.nlines,
7103 view->nlines - 2);
7105 break;
7106 default:
7107 view->count = 0;
7108 break;
7110 return thread_err ? thread_err : err;
7113 static const struct got_error *
7114 reset_blame_view(struct tog_view *view)
7116 const struct got_error *err;
7117 struct tog_blame_view_state *s = &view->state.blame;
7119 view->count = 0;
7120 s->done = 1;
7121 err = stop_blame(&s->blame);
7122 s->done = 0;
7123 if (err)
7124 return err;
7125 return run_blame(view);
7128 static const struct got_error *
7129 cmd_blame(int argc, char *argv[])
7131 const struct got_error *error;
7132 struct got_repository *repo = NULL;
7133 struct got_worktree *worktree = NULL;
7134 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7135 char *link_target = NULL;
7136 struct got_object_id *commit_id = NULL;
7137 struct got_commit_object *commit = NULL;
7138 char *keyword_idstr = NULL, *commit_id_str = NULL;
7139 int ch;
7140 struct tog_view *view = NULL;
7141 int *pack_fds = NULL;
7143 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7144 switch (ch) {
7145 case 'c':
7146 commit_id_str = optarg;
7147 break;
7148 case 'r':
7149 repo_path = realpath(optarg, NULL);
7150 if (repo_path == NULL)
7151 return got_error_from_errno2("realpath",
7152 optarg);
7153 break;
7154 default:
7155 usage_blame();
7156 /* NOTREACHED */
7160 argc -= optind;
7161 argv += optind;
7163 if (argc != 1)
7164 usage_blame();
7166 error = got_repo_pack_fds_open(&pack_fds);
7167 if (error != NULL)
7168 goto done;
7170 if (repo_path == NULL) {
7171 cwd = getcwd(NULL, 0);
7172 if (cwd == NULL)
7173 return got_error_from_errno("getcwd");
7174 error = got_worktree_open(&worktree, cwd, NULL);
7175 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7176 goto done;
7177 if (worktree)
7178 repo_path =
7179 strdup(got_worktree_get_repo_path(worktree));
7180 else
7181 repo_path = strdup(cwd);
7182 if (repo_path == NULL) {
7183 error = got_error_from_errno("strdup");
7184 goto done;
7188 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7189 if (error != NULL)
7190 goto done;
7192 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7193 worktree);
7194 if (error)
7195 goto done;
7197 init_curses();
7199 error = apply_unveil(got_repo_get_path(repo), NULL);
7200 if (error)
7201 goto done;
7203 error = tog_load_refs(repo, 0);
7204 if (error)
7205 goto done;
7207 if (commit_id_str == NULL) {
7208 struct got_reference *head_ref;
7209 error = got_ref_open(&head_ref, repo, worktree ?
7210 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7211 if (error != NULL)
7212 goto done;
7213 error = got_ref_resolve(&commit_id, repo, head_ref);
7214 got_ref_close(head_ref);
7215 } else {
7216 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
7217 repo, worktree);
7218 if (error != NULL)
7219 goto done;
7220 if (keyword_idstr != NULL)
7221 commit_id_str = keyword_idstr;
7223 error = got_repo_match_object_id(&commit_id, NULL,
7224 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7226 if (error != NULL)
7227 goto done;
7229 error = got_object_open_as_commit(&commit, repo, commit_id);
7230 if (error)
7231 goto done;
7233 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7234 commit, repo);
7235 if (error)
7236 goto done;
7238 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7239 if (view == NULL) {
7240 error = got_error_from_errno("view_open");
7241 goto done;
7243 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7244 commit_id, repo);
7245 if (error != NULL) {
7246 if (view->close == NULL)
7247 close_blame_view(view);
7248 view_close(view);
7249 goto done;
7252 if (worktree) {
7253 error = set_tog_base_commit(repo, worktree);
7254 if (error != NULL)
7255 goto done;
7257 /* Release work tree lock. */
7258 got_worktree_close(worktree);
7259 worktree = NULL;
7262 error = view_loop(view);
7264 done:
7265 free(tog_base_commit.id);
7266 free(repo_path);
7267 free(in_repo_path);
7268 free(link_target);
7269 free(cwd);
7270 free(commit_id);
7271 free(keyword_idstr);
7272 if (commit)
7273 got_object_commit_close(commit);
7274 if (worktree)
7275 got_worktree_close(worktree);
7276 if (repo) {
7277 const struct got_error *close_err = got_repo_close(repo);
7278 if (error == NULL)
7279 error = close_err;
7281 if (pack_fds) {
7282 const struct got_error *pack_err =
7283 got_repo_pack_fds_close(pack_fds);
7284 if (error == NULL)
7285 error = pack_err;
7287 tog_free_refs();
7288 return error;
7291 static const struct got_error *
7292 draw_tree_entries(struct tog_view *view, const char *parent_path)
7294 struct tog_tree_view_state *s = &view->state.tree;
7295 const struct got_error *err = NULL;
7296 struct got_tree_entry *te;
7297 wchar_t *wline;
7298 char *index = NULL;
7299 struct tog_color *tc;
7300 int width, n, nentries, scrollx, i = 1;
7301 int limit = view->nlines;
7303 s->ndisplayed = 0;
7304 if (view_is_hsplit_top(view))
7305 --limit; /* border */
7307 werase(view->window);
7309 if (limit == 0)
7310 return NULL;
7312 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7313 0, 0);
7314 if (err)
7315 return err;
7316 if (view_needs_focus_indication(view))
7317 wstandout(view->window);
7318 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7319 if (tc)
7320 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7321 waddwstr(view->window, wline);
7322 free(wline);
7323 wline = NULL;
7324 while (width++ < view->ncols)
7325 waddch(view->window, ' ');
7326 if (tc)
7327 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7328 if (view_needs_focus_indication(view))
7329 wstandend(view->window);
7330 if (--limit <= 0)
7331 return NULL;
7333 i += s->selected;
7334 if (s->first_displayed_entry) {
7335 i += got_tree_entry_get_index(s->first_displayed_entry);
7336 if (s->tree != s->root)
7337 ++i; /* account for ".." entry */
7339 nentries = got_object_tree_get_nentries(s->tree);
7340 if (asprintf(&index, "[%d/%d] %s",
7341 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7342 return got_error_from_errno("asprintf");
7343 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7344 free(index);
7345 if (err)
7346 return err;
7347 waddwstr(view->window, wline);
7348 free(wline);
7349 wline = NULL;
7350 if (width < view->ncols - 1)
7351 waddch(view->window, '\n');
7352 if (--limit <= 0)
7353 return NULL;
7354 waddch(view->window, '\n');
7355 if (--limit <= 0)
7356 return NULL;
7358 if (s->first_displayed_entry == NULL) {
7359 te = got_object_tree_get_first_entry(s->tree);
7360 if (s->selected == 0) {
7361 if (view->focussed)
7362 wstandout(view->window);
7363 s->selected_entry = NULL;
7365 waddstr(view->window, " ..\n"); /* parent directory */
7366 if (s->selected == 0 && view->focussed)
7367 wstandend(view->window);
7368 s->ndisplayed++;
7369 if (--limit <= 0)
7370 return NULL;
7371 n = 1;
7372 } else {
7373 n = 0;
7374 te = s->first_displayed_entry;
7377 view->maxx = 0;
7378 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7379 char *line = NULL, *id_str = NULL, *link_target = NULL;
7380 const char *modestr = "";
7381 mode_t mode;
7383 te = got_object_tree_get_entry(s->tree, i);
7384 mode = got_tree_entry_get_mode(te);
7386 if (s->show_ids) {
7387 err = got_object_id_str(&id_str,
7388 got_tree_entry_get_id(te));
7389 if (err)
7390 return got_error_from_errno(
7391 "got_object_id_str");
7393 if (got_object_tree_entry_is_submodule(te))
7394 modestr = "$";
7395 else if (S_ISLNK(mode)) {
7396 int i;
7398 err = got_tree_entry_get_symlink_target(&link_target,
7399 te, s->repo);
7400 if (err) {
7401 free(id_str);
7402 return err;
7404 for (i = 0; link_target[i] != '\0'; i++) {
7405 if (!isprint((unsigned char)link_target[i]))
7406 link_target[i] = '?';
7408 modestr = "@";
7410 else if (S_ISDIR(mode))
7411 modestr = "/";
7412 else if (mode & S_IXUSR)
7413 modestr = "*";
7414 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7415 got_tree_entry_get_name(te), modestr,
7416 link_target ? " -> ": "",
7417 link_target ? link_target : "") == -1) {
7418 free(id_str);
7419 free(link_target);
7420 return got_error_from_errno("asprintf");
7422 free(id_str);
7423 free(link_target);
7425 /* use full line width to determine view->maxx */
7426 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7427 if (err) {
7428 free(line);
7429 break;
7431 view->maxx = MAX(view->maxx, width);
7432 free(wline);
7433 wline = NULL;
7435 err = format_line(&wline, &width, &scrollx, line, view->x,
7436 view->ncols, 0, 0);
7437 if (err) {
7438 free(line);
7439 break;
7441 if (n == s->selected) {
7442 if (view->focussed)
7443 wstandout(view->window);
7444 s->selected_entry = te;
7446 tc = match_color(&s->colors, line);
7447 if (tc)
7448 wattr_on(view->window,
7449 COLOR_PAIR(tc->colorpair), NULL);
7450 waddwstr(view->window, &wline[scrollx]);
7451 if (tc)
7452 wattr_off(view->window,
7453 COLOR_PAIR(tc->colorpair), NULL);
7454 if (width < view->ncols)
7455 waddch(view->window, '\n');
7456 if (n == s->selected && view->focussed)
7457 wstandend(view->window);
7458 free(line);
7459 free(wline);
7460 wline = NULL;
7461 n++;
7462 s->ndisplayed++;
7463 s->last_displayed_entry = te;
7464 if (--limit <= 0)
7465 break;
7468 return err;
7471 static void
7472 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7474 struct got_tree_entry *te;
7475 int isroot = s->tree == s->root;
7476 int i = 0;
7478 if (s->first_displayed_entry == NULL)
7479 return;
7481 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7482 while (i++ < maxscroll) {
7483 if (te == NULL) {
7484 if (!isroot)
7485 s->first_displayed_entry = NULL;
7486 break;
7488 s->first_displayed_entry = te;
7489 te = got_tree_entry_get_prev(s->tree, te);
7493 static const struct got_error *
7494 tree_scroll_down(struct tog_view *view, int maxscroll)
7496 struct tog_tree_view_state *s = &view->state.tree;
7497 struct got_tree_entry *next, *last;
7498 int n = 0;
7500 if (s->first_displayed_entry)
7501 next = got_tree_entry_get_next(s->tree,
7502 s->first_displayed_entry);
7503 else
7504 next = got_object_tree_get_first_entry(s->tree);
7506 last = s->last_displayed_entry;
7507 while (next && n++ < maxscroll) {
7508 if (last) {
7509 s->last_displayed_entry = last;
7510 last = got_tree_entry_get_next(s->tree, last);
7512 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7513 s->first_displayed_entry = next;
7514 next = got_tree_entry_get_next(s->tree, next);
7518 return NULL;
7521 static const struct got_error *
7522 tree_entry_path(char **path, struct tog_parent_trees *parents,
7523 struct got_tree_entry *te)
7525 const struct got_error *err = NULL;
7526 struct tog_parent_tree *pt;
7527 size_t len = 2; /* for leading slash and NUL */
7529 TAILQ_FOREACH(pt, parents, entry)
7530 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7531 + 1 /* slash */;
7532 if (te)
7533 len += strlen(got_tree_entry_get_name(te));
7535 *path = calloc(1, len);
7536 if (path == NULL)
7537 return got_error_from_errno("calloc");
7539 (*path)[0] = '/';
7540 pt = TAILQ_LAST(parents, tog_parent_trees);
7541 while (pt) {
7542 const char *name = got_tree_entry_get_name(pt->selected_entry);
7543 if (strlcat(*path, name, len) >= len) {
7544 err = got_error(GOT_ERR_NO_SPACE);
7545 goto done;
7547 if (strlcat(*path, "/", len) >= len) {
7548 err = got_error(GOT_ERR_NO_SPACE);
7549 goto done;
7551 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7553 if (te) {
7554 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7555 err = got_error(GOT_ERR_NO_SPACE);
7556 goto done;
7559 done:
7560 if (err) {
7561 free(*path);
7562 *path = NULL;
7564 return err;
7567 static const struct got_error *
7568 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7569 struct got_tree_entry *te, struct tog_parent_trees *parents,
7570 struct got_object_id *commit_id, struct got_repository *repo)
7572 const struct got_error *err = NULL;
7573 char *path;
7574 struct tog_view *blame_view;
7576 *new_view = NULL;
7578 err = tree_entry_path(&path, parents, te);
7579 if (err)
7580 return err;
7582 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7583 if (blame_view == NULL) {
7584 err = got_error_from_errno("view_open");
7585 goto done;
7588 err = open_blame_view(blame_view, path, commit_id, repo);
7589 if (err) {
7590 if (err->code == GOT_ERR_CANCELLED)
7591 err = NULL;
7592 view_close(blame_view);
7593 } else
7594 *new_view = blame_view;
7595 done:
7596 free(path);
7597 return err;
7600 static const struct got_error *
7601 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7602 struct tog_tree_view_state *s)
7604 struct tog_view *log_view;
7605 const struct got_error *err = NULL;
7606 char *path;
7608 *new_view = NULL;
7610 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7611 if (log_view == NULL)
7612 return got_error_from_errno("view_open");
7614 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7615 if (err)
7616 return err;
7618 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7619 path, 0);
7620 if (err)
7621 view_close(log_view);
7622 else
7623 *new_view = log_view;
7624 free(path);
7625 return err;
7628 static const struct got_error *
7629 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7630 const char *head_ref_name, struct got_repository *repo)
7632 const struct got_error *err = NULL;
7633 char *commit_id_str = NULL;
7634 struct tog_tree_view_state *s = &view->state.tree;
7635 struct got_commit_object *commit = NULL;
7637 TAILQ_INIT(&s->parents);
7638 STAILQ_INIT(&s->colors);
7640 s->commit_id = got_object_id_dup(commit_id);
7641 if (s->commit_id == NULL) {
7642 err = got_error_from_errno("got_object_id_dup");
7643 goto done;
7646 err = got_object_open_as_commit(&commit, repo, commit_id);
7647 if (err)
7648 goto done;
7651 * The root is opened here and will be closed when the view is closed.
7652 * Any visited subtrees and their path-wise parents are opened and
7653 * closed on demand.
7655 err = got_object_open_as_tree(&s->root, repo,
7656 got_object_commit_get_tree_id(commit));
7657 if (err)
7658 goto done;
7659 s->tree = s->root;
7661 err = got_object_id_str(&commit_id_str, commit_id);
7662 if (err != NULL)
7663 goto done;
7665 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7666 err = got_error_from_errno("asprintf");
7667 goto done;
7670 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7671 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7672 if (head_ref_name) {
7673 s->head_ref_name = strdup(head_ref_name);
7674 if (s->head_ref_name == NULL) {
7675 err = got_error_from_errno("strdup");
7676 goto done;
7679 s->repo = repo;
7681 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7682 err = add_color(&s->colors, "\\$$",
7683 TOG_COLOR_TREE_SUBMODULE,
7684 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7685 if (err)
7686 goto done;
7687 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7688 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7689 if (err)
7690 goto done;
7691 err = add_color(&s->colors, "/$",
7692 TOG_COLOR_TREE_DIRECTORY,
7693 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7694 if (err)
7695 goto done;
7697 err = add_color(&s->colors, "\\*$",
7698 TOG_COLOR_TREE_EXECUTABLE,
7699 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7700 if (err)
7701 goto done;
7703 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7704 get_color_value("TOG_COLOR_COMMIT"));
7705 if (err)
7706 goto done;
7709 view->show = show_tree_view;
7710 view->input = input_tree_view;
7711 view->close = close_tree_view;
7712 view->search_start = search_start_tree_view;
7713 view->search_next = search_next_tree_view;
7714 done:
7715 free(commit_id_str);
7716 if (commit)
7717 got_object_commit_close(commit);
7718 if (err) {
7719 if (view->close == NULL)
7720 close_tree_view(view);
7721 view_close(view);
7723 return err;
7726 static const struct got_error *
7727 close_tree_view(struct tog_view *view)
7729 struct tog_tree_view_state *s = &view->state.tree;
7731 free_colors(&s->colors);
7732 free(s->tree_label);
7733 s->tree_label = NULL;
7734 free(s->commit_id);
7735 s->commit_id = NULL;
7736 free(s->head_ref_name);
7737 s->head_ref_name = NULL;
7738 while (!TAILQ_EMPTY(&s->parents)) {
7739 struct tog_parent_tree *parent;
7740 parent = TAILQ_FIRST(&s->parents);
7741 TAILQ_REMOVE(&s->parents, parent, entry);
7742 if (parent->tree != s->root)
7743 got_object_tree_close(parent->tree);
7744 free(parent);
7747 if (s->tree != NULL && s->tree != s->root)
7748 got_object_tree_close(s->tree);
7749 if (s->root)
7750 got_object_tree_close(s->root);
7751 return NULL;
7754 static const struct got_error *
7755 search_start_tree_view(struct tog_view *view)
7757 struct tog_tree_view_state *s = &view->state.tree;
7759 s->matched_entry = NULL;
7760 return NULL;
7763 static int
7764 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7766 regmatch_t regmatch;
7768 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7769 0) == 0;
7772 static const struct got_error *
7773 search_next_tree_view(struct tog_view *view)
7775 struct tog_tree_view_state *s = &view->state.tree;
7776 struct got_tree_entry *te = NULL;
7778 if (!view->searching) {
7779 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7780 return NULL;
7783 if (s->matched_entry) {
7784 if (view->searching == TOG_SEARCH_FORWARD) {
7785 if (s->selected_entry)
7786 te = got_tree_entry_get_next(s->tree,
7787 s->selected_entry);
7788 else
7789 te = got_object_tree_get_first_entry(s->tree);
7790 } else {
7791 if (s->selected_entry == NULL)
7792 te = got_object_tree_get_last_entry(s->tree);
7793 else
7794 te = got_tree_entry_get_prev(s->tree,
7795 s->selected_entry);
7797 } else {
7798 if (s->selected_entry)
7799 te = s->selected_entry;
7800 else if (view->searching == TOG_SEARCH_FORWARD)
7801 te = got_object_tree_get_first_entry(s->tree);
7802 else
7803 te = got_object_tree_get_last_entry(s->tree);
7806 while (1) {
7807 if (te == NULL) {
7808 if (s->matched_entry == NULL) {
7809 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7810 return NULL;
7812 if (view->searching == TOG_SEARCH_FORWARD)
7813 te = got_object_tree_get_first_entry(s->tree);
7814 else
7815 te = got_object_tree_get_last_entry(s->tree);
7818 if (match_tree_entry(te, &view->regex)) {
7819 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7820 s->matched_entry = te;
7821 break;
7824 if (view->searching == TOG_SEARCH_FORWARD)
7825 te = got_tree_entry_get_next(s->tree, te);
7826 else
7827 te = got_tree_entry_get_prev(s->tree, te);
7830 if (s->matched_entry) {
7831 s->first_displayed_entry = s->matched_entry;
7832 s->selected = 0;
7835 return NULL;
7838 static const struct got_error *
7839 show_tree_view(struct tog_view *view)
7841 const struct got_error *err = NULL;
7842 struct tog_tree_view_state *s = &view->state.tree;
7843 char *parent_path;
7845 err = tree_entry_path(&parent_path, &s->parents, NULL);
7846 if (err)
7847 return err;
7849 err = draw_tree_entries(view, parent_path);
7850 free(parent_path);
7852 view_border(view);
7853 return err;
7856 static const struct got_error *
7857 tree_goto_line(struct tog_view *view, int nlines)
7859 const struct got_error *err = NULL;
7860 struct tog_tree_view_state *s = &view->state.tree;
7861 struct got_tree_entry **fte, **lte, **ste;
7862 int g, last, first = 1, i = 1;
7863 int root = s->tree == s->root;
7864 int off = root ? 1 : 2;
7866 g = view->gline;
7867 view->gline = 0;
7869 if (g == 0)
7870 g = 1;
7871 else if (g > got_object_tree_get_nentries(s->tree))
7872 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7874 fte = &s->first_displayed_entry;
7875 lte = &s->last_displayed_entry;
7876 ste = &s->selected_entry;
7878 if (*fte != NULL) {
7879 first = got_tree_entry_get_index(*fte);
7880 first += off; /* account for ".." */
7882 last = got_tree_entry_get_index(*lte);
7883 last += off;
7885 if (g >= first && g <= last && g - first < nlines) {
7886 s->selected = g - first;
7887 return NULL; /* gline is on the current page */
7890 if (*ste != NULL) {
7891 i = got_tree_entry_get_index(*ste);
7892 i += off;
7895 if (i < g) {
7896 err = tree_scroll_down(view, g - i);
7897 if (err)
7898 return err;
7899 if (got_tree_entry_get_index(*lte) >=
7900 got_object_tree_get_nentries(s->tree) - 1 &&
7901 first + s->selected < g &&
7902 s->selected < s->ndisplayed - 1) {
7903 first = got_tree_entry_get_index(*fte);
7904 first += off;
7905 s->selected = g - first;
7907 } else if (i > g)
7908 tree_scroll_up(s, i - g);
7910 if (g < nlines &&
7911 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7912 s->selected = g - 1;
7914 return NULL;
7917 static const struct got_error *
7918 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7920 const struct got_error *err = NULL;
7921 struct tog_tree_view_state *s = &view->state.tree;
7922 struct got_tree_entry *te;
7923 int n, nscroll = view->nlines - 3;
7925 if (view->gline)
7926 return tree_goto_line(view, nscroll);
7928 switch (ch) {
7929 case '0':
7930 case '$':
7931 case KEY_RIGHT:
7932 case 'l':
7933 case KEY_LEFT:
7934 case 'h':
7935 horizontal_scroll_input(view, ch);
7936 break;
7937 case 'i':
7938 s->show_ids = !s->show_ids;
7939 view->count = 0;
7940 break;
7941 case 'L':
7942 view->count = 0;
7943 if (!s->selected_entry)
7944 break;
7945 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7946 break;
7947 case 'R':
7948 view->count = 0;
7949 err = view_request_new(new_view, view, TOG_VIEW_REF);
7950 break;
7951 case 'g':
7952 case '=':
7953 case KEY_HOME:
7954 s->selected = 0;
7955 view->count = 0;
7956 if (s->tree == s->root)
7957 s->first_displayed_entry =
7958 got_object_tree_get_first_entry(s->tree);
7959 else
7960 s->first_displayed_entry = NULL;
7961 break;
7962 case 'G':
7963 case '*':
7964 case KEY_END: {
7965 int eos = view->nlines - 3;
7967 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7968 --eos; /* border */
7969 s->selected = 0;
7970 view->count = 0;
7971 te = got_object_tree_get_last_entry(s->tree);
7972 for (n = 0; n < eos; n++) {
7973 if (te == NULL) {
7974 if (s->tree != s->root) {
7975 s->first_displayed_entry = NULL;
7976 n++;
7978 break;
7980 s->first_displayed_entry = te;
7981 te = got_tree_entry_get_prev(s->tree, te);
7983 if (n > 0)
7984 s->selected = n - 1;
7985 break;
7987 case 'k':
7988 case KEY_UP:
7989 case CTRL('p'):
7990 if (s->selected > 0) {
7991 s->selected--;
7992 break;
7994 tree_scroll_up(s, 1);
7995 if (s->selected_entry == NULL ||
7996 (s->tree == s->root && s->selected_entry ==
7997 got_object_tree_get_first_entry(s->tree)))
7998 view->count = 0;
7999 break;
8000 case CTRL('u'):
8001 case 'u':
8002 nscroll /= 2;
8003 /* FALL THROUGH */
8004 case KEY_PPAGE:
8005 case CTRL('b'):
8006 case 'b':
8007 if (s->tree == s->root) {
8008 if (got_object_tree_get_first_entry(s->tree) ==
8009 s->first_displayed_entry)
8010 s->selected -= MIN(s->selected, nscroll);
8011 } else {
8012 if (s->first_displayed_entry == NULL)
8013 s->selected -= MIN(s->selected, nscroll);
8015 tree_scroll_up(s, MAX(0, nscroll));
8016 if (s->selected_entry == NULL ||
8017 (s->tree == s->root && s->selected_entry ==
8018 got_object_tree_get_first_entry(s->tree)))
8019 view->count = 0;
8020 break;
8021 case 'j':
8022 case KEY_DOWN:
8023 case CTRL('n'):
8024 if (s->selected < s->ndisplayed - 1) {
8025 s->selected++;
8026 break;
8028 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8029 == NULL) {
8030 /* can't scroll any further */
8031 view->count = 0;
8032 break;
8034 tree_scroll_down(view, 1);
8035 break;
8036 case CTRL('d'):
8037 case 'd':
8038 nscroll /= 2;
8039 /* FALL THROUGH */
8040 case KEY_NPAGE:
8041 case CTRL('f'):
8042 case 'f':
8043 case ' ':
8044 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8045 == NULL) {
8046 /* can't scroll any further; move cursor down */
8047 if (s->selected < s->ndisplayed - 1)
8048 s->selected += MIN(nscroll,
8049 s->ndisplayed - s->selected - 1);
8050 else
8051 view->count = 0;
8052 break;
8054 tree_scroll_down(view, nscroll);
8055 break;
8056 case KEY_ENTER:
8057 case '\r':
8058 case KEY_BACKSPACE:
8059 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
8060 struct tog_parent_tree *parent;
8061 /* user selected '..' */
8062 if (s->tree == s->root) {
8063 view->count = 0;
8064 break;
8066 parent = TAILQ_FIRST(&s->parents);
8067 TAILQ_REMOVE(&s->parents, parent,
8068 entry);
8069 got_object_tree_close(s->tree);
8070 s->tree = parent->tree;
8071 s->first_displayed_entry =
8072 parent->first_displayed_entry;
8073 s->selected_entry =
8074 parent->selected_entry;
8075 s->selected = parent->selected;
8076 if (s->selected > view->nlines - 3) {
8077 err = offset_selection_down(view);
8078 if (err)
8079 break;
8081 free(parent);
8082 } else if (S_ISDIR(got_tree_entry_get_mode(
8083 s->selected_entry))) {
8084 struct got_tree_object *subtree;
8085 view->count = 0;
8086 err = got_object_open_as_tree(&subtree, s->repo,
8087 got_tree_entry_get_id(s->selected_entry));
8088 if (err)
8089 break;
8090 err = tree_view_visit_subtree(s, subtree);
8091 if (err) {
8092 got_object_tree_close(subtree);
8093 break;
8095 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
8096 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
8097 break;
8098 case KEY_RESIZE:
8099 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
8100 s->selected = view->nlines - 4;
8101 view->count = 0;
8102 break;
8103 default:
8104 view->count = 0;
8105 break;
8108 return err;
8111 __dead static void
8112 usage_tree(void)
8114 endwin();
8115 fprintf(stderr,
8116 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
8117 getprogname());
8118 exit(1);
8121 static const struct got_error *
8122 cmd_tree(int argc, char *argv[])
8124 const struct got_error *error;
8125 struct got_repository *repo = NULL;
8126 struct got_worktree *worktree = NULL;
8127 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8128 struct got_object_id *commit_id = NULL;
8129 struct got_commit_object *commit = NULL;
8130 const char *commit_id_arg = NULL;
8131 char *keyword_idstr = NULL, *label = NULL;
8132 struct got_reference *ref = NULL;
8133 const char *head_ref_name = NULL;
8134 int ch;
8135 struct tog_view *view;
8136 int *pack_fds = NULL;
8138 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
8139 switch (ch) {
8140 case 'c':
8141 commit_id_arg = optarg;
8142 break;
8143 case 'r':
8144 repo_path = realpath(optarg, NULL);
8145 if (repo_path == NULL)
8146 return got_error_from_errno2("realpath",
8147 optarg);
8148 break;
8149 default:
8150 usage_tree();
8151 /* NOTREACHED */
8155 argc -= optind;
8156 argv += optind;
8158 if (argc > 1)
8159 usage_tree();
8161 error = got_repo_pack_fds_open(&pack_fds);
8162 if (error != NULL)
8163 goto done;
8165 if (repo_path == NULL) {
8166 cwd = getcwd(NULL, 0);
8167 if (cwd == NULL)
8168 return got_error_from_errno("getcwd");
8169 error = got_worktree_open(&worktree, cwd, NULL);
8170 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8171 goto done;
8172 if (worktree)
8173 repo_path =
8174 strdup(got_worktree_get_repo_path(worktree));
8175 else
8176 repo_path = strdup(cwd);
8177 if (repo_path == NULL) {
8178 error = got_error_from_errno("strdup");
8179 goto done;
8183 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8184 if (error != NULL)
8185 goto done;
8187 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8188 repo, worktree);
8189 if (error)
8190 goto done;
8192 init_curses();
8194 error = apply_unveil(got_repo_get_path(repo), NULL);
8195 if (error)
8196 goto done;
8198 error = tog_load_refs(repo, 0);
8199 if (error)
8200 goto done;
8202 if (commit_id_arg == NULL) {
8203 error = got_repo_match_object_id(&commit_id, &label,
8204 worktree ? got_worktree_get_head_ref_name(worktree) :
8205 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8206 if (error)
8207 goto done;
8208 head_ref_name = label;
8209 } else {
8210 error = got_keyword_to_idstr(&keyword_idstr, commit_id_arg,
8211 repo, worktree);
8212 if (error != NULL)
8213 goto done;
8214 if (keyword_idstr != NULL)
8215 commit_id_arg = keyword_idstr;
8217 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8218 if (error == NULL)
8219 head_ref_name = got_ref_get_name(ref);
8220 else if (error->code != GOT_ERR_NOT_REF)
8221 goto done;
8222 error = got_repo_match_object_id(&commit_id, NULL,
8223 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8224 if (error)
8225 goto done;
8228 error = got_object_open_as_commit(&commit, repo, commit_id);
8229 if (error)
8230 goto done;
8232 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8233 if (view == NULL) {
8234 error = got_error_from_errno("view_open");
8235 goto done;
8237 error = open_tree_view(view, commit_id, head_ref_name, repo);
8238 if (error)
8239 goto done;
8240 if (!got_path_is_root_dir(in_repo_path)) {
8241 error = tree_view_walk_path(&view->state.tree, commit,
8242 in_repo_path);
8243 if (error)
8244 goto done;
8247 if (worktree) {
8248 error = set_tog_base_commit(repo, worktree);
8249 if (error != NULL)
8250 goto done;
8252 /* Release work tree lock. */
8253 got_worktree_close(worktree);
8254 worktree = NULL;
8257 error = view_loop(view);
8259 done:
8260 free(tog_base_commit.id);
8261 free(keyword_idstr);
8262 free(repo_path);
8263 free(cwd);
8264 free(commit_id);
8265 free(label);
8266 if (ref)
8267 got_ref_close(ref);
8268 if (worktree != NULL)
8269 got_worktree_close(worktree);
8270 if (repo) {
8271 const struct got_error *close_err = got_repo_close(repo);
8272 if (error == NULL)
8273 error = close_err;
8275 if (pack_fds) {
8276 const struct got_error *pack_err =
8277 got_repo_pack_fds_close(pack_fds);
8278 if (error == NULL)
8279 error = pack_err;
8281 tog_free_refs();
8282 return error;
8285 static const struct got_error *
8286 ref_view_load_refs(struct tog_ref_view_state *s)
8288 struct got_reflist_entry *sre;
8289 struct tog_reflist_entry *re;
8291 s->nrefs = 0;
8292 TAILQ_FOREACH(sre, &tog_refs, entry) {
8293 if (strncmp(got_ref_get_name(sre->ref),
8294 "refs/got/", 9) == 0 &&
8295 strncmp(got_ref_get_name(sre->ref),
8296 "refs/got/backup/", 16) != 0)
8297 continue;
8299 re = malloc(sizeof(*re));
8300 if (re == NULL)
8301 return got_error_from_errno("malloc");
8303 re->ref = got_ref_dup(sre->ref);
8304 if (re->ref == NULL)
8305 return got_error_from_errno("got_ref_dup");
8306 re->idx = s->nrefs++;
8307 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8310 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8311 return NULL;
8314 static void
8315 ref_view_free_refs(struct tog_ref_view_state *s)
8317 struct tog_reflist_entry *re;
8319 while (!TAILQ_EMPTY(&s->refs)) {
8320 re = TAILQ_FIRST(&s->refs);
8321 TAILQ_REMOVE(&s->refs, re, entry);
8322 got_ref_close(re->ref);
8323 free(re);
8327 static const struct got_error *
8328 open_ref_view(struct tog_view *view, struct got_repository *repo)
8330 const struct got_error *err = NULL;
8331 struct tog_ref_view_state *s = &view->state.ref;
8333 s->selected_entry = 0;
8334 s->repo = repo;
8336 TAILQ_INIT(&s->refs);
8337 STAILQ_INIT(&s->colors);
8339 err = ref_view_load_refs(s);
8340 if (err)
8341 goto done;
8343 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8344 err = add_color(&s->colors, "^refs/heads/",
8345 TOG_COLOR_REFS_HEADS,
8346 get_color_value("TOG_COLOR_REFS_HEADS"));
8347 if (err)
8348 goto done;
8350 err = add_color(&s->colors, "^refs/tags/",
8351 TOG_COLOR_REFS_TAGS,
8352 get_color_value("TOG_COLOR_REFS_TAGS"));
8353 if (err)
8354 goto done;
8356 err = add_color(&s->colors, "^refs/remotes/",
8357 TOG_COLOR_REFS_REMOTES,
8358 get_color_value("TOG_COLOR_REFS_REMOTES"));
8359 if (err)
8360 goto done;
8362 err = add_color(&s->colors, "^refs/got/backup/",
8363 TOG_COLOR_REFS_BACKUP,
8364 get_color_value("TOG_COLOR_REFS_BACKUP"));
8365 if (err)
8366 goto done;
8369 view->show = show_ref_view;
8370 view->input = input_ref_view;
8371 view->close = close_ref_view;
8372 view->search_start = search_start_ref_view;
8373 view->search_next = search_next_ref_view;
8374 done:
8375 if (err) {
8376 if (view->close == NULL)
8377 close_ref_view(view);
8378 view_close(view);
8380 return err;
8383 static const struct got_error *
8384 close_ref_view(struct tog_view *view)
8386 struct tog_ref_view_state *s = &view->state.ref;
8388 ref_view_free_refs(s);
8389 free_colors(&s->colors);
8391 return NULL;
8394 static const struct got_error *
8395 resolve_reflist_entry(struct got_object_id **commit_id,
8396 struct tog_reflist_entry *re, struct got_repository *repo)
8398 const struct got_error *err = NULL;
8399 struct got_object_id *obj_id;
8400 struct got_tag_object *tag = NULL;
8401 int obj_type;
8403 *commit_id = NULL;
8405 err = got_ref_resolve(&obj_id, repo, re->ref);
8406 if (err)
8407 return err;
8409 err = got_object_get_type(&obj_type, repo, obj_id);
8410 if (err)
8411 goto done;
8413 switch (obj_type) {
8414 case GOT_OBJ_TYPE_COMMIT:
8415 *commit_id = obj_id;
8416 break;
8417 case GOT_OBJ_TYPE_TAG:
8418 err = got_object_open_as_tag(&tag, repo, obj_id);
8419 if (err)
8420 goto done;
8421 free(obj_id);
8422 err = got_object_get_type(&obj_type, repo,
8423 got_object_tag_get_object_id(tag));
8424 if (err)
8425 goto done;
8426 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8427 err = got_error(GOT_ERR_OBJ_TYPE);
8428 goto done;
8430 *commit_id = got_object_id_dup(
8431 got_object_tag_get_object_id(tag));
8432 if (*commit_id == NULL) {
8433 err = got_error_from_errno("got_object_id_dup");
8434 goto done;
8436 break;
8437 default:
8438 err = got_error(GOT_ERR_OBJ_TYPE);
8439 break;
8442 done:
8443 if (tag)
8444 got_object_tag_close(tag);
8445 if (err) {
8446 free(*commit_id);
8447 *commit_id = NULL;
8449 return err;
8452 static const struct got_error *
8453 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8454 struct tog_reflist_entry *re, struct got_repository *repo)
8456 struct tog_view *log_view;
8457 const struct got_error *err = NULL;
8458 struct got_object_id *commit_id = NULL;
8460 *new_view = NULL;
8462 err = resolve_reflist_entry(&commit_id, re, repo);
8463 if (err) {
8464 if (err->code != GOT_ERR_OBJ_TYPE)
8465 return err;
8466 else
8467 return NULL;
8470 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8471 if (log_view == NULL) {
8472 err = got_error_from_errno("view_open");
8473 goto done;
8476 err = open_log_view(log_view, commit_id, repo,
8477 got_ref_get_name(re->ref), "", 0);
8478 done:
8479 if (err)
8480 view_close(log_view);
8481 else
8482 *new_view = log_view;
8483 free(commit_id);
8484 return err;
8487 static void
8488 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8490 struct tog_reflist_entry *re;
8491 int i = 0;
8493 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8494 return;
8496 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8497 while (i++ < maxscroll) {
8498 if (re == NULL)
8499 break;
8500 s->first_displayed_entry = re;
8501 re = TAILQ_PREV(re, tog_reflist_head, entry);
8505 static const struct got_error *
8506 ref_scroll_down(struct tog_view *view, int maxscroll)
8508 struct tog_ref_view_state *s = &view->state.ref;
8509 struct tog_reflist_entry *next, *last;
8510 int n = 0;
8512 if (s->first_displayed_entry)
8513 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8514 else
8515 next = TAILQ_FIRST(&s->refs);
8517 last = s->last_displayed_entry;
8518 while (next && n++ < maxscroll) {
8519 if (last) {
8520 s->last_displayed_entry = last;
8521 last = TAILQ_NEXT(last, entry);
8523 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8524 s->first_displayed_entry = next;
8525 next = TAILQ_NEXT(next, entry);
8529 return NULL;
8532 static const struct got_error *
8533 search_start_ref_view(struct tog_view *view)
8535 struct tog_ref_view_state *s = &view->state.ref;
8537 s->matched_entry = NULL;
8538 return NULL;
8541 static int
8542 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8544 regmatch_t regmatch;
8546 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8547 0) == 0;
8550 static const struct got_error *
8551 search_next_ref_view(struct tog_view *view)
8553 struct tog_ref_view_state *s = &view->state.ref;
8554 struct tog_reflist_entry *re = NULL;
8556 if (!view->searching) {
8557 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8558 return NULL;
8561 if (s->matched_entry) {
8562 if (view->searching == TOG_SEARCH_FORWARD) {
8563 if (s->selected_entry)
8564 re = TAILQ_NEXT(s->selected_entry, entry);
8565 else
8566 re = TAILQ_PREV(s->selected_entry,
8567 tog_reflist_head, entry);
8568 } else {
8569 if (s->selected_entry == NULL)
8570 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8571 else
8572 re = TAILQ_PREV(s->selected_entry,
8573 tog_reflist_head, entry);
8575 } else {
8576 if (s->selected_entry)
8577 re = s->selected_entry;
8578 else if (view->searching == TOG_SEARCH_FORWARD)
8579 re = TAILQ_FIRST(&s->refs);
8580 else
8581 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8584 while (1) {
8585 if (re == NULL) {
8586 if (s->matched_entry == NULL) {
8587 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8588 return NULL;
8590 if (view->searching == TOG_SEARCH_FORWARD)
8591 re = TAILQ_FIRST(&s->refs);
8592 else
8593 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8596 if (match_reflist_entry(re, &view->regex)) {
8597 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8598 s->matched_entry = re;
8599 break;
8602 if (view->searching == TOG_SEARCH_FORWARD)
8603 re = TAILQ_NEXT(re, entry);
8604 else
8605 re = TAILQ_PREV(re, tog_reflist_head, entry);
8608 if (s->matched_entry) {
8609 s->first_displayed_entry = s->matched_entry;
8610 s->selected = 0;
8613 return NULL;
8616 static const struct got_error *
8617 show_ref_view(struct tog_view *view)
8619 const struct got_error *err = NULL;
8620 struct tog_ref_view_state *s = &view->state.ref;
8621 struct tog_reflist_entry *re;
8622 char *line = NULL;
8623 wchar_t *wline;
8624 struct tog_color *tc;
8625 int width, n, scrollx;
8626 int limit = view->nlines;
8628 werase(view->window);
8630 s->ndisplayed = 0;
8631 if (view_is_hsplit_top(view))
8632 --limit; /* border */
8634 if (limit == 0)
8635 return NULL;
8637 re = s->first_displayed_entry;
8639 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8640 s->nrefs) == -1)
8641 return got_error_from_errno("asprintf");
8643 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8644 if (err) {
8645 free(line);
8646 return err;
8648 if (view_needs_focus_indication(view))
8649 wstandout(view->window);
8650 waddwstr(view->window, wline);
8651 while (width++ < view->ncols)
8652 waddch(view->window, ' ');
8653 if (view_needs_focus_indication(view))
8654 wstandend(view->window);
8655 free(wline);
8656 wline = NULL;
8657 free(line);
8658 line = NULL;
8659 if (--limit <= 0)
8660 return NULL;
8662 n = 0;
8663 view->maxx = 0;
8664 while (re && limit > 0) {
8665 char *line = NULL;
8666 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8668 if (s->show_date) {
8669 struct got_commit_object *ci;
8670 struct got_tag_object *tag;
8671 struct got_object_id *id;
8672 struct tm tm;
8673 time_t t;
8675 err = got_ref_resolve(&id, s->repo, re->ref);
8676 if (err)
8677 return err;
8678 err = got_object_open_as_tag(&tag, s->repo, id);
8679 if (err) {
8680 if (err->code != GOT_ERR_OBJ_TYPE) {
8681 free(id);
8682 return err;
8684 err = got_object_open_as_commit(&ci, s->repo,
8685 id);
8686 if (err) {
8687 free(id);
8688 return err;
8690 t = got_object_commit_get_committer_time(ci);
8691 got_object_commit_close(ci);
8692 } else {
8693 t = got_object_tag_get_tagger_time(tag);
8694 got_object_tag_close(tag);
8696 free(id);
8697 if (gmtime_r(&t, &tm) == NULL)
8698 return got_error_from_errno("gmtime_r");
8699 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8700 return got_error(GOT_ERR_NO_SPACE);
8702 if (got_ref_is_symbolic(re->ref)) {
8703 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8704 ymd : "", got_ref_get_name(re->ref),
8705 got_ref_get_symref_target(re->ref)) == -1)
8706 return got_error_from_errno("asprintf");
8707 } else if (s->show_ids) {
8708 struct got_object_id *id;
8709 char *id_str;
8710 err = got_ref_resolve(&id, s->repo, re->ref);
8711 if (err)
8712 return err;
8713 err = got_object_id_str(&id_str, id);
8714 if (err) {
8715 free(id);
8716 return err;
8718 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8719 got_ref_get_name(re->ref), id_str) == -1) {
8720 err = got_error_from_errno("asprintf");
8721 free(id);
8722 free(id_str);
8723 return err;
8725 free(id);
8726 free(id_str);
8727 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8728 got_ref_get_name(re->ref)) == -1)
8729 return got_error_from_errno("asprintf");
8731 /* use full line width to determine view->maxx */
8732 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8733 if (err) {
8734 free(line);
8735 return err;
8737 view->maxx = MAX(view->maxx, width);
8738 free(wline);
8739 wline = NULL;
8741 err = format_line(&wline, &width, &scrollx, line, view->x,
8742 view->ncols, 0, 0);
8743 if (err) {
8744 free(line);
8745 return err;
8747 if (n == s->selected) {
8748 if (view->focussed)
8749 wstandout(view->window);
8750 s->selected_entry = re;
8752 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8753 if (tc)
8754 wattr_on(view->window,
8755 COLOR_PAIR(tc->colorpair), NULL);
8756 waddwstr(view->window, &wline[scrollx]);
8757 if (tc)
8758 wattr_off(view->window,
8759 COLOR_PAIR(tc->colorpair), NULL);
8760 if (width < view->ncols)
8761 waddch(view->window, '\n');
8762 if (n == s->selected && view->focussed)
8763 wstandend(view->window);
8764 free(line);
8765 free(wline);
8766 wline = NULL;
8767 n++;
8768 s->ndisplayed++;
8769 s->last_displayed_entry = re;
8771 limit--;
8772 re = TAILQ_NEXT(re, entry);
8775 view_border(view);
8776 return err;
8779 static const struct got_error *
8780 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8781 struct tog_reflist_entry *re, struct got_repository *repo)
8783 const struct got_error *err = NULL;
8784 struct got_object_id *commit_id = NULL;
8785 struct tog_view *tree_view;
8787 *new_view = NULL;
8789 err = resolve_reflist_entry(&commit_id, re, repo);
8790 if (err) {
8791 if (err->code != GOT_ERR_OBJ_TYPE)
8792 return err;
8793 else
8794 return NULL;
8798 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8799 if (tree_view == NULL) {
8800 err = got_error_from_errno("view_open");
8801 goto done;
8804 err = open_tree_view(tree_view, commit_id,
8805 got_ref_get_name(re->ref), repo);
8806 if (err)
8807 goto done;
8809 *new_view = tree_view;
8810 done:
8811 free(commit_id);
8812 return err;
8815 static const struct got_error *
8816 ref_goto_line(struct tog_view *view, int nlines)
8818 const struct got_error *err = NULL;
8819 struct tog_ref_view_state *s = &view->state.ref;
8820 int g, idx = s->selected_entry->idx;
8822 g = view->gline;
8823 view->gline = 0;
8825 if (g == 0)
8826 g = 1;
8827 else if (g > s->nrefs)
8828 g = s->nrefs;
8830 if (g >= s->first_displayed_entry->idx + 1 &&
8831 g <= s->last_displayed_entry->idx + 1 &&
8832 g - s->first_displayed_entry->idx - 1 < nlines) {
8833 s->selected = g - s->first_displayed_entry->idx - 1;
8834 return NULL;
8837 if (idx + 1 < g) {
8838 err = ref_scroll_down(view, g - idx - 1);
8839 if (err)
8840 return err;
8841 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8842 s->first_displayed_entry->idx + s->selected < g &&
8843 s->selected < s->ndisplayed - 1)
8844 s->selected = g - s->first_displayed_entry->idx - 1;
8845 } else if (idx + 1 > g)
8846 ref_scroll_up(s, idx - g + 1);
8848 if (g < nlines && s->first_displayed_entry->idx == 0)
8849 s->selected = g - 1;
8851 return NULL;
8855 static const struct got_error *
8856 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8858 const struct got_error *err = NULL;
8859 struct tog_ref_view_state *s = &view->state.ref;
8860 struct tog_reflist_entry *re;
8861 int n, nscroll = view->nlines - 1;
8863 if (view->gline)
8864 return ref_goto_line(view, nscroll);
8866 switch (ch) {
8867 case '0':
8868 case '$':
8869 case KEY_RIGHT:
8870 case 'l':
8871 case KEY_LEFT:
8872 case 'h':
8873 horizontal_scroll_input(view, ch);
8874 break;
8875 case 'i':
8876 s->show_ids = !s->show_ids;
8877 view->count = 0;
8878 break;
8879 case 'm':
8880 s->show_date = !s->show_date;
8881 view->count = 0;
8882 break;
8883 case 'o':
8884 s->sort_by_date = !s->sort_by_date;
8885 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8886 view->count = 0;
8887 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8888 got_ref_cmp_by_commit_timestamp_descending :
8889 tog_ref_cmp_by_name, s->repo);
8890 if (err)
8891 break;
8892 got_reflist_object_id_map_free(tog_refs_idmap);
8893 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8894 &tog_refs, s->repo);
8895 if (err)
8896 break;
8897 ref_view_free_refs(s);
8898 err = ref_view_load_refs(s);
8899 break;
8900 case KEY_ENTER:
8901 case '\r':
8902 view->count = 0;
8903 if (!s->selected_entry)
8904 break;
8905 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8906 break;
8907 case 'T':
8908 view->count = 0;
8909 if (!s->selected_entry)
8910 break;
8911 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8912 break;
8913 case 'g':
8914 case '=':
8915 case KEY_HOME:
8916 s->selected = 0;
8917 view->count = 0;
8918 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8919 break;
8920 case 'G':
8921 case '*':
8922 case KEY_END: {
8923 int eos = view->nlines - 1;
8925 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8926 --eos; /* border */
8927 s->selected = 0;
8928 view->count = 0;
8929 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8930 for (n = 0; n < eos; n++) {
8931 if (re == NULL)
8932 break;
8933 s->first_displayed_entry = re;
8934 re = TAILQ_PREV(re, tog_reflist_head, entry);
8936 if (n > 0)
8937 s->selected = n - 1;
8938 break;
8940 case 'k':
8941 case KEY_UP:
8942 case CTRL('p'):
8943 if (s->selected > 0) {
8944 s->selected--;
8945 break;
8947 ref_scroll_up(s, 1);
8948 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8949 view->count = 0;
8950 break;
8951 case CTRL('u'):
8952 case 'u':
8953 nscroll /= 2;
8954 /* FALL THROUGH */
8955 case KEY_PPAGE:
8956 case CTRL('b'):
8957 case 'b':
8958 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8959 s->selected -= MIN(nscroll, s->selected);
8960 ref_scroll_up(s, MAX(0, nscroll));
8961 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8962 view->count = 0;
8963 break;
8964 case 'j':
8965 case KEY_DOWN:
8966 case CTRL('n'):
8967 if (s->selected < s->ndisplayed - 1) {
8968 s->selected++;
8969 break;
8971 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8972 /* can't scroll any further */
8973 view->count = 0;
8974 break;
8976 ref_scroll_down(view, 1);
8977 break;
8978 case CTRL('d'):
8979 case 'd':
8980 nscroll /= 2;
8981 /* FALL THROUGH */
8982 case KEY_NPAGE:
8983 case CTRL('f'):
8984 case 'f':
8985 case ' ':
8986 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8987 /* can't scroll any further; move cursor down */
8988 if (s->selected < s->ndisplayed - 1)
8989 s->selected += MIN(nscroll,
8990 s->ndisplayed - s->selected - 1);
8991 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8992 s->selected += s->ndisplayed - s->selected - 1;
8993 view->count = 0;
8994 break;
8996 ref_scroll_down(view, nscroll);
8997 break;
8998 case CTRL('l'):
8999 view->count = 0;
9000 tog_free_refs();
9001 err = tog_load_refs(s->repo, s->sort_by_date);
9002 if (err)
9003 break;
9004 ref_view_free_refs(s);
9005 err = ref_view_load_refs(s);
9006 break;
9007 case KEY_RESIZE:
9008 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
9009 s->selected = view->nlines - 2;
9010 break;
9011 default:
9012 view->count = 0;
9013 break;
9016 return err;
9019 __dead static void
9020 usage_ref(void)
9022 endwin();
9023 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
9024 getprogname());
9025 exit(1);
9028 static const struct got_error *
9029 cmd_ref(int argc, char *argv[])
9031 const struct got_error *error;
9032 struct got_repository *repo = NULL;
9033 struct got_worktree *worktree = NULL;
9034 char *cwd = NULL, *repo_path = NULL;
9035 int ch;
9036 struct tog_view *view;
9037 int *pack_fds = NULL;
9039 while ((ch = getopt(argc, argv, "r:")) != -1) {
9040 switch (ch) {
9041 case 'r':
9042 repo_path = realpath(optarg, NULL);
9043 if (repo_path == NULL)
9044 return got_error_from_errno2("realpath",
9045 optarg);
9046 break;
9047 default:
9048 usage_ref();
9049 /* NOTREACHED */
9053 argc -= optind;
9054 argv += optind;
9056 if (argc > 1)
9057 usage_ref();
9059 error = got_repo_pack_fds_open(&pack_fds);
9060 if (error != NULL)
9061 goto done;
9063 if (repo_path == NULL) {
9064 cwd = getcwd(NULL, 0);
9065 if (cwd == NULL)
9066 return got_error_from_errno("getcwd");
9067 error = got_worktree_open(&worktree, cwd, NULL);
9068 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9069 goto done;
9070 if (worktree)
9071 repo_path =
9072 strdup(got_worktree_get_repo_path(worktree));
9073 else
9074 repo_path = strdup(cwd);
9075 if (repo_path == NULL) {
9076 error = got_error_from_errno("strdup");
9077 goto done;
9081 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9082 if (error != NULL)
9083 goto done;
9085 init_curses();
9087 error = apply_unveil(got_repo_get_path(repo), NULL);
9088 if (error)
9089 goto done;
9091 error = tog_load_refs(repo, 0);
9092 if (error)
9093 goto done;
9095 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
9096 if (view == NULL) {
9097 error = got_error_from_errno("view_open");
9098 goto done;
9101 error = open_ref_view(view, repo);
9102 if (error)
9103 goto done;
9105 if (worktree) {
9106 error = set_tog_base_commit(repo, worktree);
9107 if (error != NULL)
9108 goto done;
9110 /* Release work tree lock. */
9111 got_worktree_close(worktree);
9112 worktree = NULL;
9115 error = view_loop(view);
9117 done:
9118 free(tog_base_commit.id);
9119 free(repo_path);
9120 free(cwd);
9121 if (worktree != NULL)
9122 got_worktree_close(worktree);
9123 if (repo) {
9124 const struct got_error *close_err = got_repo_close(repo);
9125 if (close_err)
9126 error = close_err;
9128 if (pack_fds) {
9129 const struct got_error *pack_err =
9130 got_repo_pack_fds_close(pack_fds);
9131 if (error == NULL)
9132 error = pack_err;
9134 tog_free_refs();
9135 return error;
9138 static const struct got_error*
9139 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
9140 const char *str)
9142 size_t len;
9144 if (win == NULL)
9145 win = stdscr;
9147 len = strlen(str);
9148 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
9150 if (focus)
9151 wstandout(win);
9152 if (mvwprintw(win, y, x, "%s", str) == ERR)
9153 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
9154 if (focus)
9155 wstandend(win);
9157 return NULL;
9160 static const struct got_error *
9161 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
9163 off_t *p;
9165 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
9166 if (p == NULL) {
9167 free(*line_offsets);
9168 *line_offsets = NULL;
9169 return got_error_from_errno("reallocarray");
9172 *line_offsets = p;
9173 (*line_offsets)[*nlines] = off;
9174 ++(*nlines);
9175 return NULL;
9178 static const struct got_error *
9179 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
9181 *ret = 0;
9183 for (;n > 0; --n, ++km) {
9184 char *t0, *t, *k;
9185 size_t len = 1;
9187 if (km->keys == NULL)
9188 continue;
9190 t = t0 = strdup(km->keys);
9191 if (t0 == NULL)
9192 return got_error_from_errno("strdup");
9194 len += strlen(t);
9195 while ((k = strsep(&t, " ")) != NULL)
9196 len += strlen(k) > 1 ? 2 : 0;
9197 free(t0);
9198 *ret = MAX(*ret, len);
9201 return NULL;
9205 * Write keymap section headers, keys, and key info in km to f.
9206 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9207 * wrap control and symbolic keys in guillemets, else use <>.
9209 static const struct got_error *
9210 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9212 int n, len = width;
9214 if (km->keys) {
9215 static const char *u8_glyph[] = {
9216 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9217 "\xe2\x80\xba" /* U+203A (utf8 >) */
9219 char *t0, *t, *k;
9220 int cs, s, first = 1;
9222 cs = got_locale_is_utf8();
9224 t = t0 = strdup(km->keys);
9225 if (t0 == NULL)
9226 return got_error_from_errno("strdup");
9228 len = strlen(km->keys);
9229 while ((k = strsep(&t, " ")) != NULL) {
9230 s = strlen(k) > 1; /* control or symbolic key */
9231 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9232 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9233 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9234 if (n < 0) {
9235 free(t0);
9236 return got_error_from_errno("fprintf");
9238 first = 0;
9239 len += s ? 2 : 0;
9240 *off += n;
9242 free(t0);
9244 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9245 if (n < 0)
9246 return got_error_from_errno("fprintf");
9247 *off += n;
9249 return NULL;
9252 static const struct got_error *
9253 format_help(struct tog_help_view_state *s)
9255 const struct got_error *err = NULL;
9256 off_t off = 0;
9257 int i, max, n, show = s->all;
9258 static const struct tog_key_map km[] = {
9259 #define KEYMAP_(info, type) { NULL, (info), type }
9260 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9261 GENERATE_HELP
9262 #undef KEYMAP_
9263 #undef KEY_
9266 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9267 if (err)
9268 return err;
9270 n = nitems(km);
9271 err = max_key_str(&max, km, n);
9272 if (err)
9273 return err;
9275 for (i = 0; i < n; ++i) {
9276 if (km[i].keys == NULL) {
9277 show = s->all;
9278 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9279 km[i].type == s->type || s->all)
9280 show = 1;
9282 if (show) {
9283 err = format_help_line(&off, s->f, &km[i], max);
9284 if (err)
9285 return err;
9286 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9287 if (err)
9288 return err;
9291 fputc('\n', s->f);
9292 ++off;
9293 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9294 return err;
9297 static const struct got_error *
9298 create_help(struct tog_help_view_state *s)
9300 FILE *f;
9301 const struct got_error *err;
9303 free(s->line_offsets);
9304 s->line_offsets = NULL;
9305 s->nlines = 0;
9307 f = got_opentemp();
9308 if (f == NULL)
9309 return got_error_from_errno("got_opentemp");
9310 s->f = f;
9312 err = format_help(s);
9313 if (err)
9314 return err;
9316 if (s->f && fflush(s->f) != 0)
9317 return got_error_from_errno("fflush");
9319 return NULL;
9322 static const struct got_error *
9323 search_start_help_view(struct tog_view *view)
9325 view->state.help.matched_line = 0;
9326 return NULL;
9329 static void
9330 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9331 size_t *nlines, int **first, int **last, int **match, int **selected)
9333 struct tog_help_view_state *s = &view->state.help;
9335 *f = s->f;
9336 *nlines = s->nlines;
9337 *line_offsets = s->line_offsets;
9338 *match = &s->matched_line;
9339 *first = &s->first_displayed_line;
9340 *last = &s->last_displayed_line;
9341 *selected = &s->selected_line;
9344 static const struct got_error *
9345 show_help_view(struct tog_view *view)
9347 struct tog_help_view_state *s = &view->state.help;
9348 const struct got_error *err;
9349 regmatch_t *regmatch = &view->regmatch;
9350 wchar_t *wline;
9351 char *line;
9352 ssize_t linelen;
9353 size_t linesz = 0;
9354 int width, nprinted = 0, rc = 0;
9355 int eos = view->nlines;
9357 if (view_is_hsplit_top(view))
9358 --eos; /* account for border */
9360 s->lineno = 0;
9361 rewind(s->f);
9362 werase(view->window);
9364 if (view->gline > s->nlines - 1)
9365 view->gline = s->nlines - 1;
9367 err = win_draw_center(view->window, 0, 0, view->ncols,
9368 view_needs_focus_indication(view),
9369 "tog help (press q to return to tog)");
9370 if (err)
9371 return err;
9372 if (eos <= 1)
9373 return NULL;
9374 waddstr(view->window, "\n\n");
9375 eos -= 2;
9377 s->eof = 0;
9378 view->maxx = 0;
9379 line = NULL;
9380 while (eos > 0 && nprinted < eos) {
9381 attr_t attr = 0;
9383 linelen = getline(&line, &linesz, s->f);
9384 if (linelen == -1) {
9385 if (!feof(s->f)) {
9386 free(line);
9387 return got_ferror(s->f, GOT_ERR_IO);
9389 s->eof = 1;
9390 break;
9392 if (++s->lineno < s->first_displayed_line)
9393 continue;
9394 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9395 continue;
9396 if (s->lineno == view->hiline)
9397 attr = A_STANDOUT;
9399 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9400 view->x ? 1 : 0);
9401 if (err) {
9402 free(line);
9403 return err;
9405 view->maxx = MAX(view->maxx, width);
9406 free(wline);
9407 wline = NULL;
9409 if (attr)
9410 wattron(view->window, attr);
9411 if (s->first_displayed_line + nprinted == s->matched_line &&
9412 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9413 err = add_matched_line(&width, line, view->ncols - 1, 0,
9414 view->window, view->x, regmatch);
9415 if (err) {
9416 free(line);
9417 return err;
9419 } else {
9420 int skip;
9422 err = format_line(&wline, &width, &skip, line,
9423 view->x, view->ncols, 0, view->x ? 1 : 0);
9424 if (err) {
9425 free(line);
9426 return err;
9428 waddwstr(view->window, &wline[skip]);
9429 free(wline);
9430 wline = NULL;
9432 if (s->lineno == view->hiline) {
9433 while (width++ < view->ncols)
9434 waddch(view->window, ' ');
9435 } else {
9436 if (width < view->ncols)
9437 waddch(view->window, '\n');
9439 if (attr)
9440 wattroff(view->window, attr);
9441 if (++nprinted == 1)
9442 s->first_displayed_line = s->lineno;
9444 free(line);
9445 if (nprinted > 0)
9446 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9447 else
9448 s->last_displayed_line = s->first_displayed_line;
9450 view_border(view);
9452 if (s->eof) {
9453 rc = waddnstr(view->window,
9454 "See the tog(1) manual page for full documentation",
9455 view->ncols - 1);
9456 if (rc == ERR)
9457 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9458 } else {
9459 wmove(view->window, view->nlines - 1, 0);
9460 wclrtoeol(view->window);
9461 wstandout(view->window);
9462 rc = waddnstr(view->window, "scroll down for more...",
9463 view->ncols - 1);
9464 if (rc == ERR)
9465 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9466 if (getcurx(view->window) < view->ncols - 6) {
9467 rc = wprintw(view->window, "[%.0f%%]",
9468 100.00 * s->last_displayed_line / s->nlines);
9469 if (rc == ERR)
9470 return got_error_msg(GOT_ERR_IO, "wprintw");
9472 wstandend(view->window);
9475 return NULL;
9478 static const struct got_error *
9479 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9481 struct tog_help_view_state *s = &view->state.help;
9482 const struct got_error *err = NULL;
9483 char *line = NULL;
9484 ssize_t linelen;
9485 size_t linesz = 0;
9486 int eos, nscroll;
9488 eos = nscroll = view->nlines;
9489 if (view_is_hsplit_top(view))
9490 --eos; /* border */
9492 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9494 switch (ch) {
9495 case '0':
9496 case '$':
9497 case KEY_RIGHT:
9498 case 'l':
9499 case KEY_LEFT:
9500 case 'h':
9501 horizontal_scroll_input(view, ch);
9502 break;
9503 case 'g':
9504 case KEY_HOME:
9505 s->first_displayed_line = 1;
9506 view->count = 0;
9507 break;
9508 case 'G':
9509 case KEY_END:
9510 view->count = 0;
9511 if (s->eof)
9512 break;
9513 s->first_displayed_line = (s->nlines - eos) + 3;
9514 s->eof = 1;
9515 break;
9516 case 'k':
9517 case KEY_UP:
9518 if (s->first_displayed_line > 1)
9519 --s->first_displayed_line;
9520 else
9521 view->count = 0;
9522 break;
9523 case CTRL('u'):
9524 case 'u':
9525 nscroll /= 2;
9526 /* FALL THROUGH */
9527 case KEY_PPAGE:
9528 case CTRL('b'):
9529 case 'b':
9530 if (s->first_displayed_line == 1) {
9531 view->count = 0;
9532 break;
9534 while (--nscroll > 0 && s->first_displayed_line > 1)
9535 s->first_displayed_line--;
9536 break;
9537 case 'j':
9538 case KEY_DOWN:
9539 case CTRL('n'):
9540 if (!s->eof)
9541 ++s->first_displayed_line;
9542 else
9543 view->count = 0;
9544 break;
9545 case CTRL('d'):
9546 case 'd':
9547 nscroll /= 2;
9548 /* FALL THROUGH */
9549 case KEY_NPAGE:
9550 case CTRL('f'):
9551 case 'f':
9552 case ' ':
9553 if (s->eof) {
9554 view->count = 0;
9555 break;
9557 while (!s->eof && --nscroll > 0) {
9558 linelen = getline(&line, &linesz, s->f);
9559 s->first_displayed_line++;
9560 if (linelen == -1) {
9561 if (feof(s->f))
9562 s->eof = 1;
9563 else
9564 err = got_ferror(s->f, GOT_ERR_IO);
9565 break;
9568 free(line);
9569 break;
9570 default:
9571 view->count = 0;
9572 break;
9575 return err;
9578 static const struct got_error *
9579 close_help_view(struct tog_view *view)
9581 struct tog_help_view_state *s = &view->state.help;
9583 free(s->line_offsets);
9584 s->line_offsets = NULL;
9585 if (fclose(s->f) == EOF)
9586 return got_error_from_errno("fclose");
9588 return NULL;
9591 static const struct got_error *
9592 reset_help_view(struct tog_view *view)
9594 struct tog_help_view_state *s = &view->state.help;
9597 if (s->f && fclose(s->f) == EOF)
9598 return got_error_from_errno("fclose");
9600 wclear(view->window);
9601 view->count = 0;
9602 view->x = 0;
9603 s->all = !s->all;
9604 s->first_displayed_line = 1;
9605 s->last_displayed_line = view->nlines;
9606 s->matched_line = 0;
9608 return create_help(s);
9611 static const struct got_error *
9612 open_help_view(struct tog_view *view, struct tog_view *parent)
9614 const struct got_error *err = NULL;
9615 struct tog_help_view_state *s = &view->state.help;
9617 s->type = (enum tog_keymap_type)parent->type;
9618 s->first_displayed_line = 1;
9619 s->last_displayed_line = view->nlines;
9620 s->selected_line = 1;
9622 view->show = show_help_view;
9623 view->input = input_help_view;
9624 view->reset = reset_help_view;
9625 view->close = close_help_view;
9626 view->search_start = search_start_help_view;
9627 view->search_setup = search_setup_help_view;
9628 view->search_next = search_next_view_match;
9630 err = create_help(s);
9631 return err;
9634 static const struct got_error *
9635 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9636 enum tog_view_type request, int y, int x)
9638 const struct got_error *err = NULL;
9640 *new_view = NULL;
9642 switch (request) {
9643 case TOG_VIEW_DIFF:
9644 if (view->type == TOG_VIEW_LOG) {
9645 struct tog_log_view_state *s = &view->state.log;
9647 err = open_diff_view_for_commit(new_view, y, x,
9648 s->selected_entry->commit, s->selected_entry->id,
9649 view, s->repo);
9650 } else
9651 return got_error_msg(GOT_ERR_NOT_IMPL,
9652 "parent/child view pair not supported");
9653 break;
9654 case TOG_VIEW_BLAME:
9655 if (view->type == TOG_VIEW_TREE) {
9656 struct tog_tree_view_state *s = &view->state.tree;
9658 err = blame_tree_entry(new_view, y, x,
9659 s->selected_entry, &s->parents, s->commit_id,
9660 s->repo);
9661 } else
9662 return got_error_msg(GOT_ERR_NOT_IMPL,
9663 "parent/child view pair not supported");
9664 break;
9665 case TOG_VIEW_LOG:
9666 if (view->type == TOG_VIEW_BLAME)
9667 err = log_annotated_line(new_view, y, x,
9668 view->state.blame.repo, view->state.blame.id_to_log);
9669 else if (view->type == TOG_VIEW_TREE)
9670 err = log_selected_tree_entry(new_view, y, x,
9671 &view->state.tree);
9672 else if (view->type == TOG_VIEW_REF)
9673 err = log_ref_entry(new_view, y, x,
9674 view->state.ref.selected_entry,
9675 view->state.ref.repo);
9676 else
9677 return got_error_msg(GOT_ERR_NOT_IMPL,
9678 "parent/child view pair not supported");
9679 break;
9680 case TOG_VIEW_TREE:
9681 if (view->type == TOG_VIEW_LOG)
9682 err = browse_commit_tree(new_view, y, x,
9683 view->state.log.selected_entry,
9684 view->state.log.in_repo_path,
9685 view->state.log.head_ref_name,
9686 view->state.log.repo);
9687 else if (view->type == TOG_VIEW_REF)
9688 err = browse_ref_tree(new_view, y, x,
9689 view->state.ref.selected_entry,
9690 view->state.ref.repo);
9691 else
9692 return got_error_msg(GOT_ERR_NOT_IMPL,
9693 "parent/child view pair not supported");
9694 break;
9695 case TOG_VIEW_REF:
9696 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9697 if (*new_view == NULL)
9698 return got_error_from_errno("view_open");
9699 if (view->type == TOG_VIEW_LOG)
9700 err = open_ref_view(*new_view, view->state.log.repo);
9701 else if (view->type == TOG_VIEW_TREE)
9702 err = open_ref_view(*new_view, view->state.tree.repo);
9703 else
9704 err = got_error_msg(GOT_ERR_NOT_IMPL,
9705 "parent/child view pair not supported");
9706 if (err)
9707 view_close(*new_view);
9708 break;
9709 case TOG_VIEW_HELP:
9710 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9711 if (*new_view == NULL)
9712 return got_error_from_errno("view_open");
9713 err = open_help_view(*new_view, view);
9714 if (err)
9715 view_close(*new_view);
9716 break;
9717 default:
9718 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9721 return err;
9725 * If view was scrolled down to move the selected line into view when opening a
9726 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9728 static void
9729 offset_selection_up(struct tog_view *view)
9731 switch (view->type) {
9732 case TOG_VIEW_BLAME: {
9733 struct tog_blame_view_state *s = &view->state.blame;
9734 if (s->first_displayed_line == 1) {
9735 s->selected_line = MAX(s->selected_line - view->offset,
9736 1);
9737 break;
9739 if (s->first_displayed_line > view->offset)
9740 s->first_displayed_line -= view->offset;
9741 else
9742 s->first_displayed_line = 1;
9743 s->selected_line += view->offset;
9744 break;
9746 case TOG_VIEW_LOG:
9747 log_scroll_up(&view->state.log, view->offset);
9748 view->state.log.selected += view->offset;
9749 break;
9750 case TOG_VIEW_REF:
9751 ref_scroll_up(&view->state.ref, view->offset);
9752 view->state.ref.selected += view->offset;
9753 break;
9754 case TOG_VIEW_TREE:
9755 tree_scroll_up(&view->state.tree, view->offset);
9756 view->state.tree.selected += view->offset;
9757 break;
9758 default:
9759 break;
9762 view->offset = 0;
9766 * If the selected line is in the section of screen covered by the bottom split,
9767 * scroll down offset lines to move it into view and index its new position.
9769 static const struct got_error *
9770 offset_selection_down(struct tog_view *view)
9772 const struct got_error *err = NULL;
9773 const struct got_error *(*scrolld)(struct tog_view *, int);
9774 int *selected = NULL;
9775 int header, offset;
9777 switch (view->type) {
9778 case TOG_VIEW_BLAME: {
9779 struct tog_blame_view_state *s = &view->state.blame;
9780 header = 3;
9781 scrolld = NULL;
9782 if (s->selected_line > view->nlines - header) {
9783 offset = abs(view->nlines - s->selected_line - header);
9784 s->first_displayed_line += offset;
9785 s->selected_line -= offset;
9786 view->offset = offset;
9788 break;
9790 case TOG_VIEW_LOG: {
9791 struct tog_log_view_state *s = &view->state.log;
9792 scrolld = &log_scroll_down;
9793 header = view_is_parent_view(view) ? 3 : 2;
9794 selected = &s->selected;
9795 break;
9797 case TOG_VIEW_REF: {
9798 struct tog_ref_view_state *s = &view->state.ref;
9799 scrolld = &ref_scroll_down;
9800 header = 3;
9801 selected = &s->selected;
9802 break;
9804 case TOG_VIEW_TREE: {
9805 struct tog_tree_view_state *s = &view->state.tree;
9806 scrolld = &tree_scroll_down;
9807 header = 5;
9808 selected = &s->selected;
9809 break;
9811 default:
9812 selected = NULL;
9813 scrolld = NULL;
9814 header = 0;
9815 break;
9818 if (selected && *selected > view->nlines - header) {
9819 offset = abs(view->nlines - *selected - header);
9820 view->offset = offset;
9821 if (scrolld && offset) {
9822 err = scrolld(view, offset);
9823 *selected -= offset;
9827 return err;
9830 static void
9831 list_commands(FILE *fp)
9833 size_t i;
9835 fprintf(fp, "commands:");
9836 for (i = 0; i < nitems(tog_commands); i++) {
9837 const struct tog_cmd *cmd = &tog_commands[i];
9838 fprintf(fp, " %s", cmd->name);
9840 fputc('\n', fp);
9843 __dead static void
9844 usage(int hflag, int status)
9846 FILE *fp = (status == 0) ? stdout : stderr;
9848 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9849 getprogname());
9850 if (hflag) {
9851 fprintf(fp, "lazy usage: %s path\n", getprogname());
9852 list_commands(fp);
9854 exit(status);
9857 static char **
9858 make_argv(int argc, ...)
9860 va_list ap;
9861 char **argv;
9862 int i;
9864 va_start(ap, argc);
9866 argv = calloc(argc, sizeof(char *));
9867 if (argv == NULL)
9868 err(1, "calloc");
9869 for (i = 0; i < argc; i++) {
9870 argv[i] = strdup(va_arg(ap, char *));
9871 if (argv[i] == NULL)
9872 err(1, "strdup");
9875 va_end(ap);
9876 return argv;
9880 * Try to convert 'tog path' into a 'tog log path' command.
9881 * The user could simply have mistyped the command rather than knowingly
9882 * provided a path. So check whether argv[0] can in fact be resolved
9883 * to a path in the HEAD commit and print a special error if not.
9884 * This hack is for mpi@ <3
9886 static const struct got_error *
9887 tog_log_with_path(int argc, char *argv[])
9889 const struct got_error *error = NULL, *close_err;
9890 const struct tog_cmd *cmd = NULL;
9891 struct got_repository *repo = NULL;
9892 struct got_worktree *worktree = NULL;
9893 struct got_object_id *commit_id = NULL, *id = NULL;
9894 struct got_commit_object *commit = NULL;
9895 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9896 char *commit_id_str = NULL, **cmd_argv = NULL;
9897 int *pack_fds = NULL;
9899 cwd = getcwd(NULL, 0);
9900 if (cwd == NULL)
9901 return got_error_from_errno("getcwd");
9903 error = got_repo_pack_fds_open(&pack_fds);
9904 if (error != NULL)
9905 goto done;
9907 error = got_worktree_open(&worktree, cwd, NULL);
9908 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9909 goto done;
9911 if (worktree)
9912 repo_path = strdup(got_worktree_get_repo_path(worktree));
9913 else
9914 repo_path = strdup(cwd);
9915 if (repo_path == NULL) {
9916 error = got_error_from_errno("strdup");
9917 goto done;
9920 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9921 if (error != NULL)
9922 goto done;
9924 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9925 repo, worktree);
9926 if (error)
9927 goto done;
9929 error = tog_load_refs(repo, 0);
9930 if (error)
9931 goto done;
9932 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9933 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9934 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9935 if (error)
9936 goto done;
9938 if (worktree) {
9939 got_worktree_close(worktree);
9940 worktree = NULL;
9943 error = got_object_open_as_commit(&commit, repo, commit_id);
9944 if (error)
9945 goto done;
9947 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9948 if (error) {
9949 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9950 goto done;
9951 fprintf(stderr, "%s: '%s' is no known command or path\n",
9952 getprogname(), argv[0]);
9953 usage(1, 1);
9954 /* not reached */
9957 error = got_object_id_str(&commit_id_str, commit_id);
9958 if (error)
9959 goto done;
9961 cmd = &tog_commands[0]; /* log */
9962 argc = 4;
9963 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9964 error = cmd->cmd_main(argc, cmd_argv);
9965 done:
9966 if (repo) {
9967 close_err = got_repo_close(repo);
9968 if (error == NULL)
9969 error = close_err;
9971 if (commit)
9972 got_object_commit_close(commit);
9973 if (worktree)
9974 got_worktree_close(worktree);
9975 if (pack_fds) {
9976 const struct got_error *pack_err =
9977 got_repo_pack_fds_close(pack_fds);
9978 if (error == NULL)
9979 error = pack_err;
9981 free(id);
9982 free(commit_id_str);
9983 free(commit_id);
9984 free(cwd);
9985 free(repo_path);
9986 free(in_repo_path);
9987 if (cmd_argv) {
9988 int i;
9989 for (i = 0; i < argc; i++)
9990 free(cmd_argv[i]);
9991 free(cmd_argv);
9993 tog_free_refs();
9994 return error;
9997 int
9998 main(int argc, char *argv[])
10000 const struct got_error *io_err, *error = NULL;
10001 const struct tog_cmd *cmd = NULL;
10002 int ch, hflag = 0, Vflag = 0;
10003 char **cmd_argv = NULL;
10004 static const struct option longopts[] = {
10005 { "version", no_argument, NULL, 'V' },
10006 { NULL, 0, NULL, 0}
10008 char *diff_algo_str = NULL;
10009 const char *test_script_path;
10011 setlocale(LC_CTYPE, "");
10014 * Test mode init must happen before pledge() because "tty" will
10015 * not allow TTY-related ioctls to occur via regular files.
10017 test_script_path = getenv("TOG_TEST_SCRIPT");
10018 if (test_script_path != NULL) {
10019 error = init_mock_term(test_script_path);
10020 if (error) {
10021 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10022 return 1;
10024 } else if (!isatty(STDIN_FILENO))
10025 errx(1, "standard input is not a tty");
10027 #if !defined(PROFILE)
10028 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
10029 NULL) == -1)
10030 err(1, "pledge");
10031 #endif
10033 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
10034 switch (ch) {
10035 case 'h':
10036 hflag = 1;
10037 break;
10038 case 'V':
10039 Vflag = 1;
10040 break;
10041 default:
10042 usage(hflag, 1);
10043 /* NOTREACHED */
10047 argc -= optind;
10048 argv += optind;
10049 optind = 1;
10050 optreset = 1;
10052 if (Vflag) {
10053 got_version_print_str();
10054 return 0;
10057 if (argc == 0) {
10058 if (hflag)
10059 usage(hflag, 0);
10060 /* Build an argument vector which runs a default command. */
10061 cmd = &tog_commands[0];
10062 argc = 1;
10063 cmd_argv = make_argv(argc, cmd->name);
10064 } else {
10065 size_t i;
10067 /* Did the user specify a command? */
10068 for (i = 0; i < nitems(tog_commands); i++) {
10069 if (strncmp(tog_commands[i].name, argv[0],
10070 strlen(argv[0])) == 0) {
10071 cmd = &tog_commands[i];
10072 break;
10077 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
10078 if (diff_algo_str) {
10079 if (strcasecmp(diff_algo_str, "patience") == 0)
10080 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
10081 if (strcasecmp(diff_algo_str, "myers") == 0)
10082 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
10085 if (cmd == NULL) {
10086 if (argc != 1)
10087 usage(0, 1);
10088 /* No command specified; try log with a path */
10089 error = tog_log_with_path(argc, argv);
10090 } else {
10091 if (hflag)
10092 cmd->cmd_usage();
10093 else
10094 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
10097 if (using_mock_io) {
10098 io_err = tog_io_close();
10099 if (error == NULL)
10100 error = io_err;
10102 endwin();
10103 if (cmd_argv) {
10104 int i;
10105 for (i = 0; i < argc; i++)
10106 free(cmd_argv[i]);
10107 free(cmd_argv);
10110 if (error && error->code != GOT_ERR_CANCELLED &&
10111 error->code != GOT_ERR_EOF &&
10112 error->code != GOT_ERR_PRIVSEP_EXIT &&
10113 error->code != GOT_ERR_PRIVSEP_PIPE &&
10114 !(error->code == GOT_ERR_ERRNO && errno == EINTR)) {
10115 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10116 return 1;
10118 return 0;