Blob


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