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 "got_compat.h"
19 #include <sys/queue.h>
20 #include <sys/stat.h>
21 #include <sys/ioctl.h>
23 #include <ctype.h>
24 #include <errno.h>
25 #if defined(__FreeBSD__) || defined(__APPLE__)
26 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
27 #endif
28 #include <curses.h>
29 #include <panel.h>
30 #include <locale.h>
31 #include <signal.h>
32 #include <stdlib.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <getopt.h>
36 #include <string.h>
37 #include <err.h>
38 #include <unistd.h>
39 #include <limits.h>
40 #include <wchar.h>
41 #include <time.h>
42 #include <pthread.h>
43 #include <libgen.h>
44 #include <regex.h>
45 #include <sched.h>
47 #include "got_version.h"
48 #include "got_error.h"
49 #include "got_object.h"
50 #include "got_reference.h"
51 #include "got_repository.h"
52 #include "got_diff.h"
53 #include "got_opentemp.h"
54 #include "got_utf8.h"
55 #include "got_cancel.h"
56 #include "got_commit_graph.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_path.h"
60 #include "got_worktree.h"
61 #include "got_keyword.h"
63 #ifndef MIN
64 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
65 #endif
67 #ifndef MAX
68 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
69 #endif
71 #ifndef CTRL
72 #define CTRL(x) ((x) & 0x1f)
73 #endif
75 #ifndef nitems
76 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
77 #endif
79 struct tog_cmd {
80 const char *name;
81 const struct got_error *(*cmd_main)(int, char *[]);
82 void (*cmd_usage)(void);
83 };
85 __dead static void usage(int, int);
86 __dead static void usage_log(void);
87 __dead static void usage_diff(void);
88 __dead static void usage_blame(void);
89 __dead static void usage_tree(void);
90 __dead static void usage_ref(void);
92 static const struct got_error* cmd_log(int, char *[]);
93 static const struct got_error* cmd_diff(int, char *[]);
94 static const struct got_error* cmd_blame(int, char *[]);
95 static const struct got_error* cmd_tree(int, char *[]);
96 static const struct got_error* cmd_ref(int, char *[]);
98 static const struct tog_cmd tog_commands[] = {
99 { "log", cmd_log, usage_log },
100 { "diff", cmd_diff, usage_diff },
101 { "blame", cmd_blame, usage_blame },
102 { "tree", cmd_tree, usage_tree },
103 { "ref", cmd_ref, usage_ref },
104 };
106 enum tog_view_type {
107 TOG_VIEW_DIFF,
108 TOG_VIEW_LOG,
109 TOG_VIEW_BLAME,
110 TOG_VIEW_TREE,
111 TOG_VIEW_REF,
112 TOG_VIEW_HELP
113 };
115 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
116 enum tog_keymap_type {
117 TOG_KEYMAP_KEYS = -2,
118 TOG_KEYMAP_GLOBAL,
119 TOG_KEYMAP_DIFF,
120 TOG_KEYMAP_LOG,
121 TOG_KEYMAP_BLAME,
122 TOG_KEYMAP_TREE,
123 TOG_KEYMAP_REF,
124 TOG_KEYMAP_HELP
125 };
127 enum tog_view_mode {
128 TOG_VIEW_SPLIT_NONE,
129 TOG_VIEW_SPLIT_VERT,
130 TOG_VIEW_SPLIT_HRZN
131 };
133 #define HSPLIT_SCALE 0.3f /* default horizontal split scale */
135 #define TOG_EOF_STRING "(END)"
137 struct commit_queue_entry {
138 TAILQ_ENTRY(commit_queue_entry) entry;
139 struct got_object_id *id;
140 struct got_commit_object *commit;
141 int idx;
142 };
143 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
144 struct commit_queue {
145 int ncommits;
146 struct commit_queue_head head;
147 };
149 struct tog_color {
150 STAILQ_ENTRY(tog_color) entry;
151 regex_t regex;
152 short colorpair;
153 };
154 STAILQ_HEAD(tog_colors, tog_color);
156 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
157 static struct got_reflist_object_id_map *tog_refs_idmap;
158 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
160 static const struct got_error *
161 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
162 struct got_reference* re2)
164 const char *name1 = got_ref_get_name(re1);
165 const char *name2 = got_ref_get_name(re2);
166 int isbackup1, isbackup2;
168 /* Sort backup refs towards the bottom of the list. */
169 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
170 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
171 if (!isbackup1 && isbackup2) {
172 *cmp = -1;
173 return NULL;
174 } else if (isbackup1 && !isbackup2) {
175 *cmp = 1;
176 return NULL;
179 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
180 return NULL;
183 static const struct got_error *
184 tog_load_refs(struct got_repository *repo, int sort_by_date)
186 const struct got_error *err;
188 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
189 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
190 repo);
191 if (err)
192 return err;
194 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
195 repo);
198 static void
199 tog_free_refs(void)
201 if (tog_refs_idmap) {
202 got_reflist_object_id_map_free(tog_refs_idmap);
203 tog_refs_idmap = NULL;
205 got_ref_list_free(&tog_refs);
208 static const struct got_error *
209 add_color(struct tog_colors *colors, const char *pattern,
210 int idx, short color)
212 const struct got_error *err = NULL;
213 struct tog_color *tc;
214 int regerr = 0;
216 if (idx < 1 || idx > COLOR_PAIRS - 1)
217 return NULL;
219 init_pair(idx, color, -1);
221 tc = calloc(1, sizeof(*tc));
222 if (tc == NULL)
223 return got_error_from_errno("calloc");
224 regerr = regcomp(&tc->regex, pattern,
225 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
226 if (regerr) {
227 static char regerr_msg[512];
228 static char err_msg[512];
229 regerror(regerr, &tc->regex, regerr_msg,
230 sizeof(regerr_msg));
231 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
232 regerr_msg);
233 err = got_error_msg(GOT_ERR_REGEX, err_msg);
234 free(tc);
235 return err;
237 tc->colorpair = idx;
238 STAILQ_INSERT_HEAD(colors, tc, entry);
239 return NULL;
242 static void
243 free_colors(struct tog_colors *colors)
245 struct tog_color *tc;
247 while (!STAILQ_EMPTY(colors)) {
248 tc = STAILQ_FIRST(colors);
249 STAILQ_REMOVE_HEAD(colors, entry);
250 regfree(&tc->regex);
251 free(tc);
255 static struct tog_color *
256 get_color(struct tog_colors *colors, int colorpair)
258 struct tog_color *tc = NULL;
260 STAILQ_FOREACH(tc, colors, entry) {
261 if (tc->colorpair == colorpair)
262 return tc;
265 return NULL;
268 static int
269 default_color_value(const char *envvar)
271 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
272 return COLOR_MAGENTA;
273 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
274 return COLOR_CYAN;
275 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
276 return COLOR_YELLOW;
277 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
278 return COLOR_GREEN;
279 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
280 return COLOR_MAGENTA;
281 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
282 return COLOR_MAGENTA;
283 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
284 return COLOR_CYAN;
285 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
286 return COLOR_GREEN;
287 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
288 return COLOR_GREEN;
289 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
290 return COLOR_CYAN;
291 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
292 return COLOR_YELLOW;
293 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
294 return COLOR_GREEN;
295 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
296 return COLOR_MAGENTA;
297 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
298 return COLOR_YELLOW;
299 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
300 return COLOR_CYAN;
302 return -1;
305 static int
306 get_color_value(const char *envvar)
308 const char *val = getenv(envvar);
310 if (val == NULL)
311 return default_color_value(envvar);
313 if (strcasecmp(val, "black") == 0)
314 return COLOR_BLACK;
315 if (strcasecmp(val, "red") == 0)
316 return COLOR_RED;
317 if (strcasecmp(val, "green") == 0)
318 return COLOR_GREEN;
319 if (strcasecmp(val, "yellow") == 0)
320 return COLOR_YELLOW;
321 if (strcasecmp(val, "blue") == 0)
322 return COLOR_BLUE;
323 if (strcasecmp(val, "magenta") == 0)
324 return COLOR_MAGENTA;
325 if (strcasecmp(val, "cyan") == 0)
326 return COLOR_CYAN;
327 if (strcasecmp(val, "white") == 0)
328 return COLOR_WHITE;
329 if (strcasecmp(val, "default") == 0)
330 return -1;
332 return default_color_value(envvar);
335 struct tog_diff_view_state {
336 struct got_object_id *id1, *id2;
337 const char *label1, *label2;
338 FILE *f, *f1, *f2;
339 int fd1, fd2;
340 int lineno;
341 int first_displayed_line;
342 int last_displayed_line;
343 int eof;
344 int diff_context;
345 int ignore_whitespace;
346 int force_text_diff;
347 struct got_repository *repo;
348 struct got_diff_line *lines;
349 size_t nlines;
350 int matched_line;
351 int selected_line;
353 /* passed from log or blame view; may be NULL */
354 struct tog_view *parent_view;
355 };
357 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
358 static volatile sig_atomic_t tog_thread_error;
360 struct tog_log_thread_args {
361 pthread_cond_t need_commits;
362 pthread_cond_t commit_loaded;
363 int commits_needed;
364 int load_all;
365 struct got_commit_graph *graph;
366 struct commit_queue *real_commits;
367 const char *in_repo_path;
368 struct got_object_id *start_id;
369 struct got_repository *repo;
370 int *pack_fds;
371 int log_complete;
372 sig_atomic_t *quit;
373 struct commit_queue_entry **first_displayed_entry;
374 struct commit_queue_entry **selected_entry;
375 int *searching;
376 int *search_next_done;
377 regex_t *regex;
378 int *limiting;
379 int limit_match;
380 regex_t *limit_regex;
381 struct commit_queue *limit_commits;
382 };
384 struct tog_log_view_state {
385 struct commit_queue *commits;
386 struct commit_queue_entry *first_displayed_entry;
387 struct commit_queue_entry *last_displayed_entry;
388 struct commit_queue_entry *selected_entry;
389 struct commit_queue real_commits;
390 int selected;
391 char *in_repo_path;
392 char *head_ref_name;
393 int log_branches;
394 struct got_repository *repo;
395 struct got_object_id *start_id;
396 sig_atomic_t quit;
397 pthread_t thread;
398 struct tog_log_thread_args thread_args;
399 struct commit_queue_entry *matched_entry;
400 struct commit_queue_entry *search_entry;
401 struct tog_colors colors;
402 int use_committer;
403 int limit_view;
404 regex_t limit_regex;
405 struct commit_queue limit_commits;
406 };
408 #define TOG_COLOR_DIFF_MINUS 1
409 #define TOG_COLOR_DIFF_PLUS 2
410 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
411 #define TOG_COLOR_DIFF_META 4
412 #define TOG_COLOR_TREE_SUBMODULE 5
413 #define TOG_COLOR_TREE_SYMLINK 6
414 #define TOG_COLOR_TREE_DIRECTORY 7
415 #define TOG_COLOR_TREE_EXECUTABLE 8
416 #define TOG_COLOR_COMMIT 9
417 #define TOG_COLOR_AUTHOR 10
418 #define TOG_COLOR_DATE 11
419 #define TOG_COLOR_REFS_HEADS 12
420 #define TOG_COLOR_REFS_TAGS 13
421 #define TOG_COLOR_REFS_REMOTES 14
422 #define TOG_COLOR_REFS_BACKUP 15
424 struct tog_blame_cb_args {
425 struct tog_blame_line *lines; /* one per line */
426 int nlines;
428 struct tog_view *view;
429 struct got_object_id *commit_id;
430 int *quit;
431 };
433 struct tog_blame_thread_args {
434 const char *path;
435 struct got_repository *repo;
436 struct tog_blame_cb_args *cb_args;
437 int *complete;
438 got_cancel_cb cancel_cb;
439 void *cancel_arg;
440 pthread_cond_t blame_complete;
441 };
443 struct tog_blame {
444 FILE *f;
445 off_t filesize;
446 struct tog_blame_line *lines;
447 int nlines;
448 off_t *line_offsets;
449 pthread_t thread;
450 struct tog_blame_thread_args thread_args;
451 struct tog_blame_cb_args cb_args;
452 const char *path;
453 int *pack_fds;
454 };
456 struct tog_blame_view_state {
457 int first_displayed_line;
458 int last_displayed_line;
459 int selected_line;
460 int last_diffed_line;
461 int blame_complete;
462 int eof;
463 int done;
464 struct got_object_id_queue blamed_commits;
465 struct got_object_qid *blamed_commit;
466 char *path;
467 struct got_repository *repo;
468 struct got_object_id *commit_id;
469 struct got_object_id *id_to_log;
470 struct tog_blame blame;
471 int matched_line;
472 struct tog_colors colors;
473 };
475 struct tog_parent_tree {
476 TAILQ_ENTRY(tog_parent_tree) entry;
477 struct got_tree_object *tree;
478 struct got_tree_entry *first_displayed_entry;
479 struct got_tree_entry *selected_entry;
480 int selected;
481 };
483 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
485 struct tog_tree_view_state {
486 char *tree_label;
487 struct got_object_id *commit_id;/* commit which this tree belongs to */
488 struct got_tree_object *root; /* the commit's root tree entry */
489 struct got_tree_object *tree; /* currently displayed (sub-)tree */
490 struct got_tree_entry *first_displayed_entry;
491 struct got_tree_entry *last_displayed_entry;
492 struct got_tree_entry *selected_entry;
493 int ndisplayed, selected, show_ids;
494 struct tog_parent_trees parents; /* parent trees of current sub-tree */
495 char *head_ref_name;
496 struct got_repository *repo;
497 struct got_tree_entry *matched_entry;
498 struct tog_colors colors;
499 };
501 struct tog_reflist_entry {
502 TAILQ_ENTRY(tog_reflist_entry) entry;
503 struct got_reference *ref;
504 int idx;
505 };
507 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
509 struct tog_ref_view_state {
510 struct tog_reflist_head refs;
511 struct tog_reflist_entry *first_displayed_entry;
512 struct tog_reflist_entry *last_displayed_entry;
513 struct tog_reflist_entry *selected_entry;
514 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
515 struct got_repository *repo;
516 struct tog_reflist_entry *matched_entry;
517 struct tog_colors colors;
518 };
520 struct tog_help_view_state {
521 FILE *f;
522 off_t *line_offsets;
523 size_t nlines;
524 int lineno;
525 int first_displayed_line;
526 int last_displayed_line;
527 int eof;
528 int matched_line;
529 int selected_line;
530 int all;
531 enum tog_keymap_type type;
532 };
534 #define GENERATE_HELP \
535 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
536 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
537 KEY_("k C-p Up", "Move cursor or page up one line"), \
538 KEY_("j C-n Down", "Move cursor or page down one line"), \
539 KEY_("C-b b PgUp", "Scroll the view up one page"), \
540 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
541 KEY_("C-u u", "Scroll the view up one half page"), \
542 KEY_("C-d d", "Scroll the view down one half page"), \
543 KEY_("g", "Go to line N (default: first line)"), \
544 KEY_("Home =", "Go to the first line"), \
545 KEY_("G", "Go to line N (default: last line)"), \
546 KEY_("End *", "Go to the last line"), \
547 KEY_("l Right", "Scroll the view right"), \
548 KEY_("h Left", "Scroll the view left"), \
549 KEY_("$", "Scroll view to the rightmost position"), \
550 KEY_("0", "Scroll view to the leftmost position"), \
551 KEY_("-", "Decrease size of the focussed split"), \
552 KEY_("+", "Increase size of the focussed split"), \
553 KEY_("Tab", "Switch focus between views"), \
554 KEY_("F", "Toggle fullscreen mode"), \
555 KEY_("S", "Switch split-screen layout"), \
556 KEY_("/", "Open prompt to enter search term"), \
557 KEY_("n", "Find next line/token matching the current search term"), \
558 KEY_("N", "Find previous line/token matching the current search term"),\
559 KEY_("q", "Quit the focussed view; Quit help screen"), \
560 KEY_("Q", "Quit tog"), \
562 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
563 KEY_("< ,", "Move cursor up one commit"), \
564 KEY_("> .", "Move cursor down one commit"), \
565 KEY_("Enter", "Open diff view of the selected commit"), \
566 KEY_("B", "Reload the log view and toggle display of merged commits"), \
567 KEY_("R", "Open ref view of all repository references"), \
568 KEY_("T", "Display tree view of the repository from the selected" \
569 " commit"), \
570 KEY_("@", "Toggle between displaying author and committer name"), \
571 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
572 KEY_("C-g Backspace", "Cancel current search or log operation"), \
573 KEY_("C-l", "Reload the log view with new commits in the repository"), \
575 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
576 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
577 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
578 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
579 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
580 " data"), \
581 KEY_("(", "Go to the previous file in the diff"), \
582 KEY_(")", "Go to the next file in the diff"), \
583 KEY_("{", "Go to the previous hunk in the diff"), \
584 KEY_("}", "Go to the next hunk in the diff"), \
585 KEY_("[", "Decrease the number of context lines"), \
586 KEY_("]", "Increase the number of context lines"), \
587 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
589 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
590 KEY_("Enter", "Display diff view of the selected line's commit"), \
591 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
592 KEY_("L", "Open log view for the currently selected annotated line"), \
593 KEY_("C", "Reload view with the previously blamed commit"), \
594 KEY_("c", "Reload view with the version of the file found in the" \
595 " selected line's commit"), \
596 KEY_("p", "Reload view with the version of the file found in the" \
597 " selected line's parent commit"), \
599 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
600 KEY_("Enter", "Enter selected directory or open blame view of the" \
601 " selected file"), \
602 KEY_("L", "Open log view for the selected entry"), \
603 KEY_("R", "Open ref view of all repository references"), \
604 KEY_("i", "Show object IDs for all tree entries"), \
605 KEY_("Backspace", "Return to the parent directory"), \
607 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
608 KEY_("Enter", "Display log view of the selected reference"), \
609 KEY_("T", "Display tree view of the selected reference"), \
610 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
611 KEY_("m", "Toggle display of last modified date for each reference"), \
612 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
613 KEY_("C-l", "Reload view with all repository references")
615 struct tog_key_map {
616 const char *keys;
617 const char *info;
618 enum tog_keymap_type type;
619 };
621 /* curses io for tog regress */
622 struct tog_io {
623 FILE *cin;
624 FILE *cout;
625 FILE *f;
626 FILE *sdump;
627 int wait_for_ui;
628 } tog_io;
629 static int using_mock_io;
631 #define TOG_KEY_SCRDUMP SHRT_MIN
633 /*
634 * We implement two types of views: parent views and child views.
636 * The 'Tab' key switches focus between a parent view and its child view.
637 * Child views are shown side-by-side to their parent view, provided
638 * there is enough screen estate.
640 * When a new view is opened from within a parent view, this new view
641 * becomes a child view of the parent view, replacing any existing child.
643 * When a new view is opened from within a child view, this new view
644 * becomes a parent view which will obscure the views below until the
645 * user quits the new parent view by typing 'q'.
647 * This list of views contains parent views only.
648 * Child views are only pointed to by their parent view.
649 */
650 TAILQ_HEAD(tog_view_list_head, tog_view);
652 struct tog_view {
653 TAILQ_ENTRY(tog_view) entry;
654 WINDOW *window;
655 PANEL *panel;
656 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
657 int resized_y, resized_x; /* begin_y/x based on user resizing */
658 int maxx, x; /* max column and current start column */
659 int lines, cols; /* copies of LINES and COLS */
660 int nscrolled, offset; /* lines scrolled and hsplit line offset */
661 int gline, hiline; /* navigate to and highlight this nG line */
662 int ch, count; /* current keymap and count prefix */
663 int resized; /* set when in a resize event */
664 int focussed; /* Only set on one parent or child view at a time. */
665 int dying;
666 struct tog_view *parent;
667 struct tog_view *child;
669 /*
670 * This flag is initially set on parent views when a new child view
671 * is created. It gets toggled when the 'Tab' key switches focus
672 * between parent and child.
673 * The flag indicates whether focus should be passed on to our child
674 * view if this parent view gets picked for focus after another parent
675 * view was closed. This prevents child views from losing focus in such
676 * situations.
677 */
678 int focus_child;
680 enum tog_view_mode mode;
681 /* type-specific state */
682 enum tog_view_type type;
683 union {
684 struct tog_diff_view_state diff;
685 struct tog_log_view_state log;
686 struct tog_blame_view_state blame;
687 struct tog_tree_view_state tree;
688 struct tog_ref_view_state ref;
689 struct tog_help_view_state help;
690 } state;
692 const struct got_error *(*show)(struct tog_view *);
693 const struct got_error *(*input)(struct tog_view **,
694 struct tog_view *, int);
695 const struct got_error *(*reset)(struct tog_view *);
696 const struct got_error *(*resize)(struct tog_view *, int);
697 const struct got_error *(*close)(struct tog_view *);
699 const struct got_error *(*search_start)(struct tog_view *);
700 const struct got_error *(*search_next)(struct tog_view *);
701 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
702 int **, int **, int **, int **);
703 int search_started;
704 int searching;
705 #define TOG_SEARCH_FORWARD 1
706 #define TOG_SEARCH_BACKWARD 2
707 int search_next_done;
708 #define TOG_SEARCH_HAVE_MORE 1
709 #define TOG_SEARCH_NO_MORE 2
710 #define TOG_SEARCH_HAVE_NONE 3
711 regex_t regex;
712 regmatch_t regmatch;
713 const char *action;
714 };
716 static const struct got_error *open_diff_view(struct tog_view *,
717 struct got_object_id *, struct got_object_id *,
718 const char *, const char *, int, int, int, struct tog_view *,
719 struct got_repository *);
720 static const struct got_error *show_diff_view(struct tog_view *);
721 static const struct got_error *input_diff_view(struct tog_view **,
722 struct tog_view *, int);
723 static const struct got_error *reset_diff_view(struct tog_view *);
724 static const struct got_error* close_diff_view(struct tog_view *);
725 static const struct got_error *search_start_diff_view(struct tog_view *);
726 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
727 size_t *, int **, int **, int **, int **);
728 static const struct got_error *search_next_view_match(struct tog_view *);
730 static const struct got_error *open_log_view(struct tog_view *,
731 struct got_object_id *, struct got_repository *,
732 const char *, const char *, int);
733 static const struct got_error * show_log_view(struct tog_view *);
734 static const struct got_error *input_log_view(struct tog_view **,
735 struct tog_view *, int);
736 static const struct got_error *resize_log_view(struct tog_view *, int);
737 static const struct got_error *close_log_view(struct tog_view *);
738 static const struct got_error *search_start_log_view(struct tog_view *);
739 static const struct got_error *search_next_log_view(struct tog_view *);
741 static const struct got_error *open_blame_view(struct tog_view *, char *,
742 struct got_object_id *, struct got_repository *);
743 static const struct got_error *show_blame_view(struct tog_view *);
744 static const struct got_error *input_blame_view(struct tog_view **,
745 struct tog_view *, int);
746 static const struct got_error *reset_blame_view(struct tog_view *);
747 static const struct got_error *close_blame_view(struct tog_view *);
748 static const struct got_error *search_start_blame_view(struct tog_view *);
749 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
750 size_t *, int **, int **, int **, int **);
752 static const struct got_error *open_tree_view(struct tog_view *,
753 struct got_object_id *, const char *, struct got_repository *);
754 static const struct got_error *show_tree_view(struct tog_view *);
755 static const struct got_error *input_tree_view(struct tog_view **,
756 struct tog_view *, int);
757 static const struct got_error *close_tree_view(struct tog_view *);
758 static const struct got_error *search_start_tree_view(struct tog_view *);
759 static const struct got_error *search_next_tree_view(struct tog_view *);
761 static const struct got_error *open_ref_view(struct tog_view *,
762 struct got_repository *);
763 static const struct got_error *show_ref_view(struct tog_view *);
764 static const struct got_error *input_ref_view(struct tog_view **,
765 struct tog_view *, int);
766 static const struct got_error *close_ref_view(struct tog_view *);
767 static const struct got_error *search_start_ref_view(struct tog_view *);
768 static const struct got_error *search_next_ref_view(struct tog_view *);
770 static const struct got_error *open_help_view(struct tog_view *,
771 struct tog_view *);
772 static const struct got_error *show_help_view(struct tog_view *);
773 static const struct got_error *input_help_view(struct tog_view **,
774 struct tog_view *, int);
775 static const struct got_error *reset_help_view(struct tog_view *);
776 static const struct got_error* close_help_view(struct tog_view *);
777 static const struct got_error *search_start_help_view(struct tog_view *);
778 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
779 size_t *, int **, int **, int **, int **);
781 static volatile sig_atomic_t tog_sigwinch_received;
782 static volatile sig_atomic_t tog_sigpipe_received;
783 static volatile sig_atomic_t tog_sigcont_received;
784 static volatile sig_atomic_t tog_sigint_received;
785 static volatile sig_atomic_t tog_sigterm_received;
787 static void
788 tog_sigwinch(int signo)
790 tog_sigwinch_received = 1;
793 static void
794 tog_sigpipe(int signo)
796 tog_sigpipe_received = 1;
799 static void
800 tog_sigcont(int signo)
802 tog_sigcont_received = 1;
805 static void
806 tog_sigint(int signo)
808 tog_sigint_received = 1;
811 static void
812 tog_sigterm(int signo)
814 tog_sigterm_received = 1;
817 static int
818 tog_fatal_signal_received(void)
820 return (tog_sigpipe_received ||
821 tog_sigint_received || tog_sigterm_received);
824 static const struct got_error *
825 view_close(struct tog_view *view)
827 const struct got_error *err = NULL, *child_err = NULL;
829 if (view->child) {
830 child_err = view_close(view->child);
831 view->child = NULL;
833 if (view->close)
834 err = view->close(view);
835 if (view->panel)
836 del_panel(view->panel);
837 if (view->window)
838 delwin(view->window);
839 free(view);
840 return err ? err : child_err;
843 static struct tog_view *
844 view_open(int nlines, int ncols, int begin_y, int begin_x,
845 enum tog_view_type type)
847 struct tog_view *view = calloc(1, sizeof(*view));
849 if (view == NULL)
850 return NULL;
852 view->type = type;
853 view->lines = LINES;
854 view->cols = COLS;
855 view->nlines = nlines ? nlines : LINES - begin_y;
856 view->ncols = ncols ? ncols : COLS - begin_x;
857 view->begin_y = begin_y;
858 view->begin_x = begin_x;
859 view->window = newwin(nlines, ncols, begin_y, begin_x);
860 if (view->window == NULL) {
861 view_close(view);
862 return NULL;
864 view->panel = new_panel(view->window);
865 if (view->panel == NULL ||
866 set_panel_userptr(view->panel, view) != OK) {
867 view_close(view);
868 return NULL;
871 keypad(view->window, TRUE);
872 return view;
875 static int
876 view_split_begin_x(int begin_x)
878 if (begin_x > 0 || COLS < 120)
879 return 0;
880 return (COLS - MAX(COLS / 2, 80));
883 /* XXX Stub till we decide what to do. */
884 static int
885 view_split_begin_y(int lines)
887 return lines * HSPLIT_SCALE;
890 static const struct got_error *view_resize(struct tog_view *);
892 static const struct got_error *
893 view_splitscreen(struct tog_view *view)
895 const struct got_error *err = NULL;
897 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
898 if (view->resized_y && view->resized_y < view->lines)
899 view->begin_y = view->resized_y;
900 else
901 view->begin_y = view_split_begin_y(view->nlines);
902 view->begin_x = 0;
903 } else if (!view->resized) {
904 if (view->resized_x && view->resized_x < view->cols - 1 &&
905 view->cols > 119)
906 view->begin_x = view->resized_x;
907 else
908 view->begin_x = view_split_begin_x(0);
909 view->begin_y = 0;
911 view->nlines = LINES - view->begin_y;
912 view->ncols = COLS - view->begin_x;
913 view->lines = LINES;
914 view->cols = COLS;
915 err = view_resize(view);
916 if (err)
917 return err;
919 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
920 view->parent->nlines = view->begin_y;
922 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
923 return got_error_from_errno("mvwin");
925 return NULL;
928 static const struct got_error *
929 view_fullscreen(struct tog_view *view)
931 const struct got_error *err = NULL;
933 view->begin_x = 0;
934 view->begin_y = view->resized ? view->begin_y : 0;
935 view->nlines = view->resized ? view->nlines : LINES;
936 view->ncols = COLS;
937 view->lines = LINES;
938 view->cols = COLS;
939 err = view_resize(view);
940 if (err)
941 return err;
943 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
944 return got_error_from_errno("mvwin");
946 return NULL;
949 static int
950 view_is_parent_view(struct tog_view *view)
952 return view->parent == NULL;
955 static int
956 view_is_splitscreen(struct tog_view *view)
958 return view->begin_x > 0 || view->begin_y > 0;
961 static int
962 view_is_fullscreen(struct tog_view *view)
964 return view->nlines == LINES && view->ncols == COLS;
967 static int
968 view_is_hsplit_top(struct tog_view *view)
970 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
971 view_is_splitscreen(view->child);
974 static void
975 view_border(struct tog_view *view)
977 PANEL *panel;
978 const struct tog_view *view_above;
980 if (view->parent)
981 return view_border(view->parent);
983 panel = panel_above(view->panel);
984 if (panel == NULL)
985 return;
987 view_above = panel_userptr(panel);
988 if (view->mode == TOG_VIEW_SPLIT_HRZN)
989 mvwhline(view->window, view_above->begin_y - 1,
990 view->begin_x, ACS_HLINE, view->ncols);
991 else
992 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
993 ACS_VLINE, view->nlines);
996 static const struct got_error *view_init_hsplit(struct tog_view *, int);
997 static const struct got_error *request_log_commits(struct tog_view *);
998 static const struct got_error *offset_selection_down(struct tog_view *);
999 static void offset_selection_up(struct tog_view *);
1000 static void view_get_split(struct tog_view *, int *, int *);
1002 static const struct got_error *
1003 view_resize(struct tog_view *view)
1005 const struct got_error *err = NULL;
1006 int dif, nlines, ncols;
1008 dif = LINES - view->lines; /* line difference */
1010 if (view->lines > LINES)
1011 nlines = view->nlines - (view->lines - LINES);
1012 else
1013 nlines = view->nlines + (LINES - view->lines);
1014 if (view->cols > COLS)
1015 ncols = view->ncols - (view->cols - COLS);
1016 else
1017 ncols = view->ncols + (COLS - view->cols);
1019 if (view->child) {
1020 int hs = view->child->begin_y;
1022 if (!view_is_fullscreen(view))
1023 view->child->begin_x = view_split_begin_x(view->begin_x);
1024 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1025 view->child->begin_x == 0) {
1026 ncols = COLS;
1028 view_fullscreen(view->child);
1029 if (view->child->focussed)
1030 show_panel(view->child->panel);
1031 else
1032 show_panel(view->panel);
1033 } else {
1034 ncols = view->child->begin_x;
1036 view_splitscreen(view->child);
1037 show_panel(view->child->panel);
1040 * XXX This is ugly and needs to be moved into the above
1041 * logic but "works" for now and my attempts at moving it
1042 * break either 'tab' or 'F' key maps in horizontal splits.
1044 if (hs) {
1045 err = view_splitscreen(view->child);
1046 if (err)
1047 return err;
1048 if (dif < 0) { /* top split decreased */
1049 err = offset_selection_down(view);
1050 if (err)
1051 return err;
1053 view_border(view);
1054 update_panels();
1055 doupdate();
1056 show_panel(view->child->panel);
1057 nlines = view->nlines;
1059 } else if (view->parent == NULL)
1060 ncols = COLS;
1062 if (view->resize && dif > 0) {
1063 err = view->resize(view, dif);
1064 if (err)
1065 return err;
1068 if (wresize(view->window, nlines, ncols) == ERR)
1069 return got_error_from_errno("wresize");
1070 if (replace_panel(view->panel, view->window) == ERR)
1071 return got_error_from_errno("replace_panel");
1072 wclear(view->window);
1074 view->nlines = nlines;
1075 view->ncols = ncols;
1076 view->lines = LINES;
1077 view->cols = COLS;
1079 return NULL;
1082 static const struct got_error *
1083 resize_log_view(struct tog_view *view, int increase)
1085 struct tog_log_view_state *s = &view->state.log;
1086 const struct got_error *err = NULL;
1087 int n = 0;
1089 if (s->selected_entry)
1090 n = s->selected_entry->idx + view->lines - s->selected;
1093 * Request commits to account for the increased
1094 * height so we have enough to populate the view.
1096 if (s->commits->ncommits < n) {
1097 view->nscrolled = n - s->commits->ncommits + increase + 1;
1098 err = request_log_commits(view);
1101 return err;
1104 static void
1105 view_adjust_offset(struct tog_view *view, int n)
1107 if (n == 0)
1108 return;
1110 if (view->parent && view->parent->offset) {
1111 if (view->parent->offset + n >= 0)
1112 view->parent->offset += n;
1113 else
1114 view->parent->offset = 0;
1115 } else if (view->offset) {
1116 if (view->offset - n >= 0)
1117 view->offset -= n;
1118 else
1119 view->offset = 0;
1123 static const struct got_error *
1124 view_resize_split(struct tog_view *view, int resize)
1126 const struct got_error *err = NULL;
1127 struct tog_view *v = NULL;
1129 if (view->parent)
1130 v = view->parent;
1131 else
1132 v = view;
1134 if (!v->child || !view_is_splitscreen(v->child))
1135 return NULL;
1137 v->resized = v->child->resized = resize; /* lock for resize event */
1139 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1140 if (v->child->resized_y)
1141 v->child->begin_y = v->child->resized_y;
1142 if (view->parent)
1143 v->child->begin_y -= resize;
1144 else
1145 v->child->begin_y += resize;
1146 if (v->child->begin_y < 3) {
1147 view->count = 0;
1148 v->child->begin_y = 3;
1149 } else if (v->child->begin_y > LINES - 1) {
1150 view->count = 0;
1151 v->child->begin_y = LINES - 1;
1153 v->ncols = COLS;
1154 v->child->ncols = COLS;
1155 view_adjust_offset(view, resize);
1156 err = view_init_hsplit(v, v->child->begin_y);
1157 if (err)
1158 return err;
1159 v->child->resized_y = v->child->begin_y;
1160 } else {
1161 if (v->child->resized_x)
1162 v->child->begin_x = v->child->resized_x;
1163 if (view->parent)
1164 v->child->begin_x -= resize;
1165 else
1166 v->child->begin_x += resize;
1167 if (v->child->begin_x < 11) {
1168 view->count = 0;
1169 v->child->begin_x = 11;
1170 } else if (v->child->begin_x > COLS - 1) {
1171 view->count = 0;
1172 v->child->begin_x = COLS - 1;
1174 v->child->resized_x = v->child->begin_x;
1177 v->child->mode = v->mode;
1178 v->child->nlines = v->lines - v->child->begin_y;
1179 v->child->ncols = v->cols - v->child->begin_x;
1180 v->focus_child = 1;
1182 err = view_fullscreen(v);
1183 if (err)
1184 return err;
1185 err = view_splitscreen(v->child);
1186 if (err)
1187 return err;
1189 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1190 err = offset_selection_down(v->child);
1191 if (err)
1192 return err;
1195 if (v->resize)
1196 err = v->resize(v, 0);
1197 else if (v->child->resize)
1198 err = v->child->resize(v->child, 0);
1200 v->resized = v->child->resized = 0;
1202 return err;
1205 static void
1206 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1208 struct tog_view *v = src->child ? src->child : src;
1210 dst->resized_x = v->resized_x;
1211 dst->resized_y = v->resized_y;
1214 static const struct got_error *
1215 view_close_child(struct tog_view *view)
1217 const struct got_error *err = NULL;
1219 if (view->child == NULL)
1220 return NULL;
1222 err = view_close(view->child);
1223 view->child = NULL;
1224 return err;
1227 static const struct got_error *
1228 view_set_child(struct tog_view *view, struct tog_view *child)
1230 const struct got_error *err = NULL;
1232 view->child = child;
1233 child->parent = view;
1235 err = view_resize(view);
1236 if (err)
1237 return err;
1239 if (view->child->resized_x || view->child->resized_y)
1240 err = view_resize_split(view, 0);
1242 return err;
1245 static const struct got_error *view_dispatch_request(struct tog_view **,
1246 struct tog_view *, enum tog_view_type, int, int);
1248 static const struct got_error *
1249 view_request_new(struct tog_view **requested, struct tog_view *view,
1250 enum tog_view_type request)
1252 struct tog_view *new_view = NULL;
1253 const struct got_error *err;
1254 int y = 0, x = 0;
1256 *requested = NULL;
1258 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1259 view_get_split(view, &y, &x);
1261 err = view_dispatch_request(&new_view, view, request, y, x);
1262 if (err)
1263 return err;
1265 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1266 request != TOG_VIEW_HELP) {
1267 err = view_init_hsplit(view, y);
1268 if (err)
1269 return err;
1272 view->focussed = 0;
1273 new_view->focussed = 1;
1274 new_view->mode = view->mode;
1275 new_view->nlines = request == TOG_VIEW_HELP ?
1276 view->lines : view->lines - y;
1278 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1279 view_transfer_size(new_view, view);
1280 err = view_close_child(view);
1281 if (err)
1282 return err;
1283 err = view_set_child(view, new_view);
1284 if (err)
1285 return err;
1286 view->focus_child = 1;
1287 } else
1288 *requested = new_view;
1290 return NULL;
1293 static void
1294 tog_resizeterm(void)
1296 int cols, lines;
1297 struct winsize size;
1299 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1300 cols = 80; /* Default */
1301 lines = 24;
1302 } else {
1303 cols = size.ws_col;
1304 lines = size.ws_row;
1306 resize_term(lines, cols);
1309 static const struct got_error *
1310 view_search_start(struct tog_view *view, int fast_refresh)
1312 const struct got_error *err = NULL;
1313 struct tog_view *v = view;
1314 char pattern[1024];
1315 int ret;
1317 if (view->search_started) {
1318 regfree(&view->regex);
1319 view->searching = 0;
1320 memset(&view->regmatch, 0, sizeof(view->regmatch));
1322 view->search_started = 0;
1324 if (view->nlines < 1)
1325 return NULL;
1327 if (view_is_hsplit_top(view))
1328 v = view->child;
1329 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1330 v = view->parent;
1332 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1333 wclrtoeol(v->window);
1335 nodelay(v->window, FALSE); /* block for search term input */
1336 nocbreak();
1337 echo();
1338 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1339 wrefresh(v->window);
1340 cbreak();
1341 noecho();
1342 nodelay(v->window, TRUE);
1343 if (!fast_refresh && !using_mock_io)
1344 halfdelay(10);
1345 if (ret == ERR)
1346 return NULL;
1348 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1349 err = view->search_start(view);
1350 if (err) {
1351 regfree(&view->regex);
1352 return err;
1354 view->search_started = 1;
1355 view->searching = TOG_SEARCH_FORWARD;
1356 view->search_next_done = 0;
1357 view->search_next(view);
1360 return NULL;
1363 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1364 static const struct got_error *
1365 switch_split(struct tog_view *view)
1367 const struct got_error *err = NULL;
1368 struct tog_view *v = NULL;
1370 if (view->parent)
1371 v = view->parent;
1372 else
1373 v = view;
1375 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1376 v->mode = TOG_VIEW_SPLIT_VERT;
1377 else
1378 v->mode = TOG_VIEW_SPLIT_HRZN;
1380 if (!v->child)
1381 return NULL;
1382 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1383 v->mode = TOG_VIEW_SPLIT_NONE;
1385 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1386 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1387 v->child->begin_y = v->child->resized_y;
1388 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1389 v->child->begin_x = v->child->resized_x;
1392 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1393 v->ncols = COLS;
1394 v->child->ncols = COLS;
1395 v->child->nscrolled = LINES - v->child->nlines;
1397 err = view_init_hsplit(v, v->child->begin_y);
1398 if (err)
1399 return err;
1401 v->child->mode = v->mode;
1402 v->child->nlines = v->lines - v->child->begin_y;
1403 v->focus_child = 1;
1405 err = view_fullscreen(v);
1406 if (err)
1407 return err;
1408 err = view_splitscreen(v->child);
1409 if (err)
1410 return err;
1412 if (v->mode == TOG_VIEW_SPLIT_NONE)
1413 v->mode = TOG_VIEW_SPLIT_VERT;
1414 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1415 err = offset_selection_down(v);
1416 if (err)
1417 return err;
1418 err = offset_selection_down(v->child);
1419 if (err)
1420 return err;
1421 } else {
1422 offset_selection_up(v);
1423 offset_selection_up(v->child);
1425 if (v->resize)
1426 err = v->resize(v, 0);
1427 else if (v->child->resize)
1428 err = v->child->resize(v->child, 0);
1430 return err;
1434 * Strip trailing whitespace from str starting at byte *n;
1435 * if *n < 0, use strlen(str). Return new str length in *n.
1437 static void
1438 strip_trailing_ws(char *str, int *n)
1440 size_t x = *n;
1442 if (str == NULL || *str == '\0')
1443 return;
1445 if (x < 0)
1446 x = strlen(str);
1448 while (x-- > 0 && isspace((unsigned char)str[x]))
1449 str[x] = '\0';
1451 *n = x + 1;
1455 * Extract visible substring of line y from the curses screen
1456 * and strip trailing whitespace. If vline is set, overwrite
1457 * line[vline] with '|' because the ACS_VLINE character is
1458 * written out as 'x'. Write the line to file f.
1460 static const struct got_error *
1461 view_write_line(FILE *f, int y, int vline)
1463 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1464 int r, w;
1466 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1467 if (r == ERR)
1468 return got_error_fmt(GOT_ERR_RANGE,
1469 "failed to extract line %d", y);
1472 * In some views, lines are padded with blanks to COLS width.
1473 * Strip them so we can diff without the -b flag when testing.
1475 strip_trailing_ws(line, &r);
1477 if (vline > 0)
1478 line[vline] = '|';
1480 w = fprintf(f, "%s\n", line);
1481 if (w != r + 1) /* \n */
1482 return got_ferror(f, GOT_ERR_IO);
1484 return NULL;
1488 * Capture the visible curses screen by writing each line to the
1489 * file at the path set via the TOG_SCR_DUMP environment variable.
1491 static const struct got_error *
1492 screendump(struct tog_view *view)
1494 const struct got_error *err;
1495 int i;
1497 err = got_opentemp_truncate(tog_io.sdump);
1498 if (err)
1499 return err;
1501 if ((view->child && view->child->begin_x) ||
1502 (view->parent && view->begin_x)) {
1503 int ncols = view->child ? view->ncols : view->parent->ncols;
1505 /* vertical splitscreen */
1506 for (i = 0; i < view->nlines; ++i) {
1507 err = view_write_line(tog_io.sdump, i, ncols - 1);
1508 if (err)
1509 goto done;
1511 } else {
1512 int hline = 0;
1514 /* fullscreen or horizontal splitscreen */
1515 if ((view->child && view->child->begin_y) ||
1516 (view->parent && view->begin_y)) /* hsplit */
1517 hline = view->child ?
1518 view->child->begin_y : view->begin_y;
1520 for (i = 0; i < view->lines; i++) {
1521 if (hline && i == hline - 1) {
1522 int c;
1524 /* ACS_HLINE writes out as 'q', overwrite it */
1525 for (c = 0; c < view->cols; ++c)
1526 fputc('-', tog_io.sdump);
1527 fputc('\n', tog_io.sdump);
1528 continue;
1531 err = view_write_line(tog_io.sdump, i, 0);
1532 if (err)
1533 goto done;
1537 done:
1538 return err;
1542 * Compute view->count from numeric input. Assign total to view->count and
1543 * return first non-numeric key entered.
1545 static int
1546 get_compound_key(struct tog_view *view, int c)
1548 struct tog_view *v = view;
1549 int x, n = 0;
1551 if (view_is_hsplit_top(view))
1552 v = view->child;
1553 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1554 v = view->parent;
1556 view->count = 0;
1557 cbreak(); /* block for input */
1558 nodelay(view->window, FALSE);
1559 wmove(v->window, v->nlines - 1, 0);
1560 wclrtoeol(v->window);
1561 waddch(v->window, ':');
1563 do {
1564 x = getcurx(v->window);
1565 if (x != ERR && x < view->ncols) {
1566 waddch(v->window, c);
1567 wrefresh(v->window);
1571 * Don't overflow. Max valid request should be the greatest
1572 * between the longest and total lines; cap at 10 million.
1574 if (n >= 9999999)
1575 n = 9999999;
1576 else
1577 n = n * 10 + (c - '0');
1578 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1580 if (c == 'G' || c == 'g') { /* nG key map */
1581 view->gline = view->hiline = n;
1582 n = 0;
1583 c = 0;
1586 /* Massage excessive or inapplicable values at the input handler. */
1587 view->count = n;
1589 return c;
1592 static void
1593 action_report(struct tog_view *view)
1595 struct tog_view *v = view;
1597 if (view_is_hsplit_top(view))
1598 v = view->child;
1599 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1600 v = view->parent;
1602 wmove(v->window, v->nlines - 1, 0);
1603 wclrtoeol(v->window);
1604 wprintw(v->window, ":%s", view->action);
1605 wrefresh(v->window);
1608 * Clear action status report. Only clear in blame view
1609 * once annotating is complete, otherwise it's too fast.
1611 if (view->type == TOG_VIEW_BLAME) {
1612 if (view->state.blame.blame_complete)
1613 view->action = NULL;
1614 } else
1615 view->action = NULL;
1619 * Read the next line from the test script and assign
1620 * key instruction to *ch. If at EOF, set the *done flag.
1622 static const struct got_error *
1623 tog_read_script_key(FILE *script, struct tog_view *view, int *ch, int *done)
1625 const struct got_error *err = NULL;
1626 char *line = NULL;
1627 size_t linesz = 0;
1629 if (view->count && --view->count) {
1630 *ch = view->ch;
1631 return NULL;
1632 } else
1633 *ch = -1;
1635 if (getline(&line, &linesz, script) == -1) {
1636 if (feof(script)) {
1637 *done = 1;
1638 goto done;
1639 } else {
1640 err = got_ferror(script, GOT_ERR_IO);
1641 goto done;
1645 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1646 tog_io.wait_for_ui = 1;
1647 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1648 *ch = KEY_ENTER;
1649 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1650 *ch = KEY_RIGHT;
1651 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1652 *ch = KEY_LEFT;
1653 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1654 *ch = KEY_DOWN;
1655 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1656 *ch = KEY_UP;
1657 else if (strncasecmp(line, "TAB", 3) == 0)
1658 *ch = '\t';
1659 else if (strncasecmp(line, "SCREENDUMP", 10) == 0)
1660 *ch = TOG_KEY_SCRDUMP;
1661 else if (isdigit((unsigned char)*line)) {
1662 char *t = line;
1664 while (isdigit((unsigned char)*t))
1665 ++t;
1666 view->ch = *ch = *t;
1667 *t = '\0';
1668 /* ignore error, view->count is 0 if instruction is invalid */
1669 view->count = strtonum(line, 0, INT_MAX, NULL);
1670 } else
1671 *ch = *line;
1673 done:
1674 free(line);
1675 return err;
1678 static const struct got_error *
1679 view_input(struct tog_view **new, int *done, struct tog_view *view,
1680 struct tog_view_list_head *views, int fast_refresh)
1682 const struct got_error *err = NULL;
1683 struct tog_view *v;
1684 int ch, errcode;
1686 *new = NULL;
1688 if (view->action)
1689 action_report(view);
1691 /* Clear "no matches" indicator. */
1692 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1693 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1694 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1695 view->count = 0;
1698 if (view->searching && !view->search_next_done) {
1699 errcode = pthread_mutex_unlock(&tog_mutex);
1700 if (errcode)
1701 return got_error_set_errno(errcode,
1702 "pthread_mutex_unlock");
1703 sched_yield();
1704 errcode = pthread_mutex_lock(&tog_mutex);
1705 if (errcode)
1706 return got_error_set_errno(errcode,
1707 "pthread_mutex_lock");
1708 view->search_next(view);
1709 return NULL;
1712 /* Allow threads to make progress while we are waiting for input. */
1713 errcode = pthread_mutex_unlock(&tog_mutex);
1714 if (errcode)
1715 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1717 if (using_mock_io) {
1718 err = tog_read_script_key(tog_io.f, view, &ch, done);
1719 if (err) {
1720 errcode = pthread_mutex_lock(&tog_mutex);
1721 return err;
1723 } else if (view->count && --view->count) {
1724 cbreak();
1725 nodelay(view->window, TRUE);
1726 ch = wgetch(view->window);
1727 /* let C-g or backspace abort unfinished count */
1728 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1729 view->count = 0;
1730 else
1731 ch = view->ch;
1732 } else {
1733 ch = wgetch(view->window);
1734 if (ch >= '1' && ch <= '9')
1735 view->ch = ch = get_compound_key(view, ch);
1737 if (view->hiline && ch != ERR && ch != 0)
1738 view->hiline = 0; /* key pressed, clear line highlight */
1739 nodelay(view->window, TRUE);
1740 errcode = pthread_mutex_lock(&tog_mutex);
1741 if (errcode)
1742 return got_error_set_errno(errcode, "pthread_mutex_lock");
1744 if (tog_sigwinch_received || tog_sigcont_received) {
1745 tog_resizeterm();
1746 tog_sigwinch_received = 0;
1747 tog_sigcont_received = 0;
1748 TAILQ_FOREACH(v, views, entry) {
1749 err = view_resize(v);
1750 if (err)
1751 return err;
1752 err = v->input(new, v, KEY_RESIZE);
1753 if (err)
1754 return err;
1755 if (v->child) {
1756 err = view_resize(v->child);
1757 if (err)
1758 return err;
1759 err = v->child->input(new, v->child,
1760 KEY_RESIZE);
1761 if (err)
1762 return err;
1763 if (v->child->resized_x || v->child->resized_y) {
1764 err = view_resize_split(v, 0);
1765 if (err)
1766 return err;
1772 switch (ch) {
1773 case '?':
1774 case 'H':
1775 case KEY_F(1):
1776 if (view->type == TOG_VIEW_HELP)
1777 err = view->reset(view);
1778 else
1779 err = view_request_new(new, view, TOG_VIEW_HELP);
1780 break;
1781 case '\t':
1782 view->count = 0;
1783 if (view->child) {
1784 view->focussed = 0;
1785 view->child->focussed = 1;
1786 view->focus_child = 1;
1787 } else if (view->parent) {
1788 view->focussed = 0;
1789 view->parent->focussed = 1;
1790 view->parent->focus_child = 0;
1791 if (!view_is_splitscreen(view)) {
1792 if (view->parent->resize) {
1793 err = view->parent->resize(view->parent,
1794 0);
1795 if (err)
1796 return err;
1798 offset_selection_up(view->parent);
1799 err = view_fullscreen(view->parent);
1800 if (err)
1801 return err;
1804 break;
1805 case 'q':
1806 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1807 if (view->parent->resize) {
1808 /* might need more commits to fill fullscreen */
1809 err = view->parent->resize(view->parent, 0);
1810 if (err)
1811 break;
1813 offset_selection_up(view->parent);
1815 err = view->input(new, view, ch);
1816 view->dying = 1;
1817 break;
1818 case 'Q':
1819 *done = 1;
1820 break;
1821 case 'F':
1822 view->count = 0;
1823 if (view_is_parent_view(view)) {
1824 if (view->child == NULL)
1825 break;
1826 if (view_is_splitscreen(view->child)) {
1827 view->focussed = 0;
1828 view->child->focussed = 1;
1829 err = view_fullscreen(view->child);
1830 } else {
1831 err = view_splitscreen(view->child);
1832 if (!err)
1833 err = view_resize_split(view, 0);
1835 if (err)
1836 break;
1837 err = view->child->input(new, view->child,
1838 KEY_RESIZE);
1839 } else {
1840 if (view_is_splitscreen(view)) {
1841 view->parent->focussed = 0;
1842 view->focussed = 1;
1843 err = view_fullscreen(view);
1844 } else {
1845 err = view_splitscreen(view);
1846 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1847 err = view_resize(view->parent);
1848 if (!err)
1849 err = view_resize_split(view, 0);
1851 if (err)
1852 break;
1853 err = view->input(new, view, KEY_RESIZE);
1855 if (err)
1856 break;
1857 if (view->resize) {
1858 err = view->resize(view, 0);
1859 if (err)
1860 break;
1862 if (view->parent) {
1863 if (view->parent->resize) {
1864 err = view->parent->resize(view->parent, 0);
1865 if (err != NULL)
1866 break;
1868 err = offset_selection_down(view->parent);
1869 if (err != NULL)
1870 break;
1872 err = offset_selection_down(view);
1873 break;
1874 case 'S':
1875 view->count = 0;
1876 err = switch_split(view);
1877 break;
1878 case '-':
1879 err = view_resize_split(view, -1);
1880 break;
1881 case '+':
1882 err = view_resize_split(view, 1);
1883 break;
1884 case KEY_RESIZE:
1885 break;
1886 case '/':
1887 view->count = 0;
1888 if (view->search_start)
1889 view_search_start(view, fast_refresh);
1890 else
1891 err = view->input(new, view, ch);
1892 break;
1893 case 'N':
1894 case 'n':
1895 if (view->search_started && view->search_next) {
1896 view->searching = (ch == 'n' ?
1897 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1898 view->search_next_done = 0;
1899 view->search_next(view);
1900 } else
1901 err = view->input(new, view, ch);
1902 break;
1903 case 'A':
1904 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1905 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1906 view->action = "Patience diff algorithm";
1907 } else {
1908 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1909 view->action = "Myers diff algorithm";
1911 TAILQ_FOREACH(v, views, entry) {
1912 if (v->reset) {
1913 err = v->reset(v);
1914 if (err)
1915 return err;
1917 if (v->child && v->child->reset) {
1918 err = v->child->reset(v->child);
1919 if (err)
1920 return err;
1923 break;
1924 case TOG_KEY_SCRDUMP:
1925 err = screendump(view);
1926 break;
1927 default:
1928 err = view->input(new, view, ch);
1929 break;
1932 return err;
1935 static int
1936 view_needs_focus_indication(struct tog_view *view)
1938 if (view_is_parent_view(view)) {
1939 if (view->child == NULL || view->child->focussed)
1940 return 0;
1941 if (!view_is_splitscreen(view->child))
1942 return 0;
1943 } else if (!view_is_splitscreen(view))
1944 return 0;
1946 return view->focussed;
1949 static const struct got_error *
1950 tog_io_close(void)
1952 const struct got_error *err = NULL;
1954 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1955 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1956 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1957 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1958 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1959 err = got_ferror(tog_io.f, GOT_ERR_IO);
1960 if (tog_io.sdump && fclose(tog_io.sdump) == EOF && err == NULL)
1961 err = got_ferror(tog_io.sdump, GOT_ERR_IO);
1963 return err;
1966 static const struct got_error *
1967 view_loop(struct tog_view *view)
1969 const struct got_error *err = NULL;
1970 struct tog_view_list_head views;
1971 struct tog_view *new_view;
1972 char *mode;
1973 int fast_refresh = 10;
1974 int done = 0, errcode;
1976 mode = getenv("TOG_VIEW_SPLIT_MODE");
1977 if (!mode || !(*mode == 'h' || *mode == 'H'))
1978 view->mode = TOG_VIEW_SPLIT_VERT;
1979 else
1980 view->mode = TOG_VIEW_SPLIT_HRZN;
1982 errcode = pthread_mutex_lock(&tog_mutex);
1983 if (errcode)
1984 return got_error_set_errno(errcode, "pthread_mutex_lock");
1986 TAILQ_INIT(&views);
1987 TAILQ_INSERT_HEAD(&views, view, entry);
1989 view->focussed = 1;
1990 err = view->show(view);
1991 if (err)
1992 return err;
1993 update_panels();
1994 doupdate();
1995 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1996 !tog_fatal_signal_received()) {
1997 /* Refresh fast during initialization, then become slower. */
1998 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
1999 halfdelay(10); /* switch to once per second */
2001 err = view_input(&new_view, &done, view, &views, fast_refresh);
2002 if (err)
2003 break;
2005 if (view->dying && view == TAILQ_FIRST(&views) &&
2006 TAILQ_NEXT(view, entry) == NULL)
2007 done = 1;
2008 if (done) {
2009 struct tog_view *v;
2012 * When we quit, scroll the screen up a single line
2013 * so we don't lose any information.
2015 TAILQ_FOREACH(v, &views, entry) {
2016 wmove(v->window, 0, 0);
2017 wdeleteln(v->window);
2018 wnoutrefresh(v->window);
2019 if (v->child && !view_is_fullscreen(v)) {
2020 wmove(v->child->window, 0, 0);
2021 wdeleteln(v->child->window);
2022 wnoutrefresh(v->child->window);
2025 doupdate();
2028 if (view->dying) {
2029 struct tog_view *v, *prev = NULL;
2031 if (view_is_parent_view(view))
2032 prev = TAILQ_PREV(view, tog_view_list_head,
2033 entry);
2034 else if (view->parent)
2035 prev = view->parent;
2037 if (view->parent) {
2038 view->parent->child = NULL;
2039 view->parent->focus_child = 0;
2040 /* Restore fullscreen line height. */
2041 view->parent->nlines = view->parent->lines;
2042 err = view_resize(view->parent);
2043 if (err)
2044 break;
2045 /* Make resized splits persist. */
2046 view_transfer_size(view->parent, view);
2047 } else
2048 TAILQ_REMOVE(&views, view, entry);
2050 err = view_close(view);
2051 if (err)
2052 goto done;
2054 view = NULL;
2055 TAILQ_FOREACH(v, &views, entry) {
2056 if (v->focussed)
2057 break;
2059 if (view == NULL && new_view == NULL) {
2060 /* No view has focus. Try to pick one. */
2061 if (prev)
2062 view = prev;
2063 else if (!TAILQ_EMPTY(&views)) {
2064 view = TAILQ_LAST(&views,
2065 tog_view_list_head);
2067 if (view) {
2068 if (view->focus_child) {
2069 view->child->focussed = 1;
2070 view = view->child;
2071 } else
2072 view->focussed = 1;
2076 if (new_view) {
2077 struct tog_view *v, *t;
2078 /* Only allow one parent view per type. */
2079 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2080 if (v->type != new_view->type)
2081 continue;
2082 TAILQ_REMOVE(&views, v, entry);
2083 err = view_close(v);
2084 if (err)
2085 goto done;
2086 break;
2088 TAILQ_INSERT_TAIL(&views, new_view, entry);
2089 view = new_view;
2091 if (view && !done) {
2092 if (view_is_parent_view(view)) {
2093 if (view->child && view->child->focussed)
2094 view = view->child;
2095 } else {
2096 if (view->parent && view->parent->focussed)
2097 view = view->parent;
2099 show_panel(view->panel);
2100 if (view->child && view_is_splitscreen(view->child))
2101 show_panel(view->child->panel);
2102 if (view->parent && view_is_splitscreen(view)) {
2103 err = view->parent->show(view->parent);
2104 if (err)
2105 goto done;
2107 err = view->show(view);
2108 if (err)
2109 goto done;
2110 if (view->child) {
2111 err = view->child->show(view->child);
2112 if (err)
2113 goto done;
2115 update_panels();
2116 doupdate();
2119 done:
2120 while (!TAILQ_EMPTY(&views)) {
2121 const struct got_error *close_err;
2122 view = TAILQ_FIRST(&views);
2123 TAILQ_REMOVE(&views, view, entry);
2124 close_err = view_close(view);
2125 if (close_err && err == NULL)
2126 err = close_err;
2129 errcode = pthread_mutex_unlock(&tog_mutex);
2130 if (errcode && err == NULL)
2131 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2133 return err;
2136 __dead static void
2137 usage_log(void)
2139 endwin();
2140 fprintf(stderr,
2141 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2142 getprogname());
2143 exit(1);
2146 /* Create newly allocated wide-character string equivalent to a byte string. */
2147 static const struct got_error *
2148 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2150 char *vis = NULL;
2151 const struct got_error *err = NULL;
2153 *ws = NULL;
2154 *wlen = mbstowcs(NULL, s, 0);
2155 if (*wlen == (size_t)-1) {
2156 int vislen;
2157 if (errno != EILSEQ)
2158 return got_error_from_errno("mbstowcs");
2160 /* byte string invalid in current encoding; try to "fix" it */
2161 err = got_mbsavis(&vis, &vislen, s);
2162 if (err)
2163 return err;
2164 *wlen = mbstowcs(NULL, vis, 0);
2165 if (*wlen == (size_t)-1) {
2166 err = got_error_from_errno("mbstowcs"); /* give up */
2167 goto done;
2171 *ws = calloc(*wlen + 1, sizeof(**ws));
2172 if (*ws == NULL) {
2173 err = got_error_from_errno("calloc");
2174 goto done;
2177 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2178 err = got_error_from_errno("mbstowcs");
2179 done:
2180 free(vis);
2181 if (err) {
2182 free(*ws);
2183 *ws = NULL;
2184 *wlen = 0;
2186 return err;
2189 static const struct got_error *
2190 expand_tab(char **ptr, const char *src)
2192 char *dst;
2193 size_t len, n, idx = 0, sz = 0;
2195 *ptr = NULL;
2196 n = len = strlen(src);
2197 dst = malloc(n + 1);
2198 if (dst == NULL)
2199 return got_error_from_errno("malloc");
2201 while (idx < len && src[idx]) {
2202 const char c = src[idx];
2204 if (c == '\t') {
2205 size_t nb = TABSIZE - sz % TABSIZE;
2206 char *p;
2208 p = realloc(dst, n + nb);
2209 if (p == NULL) {
2210 free(dst);
2211 return got_error_from_errno("realloc");
2214 dst = p;
2215 n += nb;
2216 memset(dst + sz, ' ', nb);
2217 sz += nb;
2218 } else
2219 dst[sz++] = src[idx];
2220 ++idx;
2223 dst[sz] = '\0';
2224 *ptr = dst;
2225 return NULL;
2229 * Advance at most n columns from wline starting at offset off.
2230 * Return the index to the first character after the span operation.
2231 * Return the combined column width of all spanned wide characters in
2232 * *rcol.
2234 static int
2235 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2237 int width, i, cols = 0;
2239 if (n == 0) {
2240 *rcol = cols;
2241 return off;
2244 for (i = off; wline[i] != L'\0'; ++i) {
2245 if (wline[i] == L'\t')
2246 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2247 else
2248 width = wcwidth(wline[i]);
2250 if (width == -1) {
2251 width = 1;
2252 wline[i] = L'.';
2255 if (cols + width > n)
2256 break;
2257 cols += width;
2260 *rcol = cols;
2261 return i;
2265 * Format a line for display, ensuring that it won't overflow a width limit.
2266 * With scrolling, the width returned refers to the scrolled version of the
2267 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2269 static const struct got_error *
2270 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2271 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2273 const struct got_error *err = NULL;
2274 int cols;
2275 wchar_t *wline = NULL;
2276 char *exstr = NULL;
2277 size_t wlen;
2278 int i, scrollx;
2280 *wlinep = NULL;
2281 *widthp = 0;
2283 if (expand) {
2284 err = expand_tab(&exstr, line);
2285 if (err)
2286 return err;
2289 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2290 free(exstr);
2291 if (err)
2292 return err;
2294 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2296 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2297 wline[wlen - 1] = L'\0';
2298 wlen--;
2300 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2301 wline[wlen - 1] = L'\0';
2302 wlen--;
2305 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2306 wline[i] = L'\0';
2308 if (widthp)
2309 *widthp = cols;
2310 if (scrollxp)
2311 *scrollxp = scrollx;
2312 if (err)
2313 free(wline);
2314 else
2315 *wlinep = wline;
2316 return err;
2319 static const struct got_error*
2320 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2321 struct got_object_id *id, struct got_repository *repo)
2323 static const struct got_error *err = NULL;
2324 struct got_reflist_entry *re;
2325 char *s;
2326 const char *name;
2328 *refs_str = NULL;
2330 if (refs == NULL)
2331 return NULL;
2333 TAILQ_FOREACH(re, refs, entry) {
2334 struct got_tag_object *tag = NULL;
2335 struct got_object_id *ref_id;
2336 int cmp;
2338 name = got_ref_get_name(re->ref);
2339 if (strcmp(name, GOT_REF_HEAD) == 0)
2340 continue;
2341 if (strncmp(name, "refs/", 5) == 0)
2342 name += 5;
2343 if (strncmp(name, "got/", 4) == 0)
2344 continue;
2345 if (strncmp(name, "heads/", 6) == 0)
2346 name += 6;
2347 if (strncmp(name, "remotes/", 8) == 0) {
2348 name += 8;
2349 s = strstr(name, "/" GOT_REF_HEAD);
2350 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
2351 continue;
2353 err = got_ref_resolve(&ref_id, repo, re->ref);
2354 if (err)
2355 break;
2356 if (strncmp(name, "tags/", 5) == 0) {
2357 err = got_object_open_as_tag(&tag, repo, ref_id);
2358 if (err) {
2359 if (err->code != GOT_ERR_OBJ_TYPE) {
2360 free(ref_id);
2361 break;
2363 /* Ref points at something other than a tag. */
2364 err = NULL;
2365 tag = NULL;
2368 cmp = got_object_id_cmp(tag ?
2369 got_object_tag_get_object_id(tag) : ref_id, id);
2370 free(ref_id);
2371 if (tag)
2372 got_object_tag_close(tag);
2373 if (cmp != 0)
2374 continue;
2375 s = *refs_str;
2376 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2377 s ? ", " : "", name) == -1) {
2378 err = got_error_from_errno("asprintf");
2379 free(s);
2380 *refs_str = NULL;
2381 break;
2383 free(s);
2386 return err;
2389 static const struct got_error *
2390 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2391 int col_tab_align)
2393 char *smallerthan;
2395 smallerthan = strchr(author, '<');
2396 if (smallerthan && smallerthan[1] != '\0')
2397 author = smallerthan + 1;
2398 author[strcspn(author, "@>")] = '\0';
2399 return format_line(wauthor, author_width, NULL, author, 0, limit,
2400 col_tab_align, 0);
2403 static const struct got_error *
2404 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2405 struct got_object_id *id, const size_t date_display_cols,
2406 int author_display_cols)
2408 struct tog_log_view_state *s = &view->state.log;
2409 const struct got_error *err = NULL;
2410 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2411 char *refs_str = NULL;
2412 char *logmsg0 = NULL, *logmsg = NULL;
2413 char *author = NULL;
2414 wchar_t *wrefstr = NULL, *wlogmsg = NULL, *wauthor = NULL;
2415 int author_width, refstr_width, logmsg_width;
2416 char *newline, *line = NULL;
2417 int col, limit, scrollx, logmsg_x;
2418 const int avail = view->ncols;
2419 struct tm tm;
2420 time_t committer_time;
2421 struct tog_color *tc;
2422 struct got_reflist_head *refs;
2424 committer_time = got_object_commit_get_committer_time(commit);
2425 if (gmtime_r(&committer_time, &tm) == NULL)
2426 return got_error_from_errno("gmtime_r");
2427 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2428 return got_error(GOT_ERR_NO_SPACE);
2430 if (avail <= date_display_cols)
2431 limit = MIN(sizeof(datebuf) - 1, avail);
2432 else
2433 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2434 tc = get_color(&s->colors, TOG_COLOR_DATE);
2435 if (tc)
2436 wattr_on(view->window,
2437 COLOR_PAIR(tc->colorpair), NULL);
2438 waddnstr(view->window, datebuf, limit);
2439 if (tc)
2440 wattr_off(view->window,
2441 COLOR_PAIR(tc->colorpair), NULL);
2442 col = limit;
2443 if (col > avail)
2444 goto done;
2446 if (avail >= 120) {
2447 char *id_str;
2448 err = got_object_id_str(&id_str, id);
2449 if (err)
2450 goto done;
2451 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2452 if (tc)
2453 wattr_on(view->window,
2454 COLOR_PAIR(tc->colorpair), NULL);
2455 wprintw(view->window, "%.8s ", id_str);
2456 if (tc)
2457 wattr_off(view->window,
2458 COLOR_PAIR(tc->colorpair), NULL);
2459 free(id_str);
2460 col += 9;
2461 if (col > avail)
2462 goto done;
2465 if (s->use_committer)
2466 author = strdup(got_object_commit_get_committer(commit));
2467 else
2468 author = strdup(got_object_commit_get_author(commit));
2469 if (author == NULL) {
2470 err = got_error_from_errno("strdup");
2471 goto done;
2473 err = format_author(&wauthor, &author_width, author, avail - col, col);
2474 if (err)
2475 goto done;
2476 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2477 if (tc)
2478 wattr_on(view->window,
2479 COLOR_PAIR(tc->colorpair), NULL);
2480 waddwstr(view->window, wauthor);
2481 col += author_width;
2482 while (col < avail && author_width < author_display_cols + 2) {
2483 waddch(view->window, ' ');
2484 col++;
2485 author_width++;
2487 if (tc)
2488 wattr_off(view->window,
2489 COLOR_PAIR(tc->colorpair), NULL);
2490 if (col > avail)
2491 goto done;
2493 err = got_object_commit_get_logmsg(&logmsg0, commit);
2494 if (err)
2495 goto done;
2496 logmsg = logmsg0;
2497 while (*logmsg == '\n')
2498 logmsg++;
2499 newline = strchr(logmsg, '\n');
2500 if (newline)
2501 *newline = '\0';
2503 limit = avail - col;
2504 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2505 limit--; /* for the border */
2507 /* Prepend reference labels to log message if possible .*/
2508 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, id);
2509 err = build_refs_str(&refs_str, refs, id, s->repo);
2510 if (err)
2511 goto done;
2512 if (refs_str) {
2513 char *rs;
2515 if (asprintf(&rs, "[%s]", refs_str) == -1) {
2516 err = got_error_from_errno("asprintf");
2517 goto done;
2519 err = format_line(&wrefstr, &refstr_width,
2520 &scrollx, rs, view->x, limit, col, 1);
2521 free(rs);
2522 if (err)
2523 goto done;
2524 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2525 if (tc)
2526 wattr_on(view->window,
2527 COLOR_PAIR(tc->colorpair), NULL);
2528 waddwstr(view->window, &wrefstr[scrollx]);
2529 if (tc)
2530 wattr_off(view->window,
2531 COLOR_PAIR(tc->colorpair), NULL);
2532 col += MAX(refstr_width, 0);
2533 if (col > avail)
2534 goto done;
2536 if (col < avail) {
2537 waddch(view->window, ' ');
2538 col++;
2541 if (refstr_width > 0)
2542 logmsg_x = 0;
2543 else {
2544 int unscrolled_refstr_width;
2545 size_t len = wcslen(wrefstr);
2548 * No need to check for -1 return value here since
2549 * unprintables have been replaced by span_wline().
2551 unscrolled_refstr_width = wcswidth(wrefstr, len);
2552 unscrolled_refstr_width += 1; /* trailing space */
2553 logmsg_x = view->x - unscrolled_refstr_width;
2556 limit = avail - col;
2557 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2558 limit--; /* for the border */
2559 } else
2560 logmsg_x = view->x;
2562 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, logmsg_x,
2563 limit, col, 1);
2564 if (err)
2565 goto done;
2566 waddwstr(view->window, &wlogmsg[scrollx]);
2567 col += MAX(logmsg_width, 0);
2568 while (col < avail) {
2569 waddch(view->window, ' ');
2570 col++;
2572 done:
2573 free(logmsg0);
2574 free(wlogmsg);
2575 free(wrefstr);
2576 free(refs_str);
2577 free(author);
2578 free(wauthor);
2579 free(line);
2580 return err;
2583 static struct commit_queue_entry *
2584 alloc_commit_queue_entry(struct got_commit_object *commit,
2585 struct got_object_id *id)
2587 struct commit_queue_entry *entry;
2588 struct got_object_id *dup;
2590 entry = calloc(1, sizeof(*entry));
2591 if (entry == NULL)
2592 return NULL;
2594 dup = got_object_id_dup(id);
2595 if (dup == NULL) {
2596 free(entry);
2597 return NULL;
2600 entry->id = dup;
2601 entry->commit = commit;
2602 return entry;
2605 static void
2606 pop_commit(struct commit_queue *commits)
2608 struct commit_queue_entry *entry;
2610 entry = TAILQ_FIRST(&commits->head);
2611 TAILQ_REMOVE(&commits->head, entry, entry);
2612 got_object_commit_close(entry->commit);
2613 commits->ncommits--;
2614 free(entry->id);
2615 free(entry);
2618 static void
2619 free_commits(struct commit_queue *commits)
2621 while (!TAILQ_EMPTY(&commits->head))
2622 pop_commit(commits);
2625 static const struct got_error *
2626 match_commit(int *have_match, struct got_object_id *id,
2627 struct got_commit_object *commit, regex_t *regex)
2629 const struct got_error *err = NULL;
2630 regmatch_t regmatch;
2631 char *id_str = NULL, *logmsg = NULL;
2633 *have_match = 0;
2635 err = got_object_id_str(&id_str, id);
2636 if (err)
2637 return err;
2639 err = got_object_commit_get_logmsg(&logmsg, commit);
2640 if (err)
2641 goto done;
2643 if (regexec(regex, got_object_commit_get_author(commit), 1,
2644 &regmatch, 0) == 0 ||
2645 regexec(regex, got_object_commit_get_committer(commit), 1,
2646 &regmatch, 0) == 0 ||
2647 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2648 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2649 *have_match = 1;
2650 done:
2651 free(id_str);
2652 free(logmsg);
2653 return err;
2656 static const struct got_error *
2657 queue_commits(struct tog_log_thread_args *a)
2659 const struct got_error *err = NULL;
2662 * We keep all commits open throughout the lifetime of the log
2663 * view in order to avoid having to re-fetch commits from disk
2664 * while updating the display.
2666 do {
2667 struct got_object_id id;
2668 struct got_commit_object *commit;
2669 struct commit_queue_entry *entry;
2670 int limit_match = 0;
2671 int errcode;
2673 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2674 NULL, NULL);
2675 if (err)
2676 break;
2678 err = got_object_open_as_commit(&commit, a->repo, &id);
2679 if (err)
2680 break;
2681 entry = alloc_commit_queue_entry(commit, &id);
2682 if (entry == NULL) {
2683 err = got_error_from_errno("alloc_commit_queue_entry");
2684 break;
2687 errcode = pthread_mutex_lock(&tog_mutex);
2688 if (errcode) {
2689 err = got_error_set_errno(errcode,
2690 "pthread_mutex_lock");
2691 break;
2694 entry->idx = a->real_commits->ncommits;
2695 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2696 a->real_commits->ncommits++;
2698 if (*a->limiting) {
2699 err = match_commit(&limit_match, &id, commit,
2700 a->limit_regex);
2701 if (err)
2702 break;
2704 if (limit_match) {
2705 struct commit_queue_entry *matched;
2707 matched = alloc_commit_queue_entry(
2708 entry->commit, entry->id);
2709 if (matched == NULL) {
2710 err = got_error_from_errno(
2711 "alloc_commit_queue_entry");
2712 break;
2714 matched->commit = entry->commit;
2715 got_object_commit_retain(entry->commit);
2717 matched->idx = a->limit_commits->ncommits;
2718 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2719 matched, entry);
2720 a->limit_commits->ncommits++;
2724 * This is how we signal log_thread() that we
2725 * have found a match, and that it should be
2726 * counted as a new entry for the view.
2728 a->limit_match = limit_match;
2731 if (*a->searching == TOG_SEARCH_FORWARD &&
2732 !*a->search_next_done) {
2733 int have_match;
2734 err = match_commit(&have_match, &id, commit, a->regex);
2735 if (err)
2736 break;
2738 if (*a->limiting) {
2739 if (limit_match && have_match)
2740 *a->search_next_done =
2741 TOG_SEARCH_HAVE_MORE;
2742 } else if (have_match)
2743 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2746 errcode = pthread_mutex_unlock(&tog_mutex);
2747 if (errcode && err == NULL)
2748 err = got_error_set_errno(errcode,
2749 "pthread_mutex_unlock");
2750 if (err)
2751 break;
2752 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2754 return err;
2757 static void
2758 select_commit(struct tog_log_view_state *s)
2760 struct commit_queue_entry *entry;
2761 int ncommits = 0;
2763 entry = s->first_displayed_entry;
2764 while (entry) {
2765 if (ncommits == s->selected) {
2766 s->selected_entry = entry;
2767 break;
2769 entry = TAILQ_NEXT(entry, entry);
2770 ncommits++;
2774 static const struct got_error *
2775 draw_commits(struct tog_view *view)
2777 const struct got_error *err = NULL;
2778 struct tog_log_view_state *s = &view->state.log;
2779 struct commit_queue_entry *entry = s->selected_entry;
2780 int limit = view->nlines;
2781 int width;
2782 int ncommits, author_cols = 4, refstr_cols;
2783 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2784 char *refs_str = NULL;
2785 wchar_t *wline;
2786 struct tog_color *tc;
2787 static const size_t date_display_cols = 12;
2788 struct got_reflist_head *refs;
2790 if (view_is_hsplit_top(view))
2791 --limit; /* account for border */
2793 if (s->selected_entry &&
2794 !(view->searching && view->search_next_done == 0)) {
2795 err = got_object_id_str(&id_str, s->selected_entry->id);
2796 if (err)
2797 return err;
2798 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2799 s->selected_entry->id);
2800 err = build_refs_str(&refs_str, refs, s->selected_entry->id,
2801 s->repo);
2802 if (err)
2803 goto done;
2806 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2807 halfdelay(10); /* disable fast refresh */
2809 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2810 if (asprintf(&ncommits_str, " [%d/%d] %s",
2811 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2812 (view->searching && !view->search_next_done) ?
2813 "searching..." : "loading...") == -1) {
2814 err = got_error_from_errno("asprintf");
2815 goto done;
2817 } else {
2818 const char *search_str = NULL;
2819 const char *limit_str = NULL;
2821 if (view->searching) {
2822 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2823 search_str = "no more matches";
2824 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2825 search_str = "no matches found";
2826 else if (!view->search_next_done)
2827 search_str = "searching...";
2830 if (s->limit_view && s->commits->ncommits == 0)
2831 limit_str = "no matches found";
2833 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2834 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2835 search_str ? search_str : (refs_str ? refs_str : ""),
2836 limit_str ? limit_str : "") == -1) {
2837 err = got_error_from_errno("asprintf");
2838 goto done;
2842 free(refs_str);
2843 refs_str = NULL;
2845 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2846 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2847 "........................................",
2848 s->in_repo_path, ncommits_str) == -1) {
2849 err = got_error_from_errno("asprintf");
2850 header = NULL;
2851 goto done;
2853 } else if (asprintf(&header, "commit %s%s",
2854 id_str ? id_str : "........................................",
2855 ncommits_str) == -1) {
2856 err = got_error_from_errno("asprintf");
2857 header = NULL;
2858 goto done;
2860 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2861 if (err)
2862 goto done;
2864 werase(view->window);
2866 if (view_needs_focus_indication(view))
2867 wstandout(view->window);
2868 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2869 if (tc)
2870 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2871 waddwstr(view->window, wline);
2872 while (width < view->ncols) {
2873 waddch(view->window, ' ');
2874 width++;
2876 if (tc)
2877 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2878 if (view_needs_focus_indication(view))
2879 wstandend(view->window);
2880 free(wline);
2881 if (limit <= 1)
2882 goto done;
2884 /* Grow author column size if necessary, and set view->maxx. */
2885 entry = s->first_displayed_entry;
2886 ncommits = 0;
2887 view->maxx = 0;
2888 while (entry) {
2889 struct got_commit_object *c = entry->commit;
2890 char *author, *eol, *msg, *msg0;
2891 wchar_t *wauthor, *wmsg;
2892 int width;
2893 if (ncommits >= limit - 1)
2894 break;
2895 if (s->use_committer)
2896 author = strdup(got_object_commit_get_committer(c));
2897 else
2898 author = strdup(got_object_commit_get_author(c));
2899 if (author == NULL) {
2900 err = got_error_from_errno("strdup");
2901 goto done;
2903 err = format_author(&wauthor, &width, author, COLS,
2904 date_display_cols);
2905 if (author_cols < width)
2906 author_cols = width;
2907 free(wauthor);
2908 free(author);
2909 if (err)
2910 goto done;
2911 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2912 entry->id);
2913 err = build_refs_str(&refs_str, refs, entry->id, s->repo);
2914 if (err)
2915 goto done;
2916 if (refs_str) {
2917 wchar_t *ws;
2918 err = format_line(&ws, &width, NULL, refs_str,
2919 0, INT_MAX, date_display_cols + author_cols, 0);
2920 free(ws);
2921 free(refs_str);
2922 refs_str = NULL;
2923 if (err)
2924 goto done;
2925 refstr_cols = width + 3; /* account for [ ] + space */
2926 } else
2927 refstr_cols = 0;
2928 err = got_object_commit_get_logmsg(&msg0, c);
2929 if (err)
2930 goto done;
2931 msg = msg0;
2932 while (*msg == '\n')
2933 ++msg;
2934 if ((eol = strchr(msg, '\n')))
2935 *eol = '\0';
2936 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2937 date_display_cols + author_cols + refstr_cols, 0);
2938 if (err)
2939 goto done;
2940 view->maxx = MAX(view->maxx, width + refstr_cols);
2941 free(msg0);
2942 free(wmsg);
2943 ncommits++;
2944 entry = TAILQ_NEXT(entry, entry);
2947 entry = s->first_displayed_entry;
2948 s->last_displayed_entry = s->first_displayed_entry;
2949 ncommits = 0;
2950 while (entry) {
2951 if (ncommits >= limit - 1)
2952 break;
2953 if (ncommits == s->selected)
2954 wstandout(view->window);
2955 err = draw_commit(view, entry->commit, entry->id,
2956 date_display_cols, author_cols);
2957 if (ncommits == s->selected)
2958 wstandend(view->window);
2959 if (err)
2960 goto done;
2961 ncommits++;
2962 s->last_displayed_entry = entry;
2963 entry = TAILQ_NEXT(entry, entry);
2966 view_border(view);
2967 done:
2968 free(id_str);
2969 free(refs_str);
2970 free(ncommits_str);
2971 free(header);
2972 return err;
2975 static void
2976 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2978 struct commit_queue_entry *entry;
2979 int nscrolled = 0;
2981 entry = TAILQ_FIRST(&s->commits->head);
2982 if (s->first_displayed_entry == entry)
2983 return;
2985 entry = s->first_displayed_entry;
2986 while (entry && nscrolled < maxscroll) {
2987 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2988 if (entry) {
2989 s->first_displayed_entry = entry;
2990 nscrolled++;
2995 static const struct got_error *
2996 trigger_log_thread(struct tog_view *view, int wait)
2998 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2999 int errcode;
3001 if (!using_mock_io)
3002 halfdelay(1); /* fast refresh while loading commits */
3004 while (!ta->log_complete && !tog_thread_error &&
3005 (ta->commits_needed > 0 || ta->load_all)) {
3006 /* Wake the log thread. */
3007 errcode = pthread_cond_signal(&ta->need_commits);
3008 if (errcode)
3009 return got_error_set_errno(errcode,
3010 "pthread_cond_signal");
3013 * The mutex will be released while the view loop waits
3014 * in wgetch(), at which time the log thread will run.
3016 if (!wait)
3017 break;
3019 /* Display progress update in log view. */
3020 show_log_view(view);
3021 update_panels();
3022 doupdate();
3024 /* Wait right here while next commit is being loaded. */
3025 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
3026 if (errcode)
3027 return got_error_set_errno(errcode,
3028 "pthread_cond_wait");
3030 /* Display progress update in log view. */
3031 show_log_view(view);
3032 update_panels();
3033 doupdate();
3036 return NULL;
3039 static const struct got_error *
3040 request_log_commits(struct tog_view *view)
3042 struct tog_log_view_state *state = &view->state.log;
3043 const struct got_error *err = NULL;
3045 if (state->thread_args.log_complete)
3046 return NULL;
3048 state->thread_args.commits_needed += view->nscrolled;
3049 err = trigger_log_thread(view, 1);
3050 view->nscrolled = 0;
3052 return err;
3055 static const struct got_error *
3056 log_scroll_down(struct tog_view *view, int maxscroll)
3058 struct tog_log_view_state *s = &view->state.log;
3059 const struct got_error *err = NULL;
3060 struct commit_queue_entry *pentry;
3061 int nscrolled = 0, ncommits_needed;
3063 if (s->last_displayed_entry == NULL)
3064 return NULL;
3066 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
3067 if (s->commits->ncommits < ncommits_needed &&
3068 !s->thread_args.log_complete) {
3070 * Ask the log thread for required amount of commits.
3072 s->thread_args.commits_needed +=
3073 ncommits_needed - s->commits->ncommits;
3074 err = trigger_log_thread(view, 1);
3075 if (err)
3076 return err;
3079 do {
3080 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
3081 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
3082 break;
3084 s->last_displayed_entry = pentry ?
3085 pentry : s->last_displayed_entry;
3087 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3088 if (pentry == NULL)
3089 break;
3090 s->first_displayed_entry = pentry;
3091 } while (++nscrolled < maxscroll);
3093 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3094 view->nscrolled += nscrolled;
3095 else
3096 view->nscrolled = 0;
3098 return err;
3101 static const struct got_error *
3102 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3103 struct got_commit_object *commit, struct got_object_id *commit_id,
3104 struct tog_view *log_view, struct got_repository *repo)
3106 const struct got_error *err;
3107 struct got_object_qid *parent_id;
3108 struct tog_view *diff_view;
3110 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3111 if (diff_view == NULL)
3112 return got_error_from_errno("view_open");
3114 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3115 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3116 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3117 if (err == NULL)
3118 *new_view = diff_view;
3119 return err;
3122 static const struct got_error *
3123 tree_view_visit_subtree(struct tog_tree_view_state *s,
3124 struct got_tree_object *subtree)
3126 struct tog_parent_tree *parent;
3128 parent = calloc(1, sizeof(*parent));
3129 if (parent == NULL)
3130 return got_error_from_errno("calloc");
3132 parent->tree = s->tree;
3133 parent->first_displayed_entry = s->first_displayed_entry;
3134 parent->selected_entry = s->selected_entry;
3135 parent->selected = s->selected;
3136 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3137 s->tree = subtree;
3138 s->selected = 0;
3139 s->first_displayed_entry = NULL;
3140 return NULL;
3143 static const struct got_error *
3144 tree_view_walk_path(struct tog_tree_view_state *s,
3145 struct got_commit_object *commit, const char *path)
3147 const struct got_error *err = NULL;
3148 struct got_tree_object *tree = NULL;
3149 const char *p;
3150 char *slash, *subpath = NULL;
3152 /* Walk the path and open corresponding tree objects. */
3153 p = path;
3154 while (*p) {
3155 struct got_tree_entry *te;
3156 struct got_object_id *tree_id;
3157 char *te_name;
3159 while (p[0] == '/')
3160 p++;
3162 /* Ensure the correct subtree entry is selected. */
3163 slash = strchr(p, '/');
3164 if (slash == NULL)
3165 te_name = strdup(p);
3166 else
3167 te_name = strndup(p, slash - p);
3168 if (te_name == NULL) {
3169 err = got_error_from_errno("strndup");
3170 break;
3172 te = got_object_tree_find_entry(s->tree, te_name);
3173 if (te == NULL) {
3174 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3175 free(te_name);
3176 break;
3178 free(te_name);
3179 s->first_displayed_entry = s->selected_entry = te;
3181 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3182 break; /* jump to this file's entry */
3184 slash = strchr(p, '/');
3185 if (slash)
3186 subpath = strndup(path, slash - path);
3187 else
3188 subpath = strdup(path);
3189 if (subpath == NULL) {
3190 err = got_error_from_errno("strdup");
3191 break;
3194 err = got_object_id_by_path(&tree_id, s->repo, commit,
3195 subpath);
3196 if (err)
3197 break;
3199 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3200 free(tree_id);
3201 if (err)
3202 break;
3204 err = tree_view_visit_subtree(s, tree);
3205 if (err) {
3206 got_object_tree_close(tree);
3207 break;
3209 if (slash == NULL)
3210 break;
3211 free(subpath);
3212 subpath = NULL;
3213 p = slash;
3216 free(subpath);
3217 return err;
3220 static const struct got_error *
3221 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3222 struct commit_queue_entry *entry, const char *path,
3223 const char *head_ref_name, struct got_repository *repo)
3225 const struct got_error *err = NULL;
3226 struct tog_tree_view_state *s;
3227 struct tog_view *tree_view;
3229 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3230 if (tree_view == NULL)
3231 return got_error_from_errno("view_open");
3233 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3234 if (err)
3235 return err;
3236 s = &tree_view->state.tree;
3238 *new_view = tree_view;
3240 if (got_path_is_root_dir(path))
3241 return NULL;
3243 return tree_view_walk_path(s, entry->commit, path);
3246 static const struct got_error *
3247 block_signals_used_by_main_thread(void)
3249 sigset_t sigset;
3250 int errcode;
3252 if (sigemptyset(&sigset) == -1)
3253 return got_error_from_errno("sigemptyset");
3255 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3256 if (sigaddset(&sigset, SIGWINCH) == -1)
3257 return got_error_from_errno("sigaddset");
3258 if (sigaddset(&sigset, SIGCONT) == -1)
3259 return got_error_from_errno("sigaddset");
3260 if (sigaddset(&sigset, SIGINT) == -1)
3261 return got_error_from_errno("sigaddset");
3262 if (sigaddset(&sigset, SIGTERM) == -1)
3263 return got_error_from_errno("sigaddset");
3265 /* ncurses handles SIGTSTP */
3266 if (sigaddset(&sigset, SIGTSTP) == -1)
3267 return got_error_from_errno("sigaddset");
3269 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3270 if (errcode)
3271 return got_error_set_errno(errcode, "pthread_sigmask");
3273 return NULL;
3276 static void *
3277 log_thread(void *arg)
3279 const struct got_error *err = NULL;
3280 int errcode = 0;
3281 struct tog_log_thread_args *a = arg;
3282 int done = 0;
3285 * Sync startup with main thread such that we begin our
3286 * work once view_input() has released the mutex.
3288 errcode = pthread_mutex_lock(&tog_mutex);
3289 if (errcode) {
3290 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3291 return (void *)err;
3294 err = block_signals_used_by_main_thread();
3295 if (err) {
3296 pthread_mutex_unlock(&tog_mutex);
3297 goto done;
3300 while (!done && !err && !tog_fatal_signal_received()) {
3301 errcode = pthread_mutex_unlock(&tog_mutex);
3302 if (errcode) {
3303 err = got_error_set_errno(errcode,
3304 "pthread_mutex_unlock");
3305 goto done;
3307 err = queue_commits(a);
3308 if (err) {
3309 if (err->code != GOT_ERR_ITER_COMPLETED)
3310 goto done;
3311 err = NULL;
3312 done = 1;
3313 } else if (a->commits_needed > 0 && !a->load_all) {
3314 if (*a->limiting) {
3315 if (a->limit_match)
3316 a->commits_needed--;
3317 } else
3318 a->commits_needed--;
3321 errcode = pthread_mutex_lock(&tog_mutex);
3322 if (errcode) {
3323 err = got_error_set_errno(errcode,
3324 "pthread_mutex_lock");
3325 goto done;
3326 } else if (*a->quit)
3327 done = 1;
3328 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3329 *a->first_displayed_entry =
3330 TAILQ_FIRST(&a->limit_commits->head);
3331 *a->selected_entry = *a->first_displayed_entry;
3332 } else if (*a->first_displayed_entry == NULL) {
3333 *a->first_displayed_entry =
3334 TAILQ_FIRST(&a->real_commits->head);
3335 *a->selected_entry = *a->first_displayed_entry;
3338 errcode = pthread_cond_signal(&a->commit_loaded);
3339 if (errcode) {
3340 err = got_error_set_errno(errcode,
3341 "pthread_cond_signal");
3342 pthread_mutex_unlock(&tog_mutex);
3343 goto done;
3346 if (done)
3347 a->commits_needed = 0;
3348 else {
3349 if (a->commits_needed == 0 && !a->load_all) {
3350 errcode = pthread_cond_wait(&a->need_commits,
3351 &tog_mutex);
3352 if (errcode) {
3353 err = got_error_set_errno(errcode,
3354 "pthread_cond_wait");
3355 pthread_mutex_unlock(&tog_mutex);
3356 goto done;
3358 if (*a->quit)
3359 done = 1;
3363 a->log_complete = 1;
3364 errcode = pthread_mutex_unlock(&tog_mutex);
3365 if (errcode)
3366 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3367 done:
3368 if (err) {
3369 tog_thread_error = 1;
3370 pthread_cond_signal(&a->commit_loaded);
3372 return (void *)err;
3375 static const struct got_error *
3376 stop_log_thread(struct tog_log_view_state *s)
3378 const struct got_error *err = NULL, *thread_err = NULL;
3379 int errcode;
3381 if (s->thread) {
3382 s->quit = 1;
3383 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3384 if (errcode)
3385 return got_error_set_errno(errcode,
3386 "pthread_cond_signal");
3387 errcode = pthread_mutex_unlock(&tog_mutex);
3388 if (errcode)
3389 return got_error_set_errno(errcode,
3390 "pthread_mutex_unlock");
3391 errcode = pthread_join(s->thread, (void **)&thread_err);
3392 if (errcode)
3393 return got_error_set_errno(errcode, "pthread_join");
3394 errcode = pthread_mutex_lock(&tog_mutex);
3395 if (errcode)
3396 return got_error_set_errno(errcode,
3397 "pthread_mutex_lock");
3398 s->thread = 0; //NULL;
3401 if (s->thread_args.repo) {
3402 err = got_repo_close(s->thread_args.repo);
3403 s->thread_args.repo = NULL;
3406 if (s->thread_args.pack_fds) {
3407 const struct got_error *pack_err =
3408 got_repo_pack_fds_close(s->thread_args.pack_fds);
3409 if (err == NULL)
3410 err = pack_err;
3411 s->thread_args.pack_fds = NULL;
3414 if (s->thread_args.graph) {
3415 got_commit_graph_close(s->thread_args.graph);
3416 s->thread_args.graph = NULL;
3419 return err ? err : thread_err;
3422 static const struct got_error *
3423 close_log_view(struct tog_view *view)
3425 const struct got_error *err = NULL;
3426 struct tog_log_view_state *s = &view->state.log;
3427 int errcode;
3429 err = stop_log_thread(s);
3431 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3432 if (errcode && err == NULL)
3433 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3435 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3436 if (errcode && err == NULL)
3437 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3439 free_commits(&s->limit_commits);
3440 free_commits(&s->real_commits);
3441 free(s->in_repo_path);
3442 s->in_repo_path = NULL;
3443 free(s->start_id);
3444 s->start_id = NULL;
3445 free(s->head_ref_name);
3446 s->head_ref_name = NULL;
3447 return err;
3451 * We use two queues to implement the limit feature: first consists of
3452 * commits matching the current limit_regex; second is the real queue
3453 * of all known commits (real_commits). When the user starts limiting,
3454 * we swap queues such that all movement and displaying functionality
3455 * works with very slight change.
3457 static const struct got_error *
3458 limit_log_view(struct tog_view *view)
3460 struct tog_log_view_state *s = &view->state.log;
3461 struct commit_queue_entry *entry;
3462 struct tog_view *v = view;
3463 const struct got_error *err = NULL;
3464 char pattern[1024];
3465 int ret;
3467 if (view_is_hsplit_top(view))
3468 v = view->child;
3469 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3470 v = view->parent;
3472 /* Get the pattern */
3473 wmove(v->window, v->nlines - 1, 0);
3474 wclrtoeol(v->window);
3475 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3476 nodelay(v->window, FALSE);
3477 nocbreak();
3478 echo();
3479 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3480 cbreak();
3481 noecho();
3482 nodelay(v->window, TRUE);
3483 if (ret == ERR)
3484 return NULL;
3486 if (*pattern == '\0') {
3488 * Safety measure for the situation where the user
3489 * resets limit without previously limiting anything.
3491 if (!s->limit_view)
3492 return NULL;
3495 * User could have pressed Ctrl+L, which refreshed the
3496 * commit queues, it means we can't save previously
3497 * (before limit took place) displayed entries,
3498 * because they would point to already free'ed memory,
3499 * so we are forced to always select first entry of
3500 * the queue.
3502 s->commits = &s->real_commits;
3503 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3504 s->selected_entry = s->first_displayed_entry;
3505 s->selected = 0;
3506 s->limit_view = 0;
3508 return NULL;
3511 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3512 return NULL;
3514 s->limit_view = 1;
3516 /* Clear the screen while loading limit view */
3517 s->first_displayed_entry = NULL;
3518 s->last_displayed_entry = NULL;
3519 s->selected_entry = NULL;
3520 s->commits = &s->limit_commits;
3522 /* Prepare limit queue for new search */
3523 free_commits(&s->limit_commits);
3524 s->limit_commits.ncommits = 0;
3526 /* First process commits, which are in queue already */
3527 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3528 int have_match = 0;
3530 err = match_commit(&have_match, entry->id,
3531 entry->commit, &s->limit_regex);
3532 if (err)
3533 return err;
3535 if (have_match) {
3536 struct commit_queue_entry *matched;
3538 matched = alloc_commit_queue_entry(entry->commit,
3539 entry->id);
3540 if (matched == NULL) {
3541 err = got_error_from_errno(
3542 "alloc_commit_queue_entry");
3543 break;
3545 matched->commit = entry->commit;
3546 got_object_commit_retain(entry->commit);
3548 matched->idx = s->limit_commits.ncommits;
3549 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3550 matched, entry);
3551 s->limit_commits.ncommits++;
3555 /* Second process all the commits, until we fill the screen */
3556 if (s->limit_commits.ncommits < view->nlines - 1 &&
3557 !s->thread_args.log_complete) {
3558 s->thread_args.commits_needed +=
3559 view->nlines - s->limit_commits.ncommits - 1;
3560 err = trigger_log_thread(view, 1);
3561 if (err)
3562 return err;
3565 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3566 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3567 s->selected = 0;
3569 return NULL;
3572 static const struct got_error *
3573 search_start_log_view(struct tog_view *view)
3575 struct tog_log_view_state *s = &view->state.log;
3577 s->matched_entry = NULL;
3578 s->search_entry = NULL;
3579 return NULL;
3582 static const struct got_error *
3583 search_next_log_view(struct tog_view *view)
3585 const struct got_error *err = NULL;
3586 struct tog_log_view_state *s = &view->state.log;
3587 struct commit_queue_entry *entry;
3589 /* Display progress update in log view. */
3590 show_log_view(view);
3591 update_panels();
3592 doupdate();
3594 if (s->search_entry) {
3595 int errcode, ch;
3596 errcode = pthread_mutex_unlock(&tog_mutex);
3597 if (errcode)
3598 return got_error_set_errno(errcode,
3599 "pthread_mutex_unlock");
3600 ch = wgetch(view->window);
3601 errcode = pthread_mutex_lock(&tog_mutex);
3602 if (errcode)
3603 return got_error_set_errno(errcode,
3604 "pthread_mutex_lock");
3605 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3606 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3607 return NULL;
3609 if (view->searching == TOG_SEARCH_FORWARD)
3610 entry = TAILQ_NEXT(s->search_entry, entry);
3611 else
3612 entry = TAILQ_PREV(s->search_entry,
3613 commit_queue_head, entry);
3614 } else if (s->matched_entry) {
3616 * If the user has moved the cursor after we hit a match,
3617 * the position from where we should continue searching
3618 * might have changed.
3620 if (view->searching == TOG_SEARCH_FORWARD)
3621 entry = TAILQ_NEXT(s->selected_entry, entry);
3622 else
3623 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3624 entry);
3625 } else {
3626 entry = s->selected_entry;
3629 while (1) {
3630 int have_match = 0;
3632 if (entry == NULL) {
3633 if (s->thread_args.log_complete ||
3634 view->searching == TOG_SEARCH_BACKWARD) {
3635 view->search_next_done =
3636 (s->matched_entry == NULL ?
3637 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3638 s->search_entry = NULL;
3639 return NULL;
3642 * Poke the log thread for more commits and return,
3643 * allowing the main loop to make progress. Search
3644 * will resume at s->search_entry once we come back.
3646 s->thread_args.commits_needed++;
3647 return trigger_log_thread(view, 0);
3650 err = match_commit(&have_match, entry->id, entry->commit,
3651 &view->regex);
3652 if (err)
3653 break;
3654 if (have_match) {
3655 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3656 s->matched_entry = entry;
3657 break;
3660 s->search_entry = entry;
3661 if (view->searching == TOG_SEARCH_FORWARD)
3662 entry = TAILQ_NEXT(entry, entry);
3663 else
3664 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3667 if (s->matched_entry) {
3668 int cur = s->selected_entry->idx;
3669 while (cur < s->matched_entry->idx) {
3670 err = input_log_view(NULL, view, KEY_DOWN);
3671 if (err)
3672 return err;
3673 cur++;
3675 while (cur > s->matched_entry->idx) {
3676 err = input_log_view(NULL, view, KEY_UP);
3677 if (err)
3678 return err;
3679 cur--;
3683 s->search_entry = NULL;
3685 return NULL;
3688 static const struct got_error *
3689 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3690 struct got_repository *repo, const char *head_ref_name,
3691 const char *in_repo_path, int log_branches)
3693 const struct got_error *err = NULL;
3694 struct tog_log_view_state *s = &view->state.log;
3695 struct got_repository *thread_repo = NULL;
3696 struct got_commit_graph *thread_graph = NULL;
3697 int errcode;
3699 if (in_repo_path != s->in_repo_path) {
3700 free(s->in_repo_path);
3701 s->in_repo_path = strdup(in_repo_path);
3702 if (s->in_repo_path == NULL) {
3703 err = got_error_from_errno("strdup");
3704 goto done;
3708 /* The commit queue only contains commits being displayed. */
3709 TAILQ_INIT(&s->real_commits.head);
3710 s->real_commits.ncommits = 0;
3711 s->commits = &s->real_commits;
3713 TAILQ_INIT(&s->limit_commits.head);
3714 s->limit_view = 0;
3715 s->limit_commits.ncommits = 0;
3717 s->repo = repo;
3718 if (head_ref_name) {
3719 s->head_ref_name = strdup(head_ref_name);
3720 if (s->head_ref_name == NULL) {
3721 err = got_error_from_errno("strdup");
3722 goto done;
3725 s->start_id = got_object_id_dup(start_id);
3726 if (s->start_id == NULL) {
3727 err = got_error_from_errno("got_object_id_dup");
3728 goto done;
3730 s->log_branches = log_branches;
3731 s->use_committer = 1;
3733 STAILQ_INIT(&s->colors);
3734 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3735 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3736 get_color_value("TOG_COLOR_COMMIT"));
3737 if (err)
3738 goto done;
3739 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3740 get_color_value("TOG_COLOR_AUTHOR"));
3741 if (err) {
3742 free_colors(&s->colors);
3743 goto done;
3745 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3746 get_color_value("TOG_COLOR_DATE"));
3747 if (err) {
3748 free_colors(&s->colors);
3749 goto done;
3753 view->show = show_log_view;
3754 view->input = input_log_view;
3755 view->resize = resize_log_view;
3756 view->close = close_log_view;
3757 view->search_start = search_start_log_view;
3758 view->search_next = search_next_log_view;
3760 if (s->thread_args.pack_fds == NULL) {
3761 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3762 if (err)
3763 goto done;
3765 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3766 s->thread_args.pack_fds);
3767 if (err)
3768 goto done;
3769 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3770 !s->log_branches);
3771 if (err)
3772 goto done;
3773 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3774 s->repo, NULL, NULL);
3775 if (err)
3776 goto done;
3778 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3779 if (errcode) {
3780 err = got_error_set_errno(errcode, "pthread_cond_init");
3781 goto done;
3783 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3784 if (errcode) {
3785 err = got_error_set_errno(errcode, "pthread_cond_init");
3786 goto done;
3789 s->thread_args.commits_needed = view->nlines;
3790 s->thread_args.graph = thread_graph;
3791 s->thread_args.real_commits = &s->real_commits;
3792 s->thread_args.limit_commits = &s->limit_commits;
3793 s->thread_args.in_repo_path = s->in_repo_path;
3794 s->thread_args.start_id = s->start_id;
3795 s->thread_args.repo = thread_repo;
3796 s->thread_args.log_complete = 0;
3797 s->thread_args.quit = &s->quit;
3798 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3799 s->thread_args.selected_entry = &s->selected_entry;
3800 s->thread_args.searching = &view->searching;
3801 s->thread_args.search_next_done = &view->search_next_done;
3802 s->thread_args.regex = &view->regex;
3803 s->thread_args.limiting = &s->limit_view;
3804 s->thread_args.limit_regex = &s->limit_regex;
3805 s->thread_args.limit_commits = &s->limit_commits;
3806 done:
3807 if (err) {
3808 if (view->close == NULL)
3809 close_log_view(view);
3810 view_close(view);
3812 return err;
3815 static const struct got_error *
3816 show_log_view(struct tog_view *view)
3818 const struct got_error *err;
3819 struct tog_log_view_state *s = &view->state.log;
3821 if (s->thread == 0) { //NULL) {
3822 int errcode = pthread_create(&s->thread, NULL, log_thread,
3823 &s->thread_args);
3824 if (errcode)
3825 return got_error_set_errno(errcode, "pthread_create");
3826 if (s->thread_args.commits_needed > 0) {
3827 err = trigger_log_thread(view, 1);
3828 if (err)
3829 return err;
3833 return draw_commits(view);
3836 static void
3837 log_move_cursor_up(struct tog_view *view, int page, int home)
3839 struct tog_log_view_state *s = &view->state.log;
3841 if (s->first_displayed_entry == NULL)
3842 return;
3843 if (s->selected_entry->idx == 0)
3844 view->count = 0;
3846 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3847 || home)
3848 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3850 if (!page && !home && s->selected > 0)
3851 --s->selected;
3852 else
3853 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3855 select_commit(s);
3856 return;
3859 static const struct got_error *
3860 log_move_cursor_down(struct tog_view *view, int page)
3862 struct tog_log_view_state *s = &view->state.log;
3863 const struct got_error *err = NULL;
3864 int eos = view->nlines - 2;
3866 if (s->first_displayed_entry == NULL)
3867 return NULL;
3869 if (s->thread_args.log_complete &&
3870 s->selected_entry->idx >= s->commits->ncommits - 1)
3871 return NULL;
3873 if (view_is_hsplit_top(view))
3874 --eos; /* border consumes the last line */
3876 if (!page) {
3877 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3878 ++s->selected;
3879 else
3880 err = log_scroll_down(view, 1);
3881 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3882 struct commit_queue_entry *entry;
3883 int n;
3885 s->selected = 0;
3886 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3887 s->last_displayed_entry = entry;
3888 for (n = 0; n <= eos; n++) {
3889 if (entry == NULL)
3890 break;
3891 s->first_displayed_entry = entry;
3892 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3894 if (n > 0)
3895 s->selected = n - 1;
3896 } else {
3897 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3898 s->thread_args.log_complete)
3899 s->selected += MIN(page,
3900 s->commits->ncommits - s->selected_entry->idx - 1);
3901 else
3902 err = log_scroll_down(view, page);
3904 if (err)
3905 return err;
3908 * We might necessarily overshoot in horizontal
3909 * splits; if so, select the last displayed commit.
3911 if (s->first_displayed_entry && s->last_displayed_entry) {
3912 s->selected = MIN(s->selected,
3913 s->last_displayed_entry->idx -
3914 s->first_displayed_entry->idx);
3917 select_commit(s);
3919 if (s->thread_args.log_complete &&
3920 s->selected_entry->idx == s->commits->ncommits - 1)
3921 view->count = 0;
3923 return NULL;
3926 static void
3927 view_get_split(struct tog_view *view, int *y, int *x)
3929 *x = 0;
3930 *y = 0;
3932 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3933 if (view->child && view->child->resized_y)
3934 *y = view->child->resized_y;
3935 else if (view->resized_y)
3936 *y = view->resized_y;
3937 else
3938 *y = view_split_begin_y(view->lines);
3939 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3940 if (view->child && view->child->resized_x)
3941 *x = view->child->resized_x;
3942 else if (view->resized_x)
3943 *x = view->resized_x;
3944 else
3945 *x = view_split_begin_x(view->begin_x);
3949 /* Split view horizontally at y and offset view->state->selected line. */
3950 static const struct got_error *
3951 view_init_hsplit(struct tog_view *view, int y)
3953 const struct got_error *err = NULL;
3955 view->nlines = y;
3956 view->ncols = COLS;
3957 err = view_resize(view);
3958 if (err)
3959 return err;
3961 err = offset_selection_down(view);
3963 return err;
3966 static const struct got_error *
3967 log_goto_line(struct tog_view *view, int nlines)
3969 const struct got_error *err = NULL;
3970 struct tog_log_view_state *s = &view->state.log;
3971 int g, idx = s->selected_entry->idx;
3973 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3974 return NULL;
3976 g = view->gline;
3977 view->gline = 0;
3979 if (g >= s->first_displayed_entry->idx + 1 &&
3980 g <= s->last_displayed_entry->idx + 1 &&
3981 g - s->first_displayed_entry->idx - 1 < nlines) {
3982 s->selected = g - s->first_displayed_entry->idx - 1;
3983 select_commit(s);
3984 return NULL;
3987 if (idx + 1 < g) {
3988 err = log_move_cursor_down(view, g - idx - 1);
3989 if (!err && g > s->selected_entry->idx + 1)
3990 err = log_move_cursor_down(view,
3991 g - s->first_displayed_entry->idx - 1);
3992 if (err)
3993 return err;
3994 } else if (idx + 1 > g)
3995 log_move_cursor_up(view, idx - g + 1, 0);
3997 if (g < nlines && s->first_displayed_entry->idx == 0)
3998 s->selected = g - 1;
4000 select_commit(s);
4001 return NULL;
4005 static void
4006 horizontal_scroll_input(struct tog_view *view, int ch)
4009 switch (ch) {
4010 case KEY_LEFT:
4011 case 'h':
4012 view->x -= MIN(view->x, 2);
4013 if (view->x <= 0)
4014 view->count = 0;
4015 break;
4016 case KEY_RIGHT:
4017 case 'l':
4018 if (view->x + view->ncols / 2 < view->maxx)
4019 view->x += 2;
4020 else
4021 view->count = 0;
4022 break;
4023 case '0':
4024 view->x = 0;
4025 break;
4026 case '$':
4027 view->x = MAX(view->maxx - view->ncols / 2, 0);
4028 view->count = 0;
4029 break;
4030 default:
4031 break;
4035 static const struct got_error *
4036 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
4038 const struct got_error *err = NULL;
4039 struct tog_log_view_state *s = &view->state.log;
4040 int eos, nscroll;
4042 if (s->thread_args.load_all) {
4043 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
4044 s->thread_args.load_all = 0;
4045 else if (s->thread_args.log_complete) {
4046 err = log_move_cursor_down(view, s->commits->ncommits);
4047 s->thread_args.load_all = 0;
4049 if (err)
4050 return err;
4053 eos = nscroll = view->nlines - 1;
4054 if (view_is_hsplit_top(view))
4055 --eos; /* border */
4057 if (view->gline)
4058 return log_goto_line(view, eos);
4060 switch (ch) {
4061 case '&':
4062 err = limit_log_view(view);
4063 break;
4064 case 'q':
4065 s->quit = 1;
4066 break;
4067 case '0':
4068 case '$':
4069 case KEY_RIGHT:
4070 case 'l':
4071 case KEY_LEFT:
4072 case 'h':
4073 horizontal_scroll_input(view, ch);
4074 break;
4075 case 'k':
4076 case KEY_UP:
4077 case '<':
4078 case ',':
4079 case CTRL('p'):
4080 log_move_cursor_up(view, 0, 0);
4081 break;
4082 case 'g':
4083 case '=':
4084 case KEY_HOME:
4085 log_move_cursor_up(view, 0, 1);
4086 view->count = 0;
4087 break;
4088 case CTRL('u'):
4089 case 'u':
4090 nscroll /= 2;
4091 /* FALL THROUGH */
4092 case KEY_PPAGE:
4093 case CTRL('b'):
4094 case 'b':
4095 log_move_cursor_up(view, nscroll, 0);
4096 break;
4097 case 'j':
4098 case KEY_DOWN:
4099 case '>':
4100 case '.':
4101 case CTRL('n'):
4102 err = log_move_cursor_down(view, 0);
4103 break;
4104 case '@':
4105 s->use_committer = !s->use_committer;
4106 view->action = s->use_committer ?
4107 "show committer" : "show commit author";
4108 break;
4109 case 'G':
4110 case '*':
4111 case KEY_END: {
4112 /* We don't know yet how many commits, so we're forced to
4113 * traverse them all. */
4114 view->count = 0;
4115 s->thread_args.load_all = 1;
4116 if (!s->thread_args.log_complete)
4117 return trigger_log_thread(view, 0);
4118 err = log_move_cursor_down(view, s->commits->ncommits);
4119 s->thread_args.load_all = 0;
4120 break;
4122 case CTRL('d'):
4123 case 'd':
4124 nscroll /= 2;
4125 /* FALL THROUGH */
4126 case KEY_NPAGE:
4127 case CTRL('f'):
4128 case 'f':
4129 case ' ':
4130 err = log_move_cursor_down(view, nscroll);
4131 break;
4132 case KEY_RESIZE:
4133 if (s->selected > view->nlines - 2)
4134 s->selected = view->nlines - 2;
4135 if (s->selected > s->commits->ncommits - 1)
4136 s->selected = s->commits->ncommits - 1;
4137 select_commit(s);
4138 if (s->commits->ncommits < view->nlines - 1 &&
4139 !s->thread_args.log_complete) {
4140 s->thread_args.commits_needed += (view->nlines - 1) -
4141 s->commits->ncommits;
4142 err = trigger_log_thread(view, 1);
4144 break;
4145 case KEY_ENTER:
4146 case '\r':
4147 view->count = 0;
4148 if (s->selected_entry == NULL)
4149 break;
4150 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4151 break;
4152 case 'T':
4153 view->count = 0;
4154 if (s->selected_entry == NULL)
4155 break;
4156 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4157 break;
4158 case KEY_BACKSPACE:
4159 case CTRL('l'):
4160 case 'B':
4161 view->count = 0;
4162 if (ch == KEY_BACKSPACE &&
4163 got_path_is_root_dir(s->in_repo_path))
4164 break;
4165 err = stop_log_thread(s);
4166 if (err)
4167 return err;
4168 if (ch == KEY_BACKSPACE) {
4169 char *parent_path;
4170 err = got_path_dirname(&parent_path, s->in_repo_path);
4171 if (err)
4172 return err;
4173 free(s->in_repo_path);
4174 s->in_repo_path = parent_path;
4175 s->thread_args.in_repo_path = s->in_repo_path;
4176 } else if (ch == CTRL('l')) {
4177 struct got_object_id *start_id;
4178 err = got_repo_match_object_id(&start_id, NULL,
4179 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4180 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4181 if (err) {
4182 if (s->head_ref_name == NULL ||
4183 err->code != GOT_ERR_NOT_REF)
4184 return err;
4185 /* Try to cope with deleted references. */
4186 free(s->head_ref_name);
4187 s->head_ref_name = NULL;
4188 err = got_repo_match_object_id(&start_id,
4189 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4190 &tog_refs, s->repo);
4191 if (err)
4192 return err;
4194 free(s->start_id);
4195 s->start_id = start_id;
4196 s->thread_args.start_id = s->start_id;
4197 } else /* 'B' */
4198 s->log_branches = !s->log_branches;
4200 if (s->thread_args.pack_fds == NULL) {
4201 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4202 if (err)
4203 return err;
4205 err = got_repo_open(&s->thread_args.repo,
4206 got_repo_get_path(s->repo), NULL,
4207 s->thread_args.pack_fds);
4208 if (err)
4209 return err;
4210 tog_free_refs();
4211 err = tog_load_refs(s->repo, 0);
4212 if (err)
4213 return err;
4214 err = got_commit_graph_open(&s->thread_args.graph,
4215 s->in_repo_path, !s->log_branches);
4216 if (err)
4217 return err;
4218 err = got_commit_graph_iter_start(s->thread_args.graph,
4219 s->start_id, s->repo, NULL, NULL);
4220 if (err)
4221 return err;
4222 free_commits(&s->real_commits);
4223 free_commits(&s->limit_commits);
4224 s->first_displayed_entry = NULL;
4225 s->last_displayed_entry = NULL;
4226 s->selected_entry = NULL;
4227 s->selected = 0;
4228 s->thread_args.log_complete = 0;
4229 s->quit = 0;
4230 s->thread_args.commits_needed = view->lines;
4231 s->matched_entry = NULL;
4232 s->search_entry = NULL;
4233 view->offset = 0;
4234 break;
4235 case 'R':
4236 view->count = 0;
4237 err = view_request_new(new_view, view, TOG_VIEW_REF);
4238 break;
4239 default:
4240 view->count = 0;
4241 break;
4244 return err;
4247 static const struct got_error *
4248 apply_unveil(const char *repo_path, const char *worktree_path)
4250 const struct got_error *error;
4252 #ifdef PROFILE
4253 if (unveil("gmon.out", "rwc") != 0)
4254 return got_error_from_errno2("unveil", "gmon.out");
4255 #endif
4256 if (repo_path && unveil(repo_path, "r") != 0)
4257 return got_error_from_errno2("unveil", repo_path);
4259 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4260 return got_error_from_errno2("unveil", worktree_path);
4262 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4263 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4265 error = got_privsep_unveil_exec_helpers();
4266 if (error != NULL)
4267 return error;
4269 if (unveil(NULL, NULL) != 0)
4270 return got_error_from_errno("unveil");
4272 return NULL;
4275 static const struct got_error *
4276 init_mock_term(const char *test_script_path)
4278 const struct got_error *err = NULL;
4279 const char *screen_dump_path;
4280 int in;
4282 if (test_script_path == NULL || *test_script_path == '\0')
4283 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4285 tog_io.f = fopen(test_script_path, "re");
4286 if (tog_io.f == NULL) {
4287 err = got_error_from_errno_fmt("fopen: %s",
4288 test_script_path);
4289 goto done;
4292 /* test mode, we don't want any output */
4293 tog_io.cout = fopen("/dev/null", "w+");
4294 if (tog_io.cout == NULL) {
4295 err = got_error_from_errno2("fopen", "/dev/null");
4296 goto done;
4299 in = dup(fileno(tog_io.cout));
4300 if (in == -1) {
4301 err = got_error_from_errno("dup");
4302 goto done;
4304 tog_io.cin = fdopen(in, "r");
4305 if (tog_io.cin == NULL) {
4306 err = got_error_from_errno("fdopen");
4307 close(in);
4308 goto done;
4311 screen_dump_path = getenv("TOG_SCR_DUMP");
4312 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4313 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4314 tog_io.sdump = fopen(screen_dump_path, "we");
4315 if (tog_io.sdump == NULL) {
4316 err = got_error_from_errno2("fopen", screen_dump_path);
4317 goto done;
4320 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4321 err = got_error_from_errno("fseeko");
4322 goto done;
4325 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4326 err = got_error_msg(GOT_ERR_IO,
4327 "newterm: failed to initialise curses");
4329 using_mock_io = 1;
4331 done:
4332 if (err)
4333 tog_io_close();
4334 return err;
4337 static void
4338 init_curses(void)
4341 * Override default signal handlers before starting ncurses.
4342 * This should prevent ncurses from installing its own
4343 * broken cleanup() signal handler.
4345 signal(SIGWINCH, tog_sigwinch);
4346 signal(SIGPIPE, tog_sigpipe);
4347 signal(SIGCONT, tog_sigcont);
4348 signal(SIGINT, tog_sigint);
4349 signal(SIGTERM, tog_sigterm);
4351 if (using_mock_io) /* In test mode we use a fake terminal */
4352 return;
4354 initscr();
4356 cbreak();
4357 halfdelay(1); /* Fast refresh while initial view is loading. */
4358 noecho();
4359 nonl();
4360 intrflush(stdscr, FALSE);
4361 keypad(stdscr, TRUE);
4362 curs_set(0);
4363 if (getenv("TOG_COLORS") != NULL) {
4364 start_color();
4365 use_default_colors();
4368 return;
4371 static const struct got_error *
4372 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4373 struct got_repository *repo, struct got_worktree *worktree)
4375 const struct got_error *err = NULL;
4377 if (argc == 0) {
4378 *in_repo_path = strdup("/");
4379 if (*in_repo_path == NULL)
4380 return got_error_from_errno("strdup");
4381 return NULL;
4384 if (worktree) {
4385 const char *prefix = got_worktree_get_path_prefix(worktree);
4386 char *p;
4388 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4389 if (err)
4390 return err;
4391 if (asprintf(in_repo_path, "%s%s%s", prefix,
4392 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4393 p) == -1) {
4394 err = got_error_from_errno("asprintf");
4395 *in_repo_path = NULL;
4397 free(p);
4398 } else
4399 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4401 return err;
4404 static const struct got_error *
4405 cmd_log(int argc, char *argv[])
4407 const struct got_error *error;
4408 struct got_repository *repo = NULL;
4409 struct got_worktree *worktree = NULL;
4410 struct got_object_id *start_id = NULL;
4411 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4412 char *keyword_idstr = NULL, *start_commit = NULL, *label = NULL;
4413 struct got_reference *ref = NULL;
4414 const char *head_ref_name = NULL;
4415 int ch, log_branches = 0;
4416 struct tog_view *view;
4417 int *pack_fds = NULL;
4419 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4420 switch (ch) {
4421 case 'b':
4422 log_branches = 1;
4423 break;
4424 case 'c':
4425 start_commit = optarg;
4426 break;
4427 case 'r':
4428 repo_path = realpath(optarg, NULL);
4429 if (repo_path == NULL)
4430 return got_error_from_errno2("realpath",
4431 optarg);
4432 break;
4433 default:
4434 usage_log();
4435 /* NOTREACHED */
4439 argc -= optind;
4440 argv += optind;
4442 if (argc > 1)
4443 usage_log();
4445 error = got_repo_pack_fds_open(&pack_fds);
4446 if (error != NULL)
4447 goto done;
4449 if (repo_path == NULL) {
4450 cwd = getcwd(NULL, 0);
4451 if (cwd == NULL)
4452 return got_error_from_errno("getcwd");
4453 error = got_worktree_open(&worktree, cwd, NULL);
4454 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4455 goto done;
4456 if (worktree)
4457 repo_path =
4458 strdup(got_worktree_get_repo_path(worktree));
4459 else
4460 repo_path = strdup(cwd);
4461 if (repo_path == NULL) {
4462 error = got_error_from_errno("strdup");
4463 goto done;
4467 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4468 if (error != NULL)
4469 goto done;
4471 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4472 repo, worktree);
4473 if (error)
4474 goto done;
4476 init_curses();
4478 error = apply_unveil(got_repo_get_path(repo),
4479 worktree ? got_worktree_get_root_path(worktree) : NULL);
4480 if (error)
4481 goto done;
4483 /* already loaded by tog_log_with_path()? */
4484 if (TAILQ_EMPTY(&tog_refs)) {
4485 error = tog_load_refs(repo, 0);
4486 if (error)
4487 goto done;
4490 if (start_commit == NULL) {
4491 error = got_repo_match_object_id(&start_id, &label,
4492 worktree ? got_worktree_get_head_ref_name(worktree) :
4493 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4494 if (error)
4495 goto done;
4496 head_ref_name = label;
4497 } else {
4498 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4499 repo, worktree);
4500 if (error != NULL)
4501 goto done;
4502 if (keyword_idstr != NULL)
4503 start_commit = keyword_idstr;
4505 error = got_ref_open(&ref, repo, start_commit, 0);
4506 if (error == NULL)
4507 head_ref_name = got_ref_get_name(ref);
4508 else if (error->code != GOT_ERR_NOT_REF)
4509 goto done;
4510 error = got_repo_match_object_id(&start_id, NULL,
4511 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4512 if (error)
4513 goto done;
4516 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4517 if (view == NULL) {
4518 error = got_error_from_errno("view_open");
4519 goto done;
4521 error = open_log_view(view, start_id, repo, head_ref_name,
4522 in_repo_path, log_branches);
4523 if (error)
4524 goto done;
4525 if (worktree) {
4526 /* Release work tree lock. */
4527 got_worktree_close(worktree);
4528 worktree = NULL;
4530 error = view_loop(view);
4531 done:
4532 free(keyword_idstr);
4533 free(in_repo_path);
4534 free(repo_path);
4535 free(cwd);
4536 free(start_id);
4537 free(label);
4538 if (ref)
4539 got_ref_close(ref);
4540 if (repo) {
4541 const struct got_error *close_err = got_repo_close(repo);
4542 if (error == NULL)
4543 error = close_err;
4545 if (worktree)
4546 got_worktree_close(worktree);
4547 if (pack_fds) {
4548 const struct got_error *pack_err =
4549 got_repo_pack_fds_close(pack_fds);
4550 if (error == NULL)
4551 error = pack_err;
4553 tog_free_refs();
4554 return error;
4557 __dead static void
4558 usage_diff(void)
4560 endwin();
4561 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4562 "object1 object2\n", getprogname());
4563 exit(1);
4566 static int
4567 match_line(const char *line, regex_t *regex, size_t nmatch,
4568 regmatch_t *regmatch)
4570 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4573 static struct tog_color *
4574 match_color(struct tog_colors *colors, const char *line)
4576 struct tog_color *tc = NULL;
4578 STAILQ_FOREACH(tc, colors, entry) {
4579 if (match_line(line, &tc->regex, 0, NULL))
4580 return tc;
4583 return NULL;
4586 static const struct got_error *
4587 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4588 WINDOW *window, int skipcol, regmatch_t *regmatch)
4590 const struct got_error *err = NULL;
4591 char *exstr = NULL;
4592 wchar_t *wline = NULL;
4593 int rme, rms, n, width, scrollx;
4594 int width0 = 0, width1 = 0, width2 = 0;
4595 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4597 *wtotal = 0;
4599 rms = regmatch->rm_so;
4600 rme = regmatch->rm_eo;
4602 err = expand_tab(&exstr, line);
4603 if (err)
4604 return err;
4606 /* Split the line into 3 segments, according to match offsets. */
4607 seg0 = strndup(exstr, rms);
4608 if (seg0 == NULL) {
4609 err = got_error_from_errno("strndup");
4610 goto done;
4612 seg1 = strndup(exstr + rms, rme - rms);
4613 if (seg1 == NULL) {
4614 err = got_error_from_errno("strndup");
4615 goto done;
4617 seg2 = strdup(exstr + rme);
4618 if (seg2 == NULL) {
4619 err = got_error_from_errno("strndup");
4620 goto done;
4623 /* draw up to matched token if we haven't scrolled past it */
4624 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4625 col_tab_align, 1);
4626 if (err)
4627 goto done;
4628 n = MAX(width0 - skipcol, 0);
4629 if (n) {
4630 free(wline);
4631 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4632 wlimit, col_tab_align, 1);
4633 if (err)
4634 goto done;
4635 waddwstr(window, &wline[scrollx]);
4636 wlimit -= width;
4637 *wtotal += width;
4640 if (wlimit > 0) {
4641 int i = 0, w = 0;
4642 size_t wlen;
4644 free(wline);
4645 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4646 col_tab_align, 1);
4647 if (err)
4648 goto done;
4649 wlen = wcslen(wline);
4650 while (i < wlen) {
4651 width = wcwidth(wline[i]);
4652 if (width == -1) {
4653 /* should not happen, tabs are expanded */
4654 err = got_error(GOT_ERR_RANGE);
4655 goto done;
4657 if (width0 + w + width > skipcol)
4658 break;
4659 w += width;
4660 i++;
4662 /* draw (visible part of) matched token (if scrolled into it) */
4663 if (width1 - w > 0) {
4664 wattron(window, A_STANDOUT);
4665 waddwstr(window, &wline[i]);
4666 wattroff(window, A_STANDOUT);
4667 wlimit -= (width1 - w);
4668 *wtotal += (width1 - w);
4672 if (wlimit > 0) { /* draw rest of line */
4673 free(wline);
4674 if (skipcol > width0 + width1) {
4675 err = format_line(&wline, &width2, &scrollx, seg2,
4676 skipcol - (width0 + width1), wlimit,
4677 col_tab_align, 1);
4678 if (err)
4679 goto done;
4680 waddwstr(window, &wline[scrollx]);
4681 } else {
4682 err = format_line(&wline, &width2, NULL, seg2, 0,
4683 wlimit, col_tab_align, 1);
4684 if (err)
4685 goto done;
4686 waddwstr(window, wline);
4688 *wtotal += width2;
4690 done:
4691 free(wline);
4692 free(exstr);
4693 free(seg0);
4694 free(seg1);
4695 free(seg2);
4696 return err;
4699 static int
4700 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4702 FILE *f = NULL;
4703 int *eof, *first, *selected;
4705 if (view->type == TOG_VIEW_DIFF) {
4706 struct tog_diff_view_state *s = &view->state.diff;
4708 first = &s->first_displayed_line;
4709 selected = first;
4710 eof = &s->eof;
4711 f = s->f;
4712 } else if (view->type == TOG_VIEW_HELP) {
4713 struct tog_help_view_state *s = &view->state.help;
4715 first = &s->first_displayed_line;
4716 selected = first;
4717 eof = &s->eof;
4718 f = s->f;
4719 } else if (view->type == TOG_VIEW_BLAME) {
4720 struct tog_blame_view_state *s = &view->state.blame;
4722 first = &s->first_displayed_line;
4723 selected = &s->selected_line;
4724 eof = &s->eof;
4725 f = s->blame.f;
4726 } else
4727 return 0;
4729 /* Center gline in the middle of the page like vi(1). */
4730 if (*lineno < view->gline - (view->nlines - 3) / 2)
4731 return 0;
4732 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4733 rewind(f);
4734 *eof = 0;
4735 *first = 1;
4736 *lineno = 0;
4737 *nprinted = 0;
4738 return 0;
4741 *selected = view->gline <= (view->nlines - 3) / 2 ?
4742 view->gline : (view->nlines - 3) / 2 + 1;
4743 view->gline = 0;
4745 return 1;
4748 static const struct got_error *
4749 draw_file(struct tog_view *view, const char *header)
4751 struct tog_diff_view_state *s = &view->state.diff;
4752 regmatch_t *regmatch = &view->regmatch;
4753 const struct got_error *err;
4754 int nprinted = 0;
4755 char *line;
4756 size_t linesize = 0;
4757 ssize_t linelen;
4758 wchar_t *wline;
4759 int width;
4760 int max_lines = view->nlines;
4761 int nlines = s->nlines;
4762 off_t line_offset;
4764 s->lineno = s->first_displayed_line - 1;
4765 line_offset = s->lines[s->first_displayed_line - 1].offset;
4766 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4767 return got_error_from_errno("fseek");
4769 werase(view->window);
4771 if (view->gline > s->nlines - 1)
4772 view->gline = s->nlines - 1;
4774 if (header) {
4775 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4776 1 : view->gline - (view->nlines - 3) / 2 :
4777 s->lineno + s->selected_line;
4779 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4780 return got_error_from_errno("asprintf");
4781 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4782 0, 0);
4783 free(line);
4784 if (err)
4785 return err;
4787 if (view_needs_focus_indication(view))
4788 wstandout(view->window);
4789 waddwstr(view->window, wline);
4790 free(wline);
4791 wline = NULL;
4792 while (width++ < view->ncols)
4793 waddch(view->window, ' ');
4794 if (view_needs_focus_indication(view))
4795 wstandend(view->window);
4797 if (max_lines <= 1)
4798 return NULL;
4799 max_lines--;
4802 s->eof = 0;
4803 view->maxx = 0;
4804 line = NULL;
4805 while (max_lines > 0 && nprinted < max_lines) {
4806 enum got_diff_line_type linetype;
4807 attr_t attr = 0;
4809 linelen = getline(&line, &linesize, s->f);
4810 if (linelen == -1) {
4811 if (feof(s->f)) {
4812 s->eof = 1;
4813 break;
4815 free(line);
4816 return got_ferror(s->f, GOT_ERR_IO);
4819 if (++s->lineno < s->first_displayed_line)
4820 continue;
4821 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4822 continue;
4823 if (s->lineno == view->hiline)
4824 attr = A_STANDOUT;
4826 /* Set view->maxx based on full line length. */
4827 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4828 view->x ? 1 : 0);
4829 if (err) {
4830 free(line);
4831 return err;
4833 view->maxx = MAX(view->maxx, width);
4834 free(wline);
4835 wline = NULL;
4837 linetype = s->lines[s->lineno].type;
4838 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4839 linetype < GOT_DIFF_LINE_CONTEXT)
4840 attr |= COLOR_PAIR(linetype);
4841 if (attr)
4842 wattron(view->window, attr);
4843 if (s->first_displayed_line + nprinted == s->matched_line &&
4844 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4845 err = add_matched_line(&width, line, view->ncols, 0,
4846 view->window, view->x, regmatch);
4847 if (err) {
4848 free(line);
4849 return err;
4851 } else {
4852 int skip;
4853 err = format_line(&wline, &width, &skip, line,
4854 view->x, view->ncols, 0, view->x ? 1 : 0);
4855 if (err) {
4856 free(line);
4857 return err;
4859 waddwstr(view->window, &wline[skip]);
4860 free(wline);
4861 wline = NULL;
4863 if (s->lineno == view->hiline) {
4864 /* highlight full gline length */
4865 while (width++ < view->ncols)
4866 waddch(view->window, ' ');
4867 } else {
4868 if (width <= view->ncols - 1)
4869 waddch(view->window, '\n');
4871 if (attr)
4872 wattroff(view->window, attr);
4873 if (++nprinted == 1)
4874 s->first_displayed_line = s->lineno;
4876 free(line);
4877 if (nprinted >= 1)
4878 s->last_displayed_line = s->first_displayed_line +
4879 (nprinted - 1);
4880 else
4881 s->last_displayed_line = s->first_displayed_line;
4883 view_border(view);
4885 if (s->eof) {
4886 while (nprinted < view->nlines) {
4887 waddch(view->window, '\n');
4888 nprinted++;
4891 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4892 view->ncols, 0, 0);
4893 if (err) {
4894 return err;
4897 wstandout(view->window);
4898 waddwstr(view->window, wline);
4899 free(wline);
4900 wline = NULL;
4901 wstandend(view->window);
4904 return NULL;
4907 static char *
4908 get_datestr(time_t *time, char *datebuf)
4910 struct tm mytm, *tm;
4911 char *p, *s;
4913 tm = gmtime_r(time, &mytm);
4914 if (tm == NULL)
4915 return NULL;
4916 s = asctime_r(tm, datebuf);
4917 if (s == NULL)
4918 return NULL;
4919 p = strchr(s, '\n');
4920 if (p)
4921 *p = '\0';
4922 return s;
4925 static const struct got_error *
4926 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4927 off_t off, uint8_t type)
4929 struct got_diff_line *p;
4931 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4932 if (p == NULL)
4933 return got_error_from_errno("reallocarray");
4934 *lines = p;
4935 (*lines)[*nlines].offset = off;
4936 (*lines)[*nlines].type = type;
4937 (*nlines)++;
4939 return NULL;
4942 static const struct got_error *
4943 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4944 struct got_diff_line *s_lines, size_t s_nlines)
4946 struct got_diff_line *p;
4947 char buf[BUFSIZ];
4948 size_t i, r;
4950 if (fseeko(src, 0L, SEEK_SET) == -1)
4951 return got_error_from_errno("fseeko");
4953 for (;;) {
4954 r = fread(buf, 1, sizeof(buf), src);
4955 if (r == 0) {
4956 if (ferror(src))
4957 return got_error_from_errno("fread");
4958 if (feof(src))
4959 break;
4961 if (fwrite(buf, 1, r, dst) != r)
4962 return got_ferror(dst, GOT_ERR_IO);
4965 if (s_nlines == 0 && *d_nlines == 0)
4966 return NULL;
4969 * If commit info was in dst, increment line offsets
4970 * of the appended diff content, but skip s_lines[0]
4971 * because offset zero is already in *d_lines.
4973 if (*d_nlines > 0) {
4974 for (i = 1; i < s_nlines; ++i)
4975 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4977 if (s_nlines > 0) {
4978 --s_nlines;
4979 ++s_lines;
4983 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4984 if (p == NULL) {
4985 /* d_lines is freed in close_diff_view() */
4986 return got_error_from_errno("reallocarray");
4989 *d_lines = p;
4991 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4992 *d_nlines += s_nlines;
4994 return NULL;
4997 static const struct got_error *
4998 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4999 struct got_object_id *commit_id, struct got_reflist_head *refs,
5000 struct got_repository *repo, int ignore_ws, int force_text_diff,
5001 struct got_diffstat_cb_arg *dsa, FILE *outfile)
5003 const struct got_error *err = NULL;
5004 char datebuf[26], *datestr;
5005 struct got_commit_object *commit;
5006 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
5007 time_t committer_time;
5008 const char *author, *committer;
5009 char *refs_str = NULL;
5010 struct got_pathlist_entry *pe;
5011 off_t outoff = 0;
5012 int n;
5014 err = build_refs_str(&refs_str, refs, commit_id, repo);
5015 if (err)
5016 return err;
5018 err = got_object_open_as_commit(&commit, repo, commit_id);
5019 if (err)
5020 return err;
5022 err = got_object_id_str(&id_str, commit_id);
5023 if (err) {
5024 err = got_error_from_errno("got_object_id_str");
5025 goto done;
5028 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
5029 if (err)
5030 goto done;
5032 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
5033 refs_str ? refs_str : "", refs_str ? ")" : "");
5034 if (n < 0) {
5035 err = got_error_from_errno("fprintf");
5036 goto done;
5038 outoff += n;
5039 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
5040 if (err)
5041 goto done;
5043 n = fprintf(outfile, "from: %s\n",
5044 got_object_commit_get_author(commit));
5045 if (n < 0) {
5046 err = got_error_from_errno("fprintf");
5047 goto done;
5049 outoff += n;
5050 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
5051 if (err)
5052 goto done;
5054 author = got_object_commit_get_author(commit);
5055 committer = got_object_commit_get_committer(commit);
5056 if (strcmp(author, committer) != 0) {
5057 n = fprintf(outfile, "via: %s\n", committer);
5058 if (n < 0) {
5059 err = got_error_from_errno("fprintf");
5060 goto done;
5062 outoff += n;
5063 err = add_line_metadata(lines, nlines, outoff,
5064 GOT_DIFF_LINE_AUTHOR);
5065 if (err)
5066 goto done;
5068 committer_time = got_object_commit_get_committer_time(commit);
5069 datestr = get_datestr(&committer_time, datebuf);
5070 if (datestr) {
5071 n = fprintf(outfile, "date: %s UTC\n", datestr);
5072 if (n < 0) {
5073 err = got_error_from_errno("fprintf");
5074 goto done;
5076 outoff += n;
5077 err = add_line_metadata(lines, nlines, outoff,
5078 GOT_DIFF_LINE_DATE);
5079 if (err)
5080 goto done;
5082 if (got_object_commit_get_nparents(commit) > 1) {
5083 const struct got_object_id_queue *parent_ids;
5084 struct got_object_qid *qid;
5085 int pn = 1;
5086 parent_ids = got_object_commit_get_parent_ids(commit);
5087 STAILQ_FOREACH(qid, parent_ids, entry) {
5088 err = got_object_id_str(&id_str, &qid->id);
5089 if (err)
5090 goto done;
5091 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
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_META);
5099 if (err)
5100 goto done;
5101 free(id_str);
5102 id_str = NULL;
5106 err = got_object_commit_get_logmsg(&logmsg, commit);
5107 if (err)
5108 goto done;
5109 s = logmsg;
5110 while ((line = strsep(&s, "\n")) != NULL) {
5111 n = fprintf(outfile, "%s\n", line);
5112 if (n < 0) {
5113 err = got_error_from_errno("fprintf");
5114 goto done;
5116 outoff += n;
5117 err = add_line_metadata(lines, nlines, outoff,
5118 GOT_DIFF_LINE_LOGMSG);
5119 if (err)
5120 goto done;
5123 TAILQ_FOREACH(pe, dsa->paths, entry) {
5124 struct got_diff_changed_path *cp = pe->data;
5125 int pad = dsa->max_path_len - pe->path_len + 1;
5127 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5128 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5129 dsa->rm_cols + 1, cp->rm);
5130 if (n < 0) {
5131 err = got_error_from_errno("fprintf");
5132 goto done;
5134 outoff += n;
5135 err = add_line_metadata(lines, nlines, outoff,
5136 GOT_DIFF_LINE_CHANGES);
5137 if (err)
5138 goto done;
5141 fputc('\n', outfile);
5142 outoff++;
5143 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5144 if (err)
5145 goto done;
5147 n = fprintf(outfile,
5148 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5149 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5150 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5151 if (n < 0) {
5152 err = got_error_from_errno("fprintf");
5153 goto done;
5155 outoff += n;
5156 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5157 if (err)
5158 goto done;
5160 fputc('\n', outfile);
5161 outoff++;
5162 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5163 done:
5164 free(id_str);
5165 free(logmsg);
5166 free(refs_str);
5167 got_object_commit_close(commit);
5168 if (err) {
5169 free(*lines);
5170 *lines = NULL;
5171 *nlines = 0;
5173 return err;
5176 static const struct got_error *
5177 create_diff(struct tog_diff_view_state *s)
5179 const struct got_error *err = NULL;
5180 FILE *f = NULL, *tmp_diff_file = NULL;
5181 int obj_type;
5182 struct got_diff_line *lines = NULL;
5183 struct got_pathlist_head changed_paths;
5185 TAILQ_INIT(&changed_paths);
5187 free(s->lines);
5188 s->lines = malloc(sizeof(*s->lines));
5189 if (s->lines == NULL)
5190 return got_error_from_errno("malloc");
5191 s->nlines = 0;
5193 f = got_opentemp();
5194 if (f == NULL) {
5195 err = got_error_from_errno("got_opentemp");
5196 goto done;
5198 tmp_diff_file = got_opentemp();
5199 if (tmp_diff_file == NULL) {
5200 err = got_error_from_errno("got_opentemp");
5201 goto done;
5203 if (s->f && fclose(s->f) == EOF) {
5204 err = got_error_from_errno("fclose");
5205 goto done;
5207 s->f = f;
5209 if (s->id1)
5210 err = got_object_get_type(&obj_type, s->repo, s->id1);
5211 else
5212 err = got_object_get_type(&obj_type, s->repo, s->id2);
5213 if (err)
5214 goto done;
5216 switch (obj_type) {
5217 case GOT_OBJ_TYPE_BLOB:
5218 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5219 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5220 s->label1, s->label2, tog_diff_algo, s->diff_context,
5221 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5222 s->f);
5223 break;
5224 case GOT_OBJ_TYPE_TREE:
5225 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5226 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5227 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5228 s->force_text_diff, NULL, s->repo, s->f);
5229 break;
5230 case GOT_OBJ_TYPE_COMMIT: {
5231 const struct got_object_id_queue *parent_ids;
5232 struct got_object_qid *pid;
5233 struct got_commit_object *commit2;
5234 struct got_reflist_head *refs;
5235 size_t nlines = 0;
5236 struct got_diffstat_cb_arg dsa = {
5237 0, 0, 0, 0, 0, 0,
5238 &changed_paths,
5239 s->ignore_whitespace,
5240 s->force_text_diff,
5241 tog_diff_algo
5244 lines = malloc(sizeof(*lines));
5245 if (lines == NULL) {
5246 err = got_error_from_errno("malloc");
5247 goto done;
5250 /* build diff first in tmp file then append to commit info */
5251 err = got_diff_objects_as_commits(&lines, &nlines,
5252 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5253 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5254 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5255 if (err)
5256 break;
5258 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5259 if (err)
5260 goto done;
5261 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5262 /* Show commit info if we're diffing to a parent/root commit. */
5263 if (s->id1 == NULL) {
5264 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5265 refs, s->repo, s->ignore_whitespace,
5266 s->force_text_diff, &dsa, s->f);
5267 if (err)
5268 goto done;
5269 } else {
5270 parent_ids = got_object_commit_get_parent_ids(commit2);
5271 STAILQ_FOREACH(pid, parent_ids, entry) {
5272 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5273 err = write_commit_info(&s->lines,
5274 &s->nlines, s->id2, refs, s->repo,
5275 s->ignore_whitespace,
5276 s->force_text_diff, &dsa, s->f);
5277 if (err)
5278 goto done;
5279 break;
5283 got_object_commit_close(commit2);
5285 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5286 lines, nlines);
5287 break;
5289 default:
5290 err = got_error(GOT_ERR_OBJ_TYPE);
5291 break;
5293 done:
5294 free(lines);
5295 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5296 if (s->f && fflush(s->f) != 0 && err == NULL)
5297 err = got_error_from_errno("fflush");
5298 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5299 err = got_error_from_errno("fclose");
5300 return err;
5303 static void
5304 diff_view_indicate_progress(struct tog_view *view)
5306 mvwaddstr(view->window, 0, 0, "diffing...");
5307 update_panels();
5308 doupdate();
5311 static const struct got_error *
5312 search_start_diff_view(struct tog_view *view)
5314 struct tog_diff_view_state *s = &view->state.diff;
5316 s->matched_line = 0;
5317 return NULL;
5320 static void
5321 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5322 size_t *nlines, int **first, int **last, int **match, int **selected)
5324 struct tog_diff_view_state *s = &view->state.diff;
5326 *f = s->f;
5327 *nlines = s->nlines;
5328 *line_offsets = NULL;
5329 *match = &s->matched_line;
5330 *first = &s->first_displayed_line;
5331 *last = &s->last_displayed_line;
5332 *selected = &s->selected_line;
5335 static const struct got_error *
5336 search_next_view_match(struct tog_view *view)
5338 const struct got_error *err = NULL;
5339 FILE *f;
5340 int lineno;
5341 char *line = NULL;
5342 size_t linesize = 0;
5343 ssize_t linelen;
5344 off_t *line_offsets;
5345 size_t nlines = 0;
5346 int *first, *last, *match, *selected;
5348 if (!view->search_setup)
5349 return got_error_msg(GOT_ERR_NOT_IMPL,
5350 "view search not supported");
5351 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5352 &match, &selected);
5354 if (!view->searching) {
5355 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5356 return NULL;
5359 if (*match) {
5360 if (view->searching == TOG_SEARCH_FORWARD)
5361 lineno = *first + 1;
5362 else
5363 lineno = *first - 1;
5364 } else
5365 lineno = *first - 1 + *selected;
5367 while (1) {
5368 off_t offset;
5370 if (lineno <= 0 || lineno > nlines) {
5371 if (*match == 0) {
5372 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5373 break;
5376 if (view->searching == TOG_SEARCH_FORWARD)
5377 lineno = 1;
5378 else
5379 lineno = nlines;
5382 offset = view->type == TOG_VIEW_DIFF ?
5383 view->state.diff.lines[lineno - 1].offset :
5384 line_offsets[lineno - 1];
5385 if (fseeko(f, offset, SEEK_SET) != 0) {
5386 free(line);
5387 return got_error_from_errno("fseeko");
5389 linelen = getline(&line, &linesize, f);
5390 if (linelen != -1) {
5391 char *exstr;
5392 err = expand_tab(&exstr, line);
5393 if (err)
5394 break;
5395 if (match_line(exstr, &view->regex, 1,
5396 &view->regmatch)) {
5397 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5398 *match = lineno;
5399 free(exstr);
5400 break;
5402 free(exstr);
5404 if (view->searching == TOG_SEARCH_FORWARD)
5405 lineno++;
5406 else
5407 lineno--;
5409 free(line);
5411 if (*match) {
5412 *first = *match;
5413 *selected = 1;
5416 return err;
5419 static const struct got_error *
5420 close_diff_view(struct tog_view *view)
5422 const struct got_error *err = NULL;
5423 struct tog_diff_view_state *s = &view->state.diff;
5425 free(s->id1);
5426 s->id1 = NULL;
5427 free(s->id2);
5428 s->id2 = NULL;
5429 if (s->f && fclose(s->f) == EOF)
5430 err = got_error_from_errno("fclose");
5431 s->f = NULL;
5432 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5433 err = got_error_from_errno("fclose");
5434 s->f1 = NULL;
5435 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5436 err = got_error_from_errno("fclose");
5437 s->f2 = NULL;
5438 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5439 err = got_error_from_errno("close");
5440 s->fd1 = -1;
5441 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5442 err = got_error_from_errno("close");
5443 s->fd2 = -1;
5444 free(s->lines);
5445 s->lines = NULL;
5446 s->nlines = 0;
5447 return err;
5450 static const struct got_error *
5451 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5452 struct got_object_id *id2, const char *label1, const char *label2,
5453 int diff_context, int ignore_whitespace, int force_text_diff,
5454 struct tog_view *parent_view, struct got_repository *repo)
5456 const struct got_error *err;
5457 struct tog_diff_view_state *s = &view->state.diff;
5459 memset(s, 0, sizeof(*s));
5460 s->fd1 = -1;
5461 s->fd2 = -1;
5463 if (id1 != NULL && id2 != NULL) {
5464 int type1, type2;
5466 err = got_object_get_type(&type1, repo, id1);
5467 if (err)
5468 goto done;
5469 err = got_object_get_type(&type2, repo, id2);
5470 if (err)
5471 goto done;
5473 if (type1 != type2) {
5474 err = got_error(GOT_ERR_OBJ_TYPE);
5475 goto done;
5478 s->first_displayed_line = 1;
5479 s->last_displayed_line = view->nlines;
5480 s->selected_line = 1;
5481 s->repo = repo;
5482 s->id1 = id1;
5483 s->id2 = id2;
5484 s->label1 = label1;
5485 s->label2 = label2;
5487 if (id1) {
5488 s->id1 = got_object_id_dup(id1);
5489 if (s->id1 == NULL) {
5490 err = got_error_from_errno("got_object_id_dup");
5491 goto done;
5493 } else
5494 s->id1 = NULL;
5496 s->id2 = got_object_id_dup(id2);
5497 if (s->id2 == NULL) {
5498 err = got_error_from_errno("got_object_id_dup");
5499 goto done;
5502 s->f1 = got_opentemp();
5503 if (s->f1 == NULL) {
5504 err = got_error_from_errno("got_opentemp");
5505 goto done;
5508 s->f2 = got_opentemp();
5509 if (s->f2 == NULL) {
5510 err = got_error_from_errno("got_opentemp");
5511 goto done;
5514 s->fd1 = got_opentempfd();
5515 if (s->fd1 == -1) {
5516 err = got_error_from_errno("got_opentempfd");
5517 goto done;
5520 s->fd2 = got_opentempfd();
5521 if (s->fd2 == -1) {
5522 err = got_error_from_errno("got_opentempfd");
5523 goto done;
5526 s->diff_context = diff_context;
5527 s->ignore_whitespace = ignore_whitespace;
5528 s->force_text_diff = force_text_diff;
5529 s->parent_view = parent_view;
5530 s->repo = repo;
5532 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5533 int rc;
5535 rc = init_pair(GOT_DIFF_LINE_MINUS,
5536 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5537 if (rc != ERR)
5538 rc = init_pair(GOT_DIFF_LINE_PLUS,
5539 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5540 if (rc != ERR)
5541 rc = init_pair(GOT_DIFF_LINE_HUNK,
5542 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5543 if (rc != ERR)
5544 rc = init_pair(GOT_DIFF_LINE_META,
5545 get_color_value("TOG_COLOR_DIFF_META"), -1);
5546 if (rc != ERR)
5547 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5548 get_color_value("TOG_COLOR_DIFF_META"), -1);
5549 if (rc != ERR)
5550 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5551 get_color_value("TOG_COLOR_DIFF_META"), -1);
5552 if (rc != ERR)
5553 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5554 get_color_value("TOG_COLOR_DIFF_META"), -1);
5555 if (rc != ERR)
5556 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5557 get_color_value("TOG_COLOR_AUTHOR"), -1);
5558 if (rc != ERR)
5559 rc = init_pair(GOT_DIFF_LINE_DATE,
5560 get_color_value("TOG_COLOR_DATE"), -1);
5561 if (rc == ERR) {
5562 err = got_error(GOT_ERR_RANGE);
5563 goto done;
5567 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5568 view_is_splitscreen(view))
5569 show_log_view(parent_view); /* draw border */
5570 diff_view_indicate_progress(view);
5572 err = create_diff(s);
5574 view->show = show_diff_view;
5575 view->input = input_diff_view;
5576 view->reset = reset_diff_view;
5577 view->close = close_diff_view;
5578 view->search_start = search_start_diff_view;
5579 view->search_setup = search_setup_diff_view;
5580 view->search_next = search_next_view_match;
5581 done:
5582 if (err) {
5583 if (view->close == NULL)
5584 close_diff_view(view);
5585 view_close(view);
5587 return err;
5590 static const struct got_error *
5591 show_diff_view(struct tog_view *view)
5593 const struct got_error *err;
5594 struct tog_diff_view_state *s = &view->state.diff;
5595 char *id_str1 = NULL, *id_str2, *header;
5596 const char *label1, *label2;
5598 if (s->id1) {
5599 err = got_object_id_str(&id_str1, s->id1);
5600 if (err)
5601 return err;
5602 label1 = s->label1 ? s->label1 : id_str1;
5603 } else
5604 label1 = "/dev/null";
5606 err = got_object_id_str(&id_str2, s->id2);
5607 if (err)
5608 return err;
5609 label2 = s->label2 ? s->label2 : id_str2;
5611 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5612 err = got_error_from_errno("asprintf");
5613 free(id_str1);
5614 free(id_str2);
5615 return err;
5617 free(id_str1);
5618 free(id_str2);
5620 err = draw_file(view, header);
5621 free(header);
5622 return err;
5625 static const struct got_error *
5626 set_selected_commit(struct tog_diff_view_state *s,
5627 struct commit_queue_entry *entry)
5629 const struct got_error *err;
5630 const struct got_object_id_queue *parent_ids;
5631 struct got_commit_object *selected_commit;
5632 struct got_object_qid *pid;
5634 free(s->id2);
5635 s->id2 = got_object_id_dup(entry->id);
5636 if (s->id2 == NULL)
5637 return got_error_from_errno("got_object_id_dup");
5639 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5640 if (err)
5641 return err;
5642 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5643 free(s->id1);
5644 pid = STAILQ_FIRST(parent_ids);
5645 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5646 got_object_commit_close(selected_commit);
5647 return NULL;
5650 static const struct got_error *
5651 reset_diff_view(struct tog_view *view)
5653 struct tog_diff_view_state *s = &view->state.diff;
5655 view->count = 0;
5656 wclear(view->window);
5657 s->first_displayed_line = 1;
5658 s->last_displayed_line = view->nlines;
5659 s->matched_line = 0;
5660 diff_view_indicate_progress(view);
5661 return create_diff(s);
5664 static void
5665 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5667 int start, i;
5669 i = start = s->first_displayed_line - 1;
5671 while (s->lines[i].type != type) {
5672 if (i == 0)
5673 i = s->nlines - 1;
5674 if (--i == start)
5675 return; /* do nothing, requested type not in file */
5678 s->selected_line = 1;
5679 s->first_displayed_line = i;
5682 static void
5683 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5685 int start, i;
5687 i = start = s->first_displayed_line + 1;
5689 while (s->lines[i].type != type) {
5690 if (i == s->nlines - 1)
5691 i = 0;
5692 if (++i == start)
5693 return; /* do nothing, requested type not in file */
5696 s->selected_line = 1;
5697 s->first_displayed_line = i;
5700 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5701 int, int, int);
5702 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5703 int, int);
5705 static const struct got_error *
5706 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5708 const struct got_error *err = NULL;
5709 struct tog_diff_view_state *s = &view->state.diff;
5710 struct tog_log_view_state *ls;
5711 struct commit_queue_entry *old_selected_entry;
5712 char *line = NULL;
5713 size_t linesize = 0;
5714 ssize_t linelen;
5715 int i, nscroll = view->nlines - 1, up = 0;
5717 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5719 switch (ch) {
5720 case '0':
5721 case '$':
5722 case KEY_RIGHT:
5723 case 'l':
5724 case KEY_LEFT:
5725 case 'h':
5726 horizontal_scroll_input(view, ch);
5727 break;
5728 case 'a':
5729 case 'w':
5730 if (ch == 'a') {
5731 s->force_text_diff = !s->force_text_diff;
5732 view->action = s->force_text_diff ?
5733 "force ASCII text enabled" :
5734 "force ASCII text disabled";
5736 else if (ch == 'w') {
5737 s->ignore_whitespace = !s->ignore_whitespace;
5738 view->action = s->ignore_whitespace ?
5739 "ignore whitespace enabled" :
5740 "ignore whitespace disabled";
5742 err = reset_diff_view(view);
5743 break;
5744 case 'g':
5745 case KEY_HOME:
5746 s->first_displayed_line = 1;
5747 view->count = 0;
5748 break;
5749 case 'G':
5750 case KEY_END:
5751 view->count = 0;
5752 if (s->eof)
5753 break;
5755 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5756 s->eof = 1;
5757 break;
5758 case 'k':
5759 case KEY_UP:
5760 case CTRL('p'):
5761 if (s->first_displayed_line > 1)
5762 s->first_displayed_line--;
5763 else
5764 view->count = 0;
5765 break;
5766 case CTRL('u'):
5767 case 'u':
5768 nscroll /= 2;
5769 /* FALL THROUGH */
5770 case KEY_PPAGE:
5771 case CTRL('b'):
5772 case 'b':
5773 if (s->first_displayed_line == 1) {
5774 view->count = 0;
5775 break;
5777 i = 0;
5778 while (i++ < nscroll && s->first_displayed_line > 1)
5779 s->first_displayed_line--;
5780 break;
5781 case 'j':
5782 case KEY_DOWN:
5783 case CTRL('n'):
5784 if (!s->eof)
5785 s->first_displayed_line++;
5786 else
5787 view->count = 0;
5788 break;
5789 case CTRL('d'):
5790 case 'd':
5791 nscroll /= 2;
5792 /* FALL THROUGH */
5793 case KEY_NPAGE:
5794 case CTRL('f'):
5795 case 'f':
5796 case ' ':
5797 if (s->eof) {
5798 view->count = 0;
5799 break;
5801 i = 0;
5802 while (!s->eof && i++ < nscroll) {
5803 linelen = getline(&line, &linesize, s->f);
5804 s->first_displayed_line++;
5805 if (linelen == -1) {
5806 if (feof(s->f)) {
5807 s->eof = 1;
5808 } else
5809 err = got_ferror(s->f, GOT_ERR_IO);
5810 break;
5813 free(line);
5814 break;
5815 case '(':
5816 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5817 break;
5818 case ')':
5819 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5820 break;
5821 case '{':
5822 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5823 break;
5824 case '}':
5825 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5826 break;
5827 case '[':
5828 if (s->diff_context > 0) {
5829 s->diff_context--;
5830 s->matched_line = 0;
5831 diff_view_indicate_progress(view);
5832 err = create_diff(s);
5833 if (s->first_displayed_line + view->nlines - 1 >
5834 s->nlines) {
5835 s->first_displayed_line = 1;
5836 s->last_displayed_line = view->nlines;
5838 } else
5839 view->count = 0;
5840 break;
5841 case ']':
5842 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5843 s->diff_context++;
5844 s->matched_line = 0;
5845 diff_view_indicate_progress(view);
5846 err = create_diff(s);
5847 } else
5848 view->count = 0;
5849 break;
5850 case '<':
5851 case ',':
5852 case 'K':
5853 up = 1;
5854 /* FALL THROUGH */
5855 case '>':
5856 case '.':
5857 case 'J':
5858 if (s->parent_view == NULL) {
5859 view->count = 0;
5860 break;
5862 s->parent_view->count = view->count;
5864 if (s->parent_view->type == TOG_VIEW_LOG) {
5865 ls = &s->parent_view->state.log;
5866 old_selected_entry = ls->selected_entry;
5868 err = input_log_view(NULL, s->parent_view,
5869 up ? KEY_UP : KEY_DOWN);
5870 if (err)
5871 break;
5872 view->count = s->parent_view->count;
5874 if (old_selected_entry == ls->selected_entry)
5875 break;
5877 err = set_selected_commit(s, ls->selected_entry);
5878 if (err)
5879 break;
5880 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5881 struct tog_blame_view_state *bs;
5882 struct got_object_id *id, *prev_id;
5884 bs = &s->parent_view->state.blame;
5885 prev_id = get_annotation_for_line(bs->blame.lines,
5886 bs->blame.nlines, bs->last_diffed_line);
5888 err = input_blame_view(&view, s->parent_view,
5889 up ? KEY_UP : KEY_DOWN);
5890 if (err)
5891 break;
5892 view->count = s->parent_view->count;
5894 if (prev_id == NULL)
5895 break;
5896 id = get_selected_commit_id(bs->blame.lines,
5897 bs->blame.nlines, bs->first_displayed_line,
5898 bs->selected_line);
5899 if (id == NULL)
5900 break;
5902 if (!got_object_id_cmp(prev_id, id))
5903 break;
5905 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5906 if (err)
5907 break;
5909 s->first_displayed_line = 1;
5910 s->last_displayed_line = view->nlines;
5911 s->matched_line = 0;
5912 view->x = 0;
5914 diff_view_indicate_progress(view);
5915 err = create_diff(s);
5916 break;
5917 default:
5918 view->count = 0;
5919 break;
5922 return err;
5925 static const struct got_error *
5926 cmd_diff(int argc, char *argv[])
5928 const struct got_error *error;
5929 struct got_repository *repo = NULL;
5930 struct got_worktree *worktree = NULL;
5931 struct got_object_id *id1 = NULL, *id2 = NULL;
5932 char *repo_path = NULL, *cwd = NULL;
5933 char *id_str1 = NULL, *id_str2 = NULL;
5934 char *keyword_idstr1 = NULL, *keyword_idstr2 = NULL;
5935 char *label1 = NULL, *label2 = NULL;
5936 int diff_context = 3, ignore_whitespace = 0;
5937 int ch, force_text_diff = 0;
5938 const char *errstr;
5939 struct tog_view *view;
5940 int *pack_fds = NULL;
5942 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5943 switch (ch) {
5944 case 'a':
5945 force_text_diff = 1;
5946 break;
5947 case 'C':
5948 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5949 &errstr);
5950 if (errstr != NULL)
5951 errx(1, "number of context lines is %s: %s",
5952 errstr, errstr);
5953 break;
5954 case 'r':
5955 repo_path = realpath(optarg, NULL);
5956 if (repo_path == NULL)
5957 return got_error_from_errno2("realpath",
5958 optarg);
5959 got_path_strip_trailing_slashes(repo_path);
5960 break;
5961 case 'w':
5962 ignore_whitespace = 1;
5963 break;
5964 default:
5965 usage_diff();
5966 /* NOTREACHED */
5970 argc -= optind;
5971 argv += optind;
5973 if (argc == 0) {
5974 usage_diff(); /* TODO show local worktree changes */
5975 } else if (argc == 2) {
5976 id_str1 = argv[0];
5977 id_str2 = argv[1];
5978 } else
5979 usage_diff();
5981 error = got_repo_pack_fds_open(&pack_fds);
5982 if (error)
5983 goto done;
5985 if (repo_path == NULL) {
5986 cwd = getcwd(NULL, 0);
5987 if (cwd == NULL)
5988 return got_error_from_errno("getcwd");
5989 error = got_worktree_open(&worktree, cwd, NULL);
5990 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5991 goto done;
5992 if (worktree)
5993 repo_path =
5994 strdup(got_worktree_get_repo_path(worktree));
5995 else
5996 repo_path = strdup(cwd);
5997 if (repo_path == NULL) {
5998 error = got_error_from_errno("strdup");
5999 goto done;
6003 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6004 if (error)
6005 goto done;
6007 init_curses();
6009 error = apply_unveil(got_repo_get_path(repo), NULL);
6010 if (error)
6011 goto done;
6013 error = tog_load_refs(repo, 0);
6014 if (error)
6015 goto done;
6017 if (id_str1 != NULL) {
6018 error = got_keyword_to_idstr(&keyword_idstr1, id_str1,
6019 repo, worktree);
6020 if (error != NULL)
6021 goto done;
6022 if (keyword_idstr1 != NULL)
6023 id_str1 = keyword_idstr1;
6025 if (id_str2 != NULL) {
6026 error = got_keyword_to_idstr(&keyword_idstr2, id_str2,
6027 repo, worktree);
6028 if (error != NULL)
6029 goto done;
6030 if (keyword_idstr2 != NULL)
6031 id_str2 = keyword_idstr2;
6034 error = got_repo_match_object_id(&id1, &label1, id_str1,
6035 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6036 if (error)
6037 goto done;
6039 error = got_repo_match_object_id(&id2, &label2, id_str2,
6040 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6041 if (error)
6042 goto done;
6044 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
6045 if (view == NULL) {
6046 error = got_error_from_errno("view_open");
6047 goto done;
6049 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
6050 ignore_whitespace, force_text_diff, NULL, repo);
6051 if (error)
6052 goto done;
6053 error = view_loop(view);
6054 done:
6055 free(keyword_idstr1);
6056 free(keyword_idstr2);
6057 free(label1);
6058 free(label2);
6059 free(repo_path);
6060 free(cwd);
6061 if (repo) {
6062 const struct got_error *close_err = got_repo_close(repo);
6063 if (error == NULL)
6064 error = close_err;
6066 if (worktree)
6067 got_worktree_close(worktree);
6068 if (pack_fds) {
6069 const struct got_error *pack_err =
6070 got_repo_pack_fds_close(pack_fds);
6071 if (error == NULL)
6072 error = pack_err;
6074 tog_free_refs();
6075 return error;
6078 __dead static void
6079 usage_blame(void)
6081 endwin();
6082 fprintf(stderr,
6083 "usage: %s blame [-c commit] [-r repository-path] path\n",
6084 getprogname());
6085 exit(1);
6088 struct tog_blame_line {
6089 int annotated;
6090 struct got_object_id *id;
6093 static const struct got_error *
6094 draw_blame(struct tog_view *view)
6096 struct tog_blame_view_state *s = &view->state.blame;
6097 struct tog_blame *blame = &s->blame;
6098 regmatch_t *regmatch = &view->regmatch;
6099 const struct got_error *err;
6100 int lineno = 0, nprinted = 0;
6101 char *line = NULL;
6102 size_t linesize = 0;
6103 ssize_t linelen;
6104 wchar_t *wline;
6105 int width;
6106 struct tog_blame_line *blame_line;
6107 struct got_object_id *prev_id = NULL;
6108 char *id_str;
6109 struct tog_color *tc;
6111 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6112 if (err)
6113 return err;
6115 rewind(blame->f);
6116 werase(view->window);
6118 if (asprintf(&line, "commit %s", id_str) == -1) {
6119 err = got_error_from_errno("asprintf");
6120 free(id_str);
6121 return err;
6124 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6125 free(line);
6126 line = NULL;
6127 if (err)
6128 return err;
6129 if (view_needs_focus_indication(view))
6130 wstandout(view->window);
6131 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6132 if (tc)
6133 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6134 waddwstr(view->window, wline);
6135 while (width++ < view->ncols)
6136 waddch(view->window, ' ');
6137 if (tc)
6138 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6139 if (view_needs_focus_indication(view))
6140 wstandend(view->window);
6141 free(wline);
6142 wline = NULL;
6144 if (view->gline > blame->nlines)
6145 view->gline = blame->nlines;
6147 if (tog_io.wait_for_ui) {
6148 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6149 int rc;
6151 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6152 if (rc)
6153 return got_error_set_errno(rc, "pthread_cond_wait");
6154 tog_io.wait_for_ui = 0;
6157 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6158 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6159 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6160 free(id_str);
6161 return got_error_from_errno("asprintf");
6163 free(id_str);
6164 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6165 free(line);
6166 line = NULL;
6167 if (err)
6168 return err;
6169 waddwstr(view->window, wline);
6170 free(wline);
6171 wline = NULL;
6172 if (width < view->ncols - 1)
6173 waddch(view->window, '\n');
6175 s->eof = 0;
6176 view->maxx = 0;
6177 while (nprinted < view->nlines - 2) {
6178 linelen = getline(&line, &linesize, blame->f);
6179 if (linelen == -1) {
6180 if (feof(blame->f)) {
6181 s->eof = 1;
6182 break;
6184 free(line);
6185 return got_ferror(blame->f, GOT_ERR_IO);
6187 if (++lineno < s->first_displayed_line)
6188 continue;
6189 if (view->gline && !gotoline(view, &lineno, &nprinted))
6190 continue;
6192 /* Set view->maxx based on full line length. */
6193 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6194 if (err) {
6195 free(line);
6196 return err;
6198 free(wline);
6199 wline = NULL;
6200 view->maxx = MAX(view->maxx, width);
6202 if (nprinted == s->selected_line - 1)
6203 wstandout(view->window);
6205 if (blame->nlines > 0) {
6206 blame_line = &blame->lines[lineno - 1];
6207 if (blame_line->annotated && prev_id &&
6208 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6209 !(nprinted == s->selected_line - 1)) {
6210 waddstr(view->window, " ");
6211 } else if (blame_line->annotated) {
6212 char *id_str;
6213 err = got_object_id_str(&id_str,
6214 blame_line->id);
6215 if (err) {
6216 free(line);
6217 return err;
6219 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6220 if (tc)
6221 wattr_on(view->window,
6222 COLOR_PAIR(tc->colorpair), NULL);
6223 wprintw(view->window, "%.8s", id_str);
6224 if (tc)
6225 wattr_off(view->window,
6226 COLOR_PAIR(tc->colorpair), NULL);
6227 free(id_str);
6228 prev_id = blame_line->id;
6229 } else {
6230 waddstr(view->window, "........");
6231 prev_id = NULL;
6233 } else {
6234 waddstr(view->window, "........");
6235 prev_id = NULL;
6238 if (nprinted == s->selected_line - 1)
6239 wstandend(view->window);
6240 waddstr(view->window, " ");
6242 if (view->ncols <= 9) {
6243 width = 9;
6244 } else if (s->first_displayed_line + nprinted ==
6245 s->matched_line &&
6246 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6247 err = add_matched_line(&width, line, view->ncols - 9, 9,
6248 view->window, view->x, regmatch);
6249 if (err) {
6250 free(line);
6251 return err;
6253 width += 9;
6254 } else {
6255 int skip;
6256 err = format_line(&wline, &width, &skip, line,
6257 view->x, view->ncols - 9, 9, 1);
6258 if (err) {
6259 free(line);
6260 return err;
6262 waddwstr(view->window, &wline[skip]);
6263 width += 9;
6264 free(wline);
6265 wline = NULL;
6268 if (width <= view->ncols - 1)
6269 waddch(view->window, '\n');
6270 if (++nprinted == 1)
6271 s->first_displayed_line = lineno;
6273 free(line);
6274 s->last_displayed_line = lineno;
6276 view_border(view);
6278 return NULL;
6281 static const struct got_error *
6282 blame_cb(void *arg, int nlines, int lineno,
6283 struct got_commit_object *commit, struct got_object_id *id)
6285 const struct got_error *err = NULL;
6286 struct tog_blame_cb_args *a = arg;
6287 struct tog_blame_line *line;
6288 int errcode;
6290 if (nlines != a->nlines ||
6291 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6292 return got_error(GOT_ERR_RANGE);
6294 errcode = pthread_mutex_lock(&tog_mutex);
6295 if (errcode)
6296 return got_error_set_errno(errcode, "pthread_mutex_lock");
6298 if (*a->quit) { /* user has quit the blame view */
6299 err = got_error(GOT_ERR_ITER_COMPLETED);
6300 goto done;
6303 if (lineno == -1)
6304 goto done; /* no change in this commit */
6306 line = &a->lines[lineno - 1];
6307 if (line->annotated)
6308 goto done;
6310 line->id = got_object_id_dup(id);
6311 if (line->id == NULL) {
6312 err = got_error_from_errno("got_object_id_dup");
6313 goto done;
6315 line->annotated = 1;
6316 done:
6317 errcode = pthread_mutex_unlock(&tog_mutex);
6318 if (errcode)
6319 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6320 return err;
6323 static void *
6324 blame_thread(void *arg)
6326 const struct got_error *err, *close_err;
6327 struct tog_blame_thread_args *ta = arg;
6328 struct tog_blame_cb_args *a = ta->cb_args;
6329 int errcode, fd1 = -1, fd2 = -1;
6330 FILE *f1 = NULL, *f2 = NULL;
6332 fd1 = got_opentempfd();
6333 if (fd1 == -1)
6334 return (void *)got_error_from_errno("got_opentempfd");
6336 fd2 = got_opentempfd();
6337 if (fd2 == -1) {
6338 err = got_error_from_errno("got_opentempfd");
6339 goto done;
6342 f1 = got_opentemp();
6343 if (f1 == NULL) {
6344 err = (void *)got_error_from_errno("got_opentemp");
6345 goto done;
6347 f2 = got_opentemp();
6348 if (f2 == NULL) {
6349 err = (void *)got_error_from_errno("got_opentemp");
6350 goto done;
6353 err = block_signals_used_by_main_thread();
6354 if (err)
6355 goto done;
6357 err = got_blame(ta->path, a->commit_id, ta->repo,
6358 tog_diff_algo, blame_cb, ta->cb_args,
6359 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6360 if (err && err->code == GOT_ERR_CANCELLED)
6361 err = NULL;
6363 errcode = pthread_mutex_lock(&tog_mutex);
6364 if (errcode) {
6365 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6366 goto done;
6369 close_err = got_repo_close(ta->repo);
6370 if (err == NULL)
6371 err = close_err;
6372 ta->repo = NULL;
6373 *ta->complete = 1;
6375 if (tog_io.wait_for_ui) {
6376 errcode = pthread_cond_signal(&ta->blame_complete);
6377 if (errcode && err == NULL)
6378 err = got_error_set_errno(errcode,
6379 "pthread_cond_signal");
6382 errcode = pthread_mutex_unlock(&tog_mutex);
6383 if (errcode && err == NULL)
6384 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6386 done:
6387 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6388 err = got_error_from_errno("close");
6389 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6390 err = got_error_from_errno("close");
6391 if (f1 && fclose(f1) == EOF && err == NULL)
6392 err = got_error_from_errno("fclose");
6393 if (f2 && fclose(f2) == EOF && err == NULL)
6394 err = got_error_from_errno("fclose");
6396 return (void *)err;
6399 static struct got_object_id *
6400 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6401 int first_displayed_line, int selected_line)
6403 struct tog_blame_line *line;
6405 if (nlines <= 0)
6406 return NULL;
6408 line = &lines[first_displayed_line - 1 + selected_line - 1];
6409 if (!line->annotated)
6410 return NULL;
6412 return line->id;
6415 static struct got_object_id *
6416 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6417 int lineno)
6419 struct tog_blame_line *line;
6421 if (nlines <= 0 || lineno >= nlines)
6422 return NULL;
6424 line = &lines[lineno - 1];
6425 if (!line->annotated)
6426 return NULL;
6428 return line->id;
6431 static const struct got_error *
6432 stop_blame(struct tog_blame *blame)
6434 const struct got_error *err = NULL;
6435 int i;
6437 if (blame->thread) {
6438 int errcode;
6439 errcode = pthread_mutex_unlock(&tog_mutex);
6440 if (errcode)
6441 return got_error_set_errno(errcode,
6442 "pthread_mutex_unlock");
6443 errcode = pthread_join(blame->thread, (void **)&err);
6444 if (errcode)
6445 return got_error_set_errno(errcode, "pthread_join");
6446 errcode = pthread_mutex_lock(&tog_mutex);
6447 if (errcode)
6448 return got_error_set_errno(errcode,
6449 "pthread_mutex_lock");
6450 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6451 err = NULL;
6452 blame->thread = 0; //NULL;
6454 if (blame->thread_args.repo) {
6455 const struct got_error *close_err;
6456 close_err = got_repo_close(blame->thread_args.repo);
6457 if (err == NULL)
6458 err = close_err;
6459 blame->thread_args.repo = NULL;
6461 if (blame->f) {
6462 if (fclose(blame->f) == EOF && err == NULL)
6463 err = got_error_from_errno("fclose");
6464 blame->f = NULL;
6466 if (blame->lines) {
6467 for (i = 0; i < blame->nlines; i++)
6468 free(blame->lines[i].id);
6469 free(blame->lines);
6470 blame->lines = NULL;
6472 free(blame->cb_args.commit_id);
6473 blame->cb_args.commit_id = NULL;
6474 if (blame->pack_fds) {
6475 const struct got_error *pack_err =
6476 got_repo_pack_fds_close(blame->pack_fds);
6477 if (err == NULL)
6478 err = pack_err;
6479 blame->pack_fds = NULL;
6481 return err;
6484 static const struct got_error *
6485 cancel_blame_view(void *arg)
6487 const struct got_error *err = NULL;
6488 int *done = arg;
6489 int errcode;
6491 errcode = pthread_mutex_lock(&tog_mutex);
6492 if (errcode)
6493 return got_error_set_errno(errcode,
6494 "pthread_mutex_unlock");
6496 if (*done)
6497 err = got_error(GOT_ERR_CANCELLED);
6499 errcode = pthread_mutex_unlock(&tog_mutex);
6500 if (errcode)
6501 return got_error_set_errno(errcode,
6502 "pthread_mutex_lock");
6504 return err;
6507 static const struct got_error *
6508 run_blame(struct tog_view *view)
6510 struct tog_blame_view_state *s = &view->state.blame;
6511 struct tog_blame *blame = &s->blame;
6512 const struct got_error *err = NULL;
6513 struct got_commit_object *commit = NULL;
6514 struct got_blob_object *blob = NULL;
6515 struct got_repository *thread_repo = NULL;
6516 struct got_object_id *obj_id = NULL;
6517 int obj_type, fd = -1;
6518 int *pack_fds = NULL;
6520 err = got_object_open_as_commit(&commit, s->repo,
6521 &s->blamed_commit->id);
6522 if (err)
6523 return err;
6525 fd = got_opentempfd();
6526 if (fd == -1) {
6527 err = got_error_from_errno("got_opentempfd");
6528 goto done;
6531 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6532 if (err)
6533 goto done;
6535 err = got_object_get_type(&obj_type, s->repo, obj_id);
6536 if (err)
6537 goto done;
6539 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6540 err = got_error(GOT_ERR_OBJ_TYPE);
6541 goto done;
6544 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6545 if (err)
6546 goto done;
6547 blame->f = got_opentemp();
6548 if (blame->f == NULL) {
6549 err = got_error_from_errno("got_opentemp");
6550 goto done;
6552 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6553 &blame->line_offsets, blame->f, blob);
6554 if (err)
6555 goto done;
6556 if (blame->nlines == 0) {
6557 s->blame_complete = 1;
6558 goto done;
6561 /* Don't include \n at EOF in the blame line count. */
6562 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6563 blame->nlines--;
6565 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6566 if (blame->lines == NULL) {
6567 err = got_error_from_errno("calloc");
6568 goto done;
6571 err = got_repo_pack_fds_open(&pack_fds);
6572 if (err)
6573 goto done;
6574 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6575 pack_fds);
6576 if (err)
6577 goto done;
6579 blame->pack_fds = pack_fds;
6580 blame->cb_args.view = view;
6581 blame->cb_args.lines = blame->lines;
6582 blame->cb_args.nlines = blame->nlines;
6583 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6584 if (blame->cb_args.commit_id == NULL) {
6585 err = got_error_from_errno("got_object_id_dup");
6586 goto done;
6588 blame->cb_args.quit = &s->done;
6590 blame->thread_args.path = s->path;
6591 blame->thread_args.repo = thread_repo;
6592 blame->thread_args.cb_args = &blame->cb_args;
6593 blame->thread_args.complete = &s->blame_complete;
6594 blame->thread_args.cancel_cb = cancel_blame_view;
6595 blame->thread_args.cancel_arg = &s->done;
6596 s->blame_complete = 0;
6598 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6599 s->first_displayed_line = 1;
6600 s->last_displayed_line = view->nlines;
6601 s->selected_line = 1;
6603 s->matched_line = 0;
6605 done:
6606 if (commit)
6607 got_object_commit_close(commit);
6608 if (fd != -1 && close(fd) == -1 && err == NULL)
6609 err = got_error_from_errno("close");
6610 if (blob)
6611 got_object_blob_close(blob);
6612 free(obj_id);
6613 if (err)
6614 stop_blame(blame);
6615 return err;
6618 static const struct got_error *
6619 open_blame_view(struct tog_view *view, char *path,
6620 struct got_object_id *commit_id, struct got_repository *repo)
6622 const struct got_error *err = NULL;
6623 struct tog_blame_view_state *s = &view->state.blame;
6625 STAILQ_INIT(&s->blamed_commits);
6627 s->path = strdup(path);
6628 if (s->path == NULL)
6629 return got_error_from_errno("strdup");
6631 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6632 if (err) {
6633 free(s->path);
6634 return err;
6637 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6638 s->first_displayed_line = 1;
6639 s->last_displayed_line = view->nlines;
6640 s->selected_line = 1;
6641 s->blame_complete = 0;
6642 s->repo = repo;
6643 s->commit_id = commit_id;
6644 memset(&s->blame, 0, sizeof(s->blame));
6646 STAILQ_INIT(&s->colors);
6647 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6648 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6649 get_color_value("TOG_COLOR_COMMIT"));
6650 if (err)
6651 return err;
6654 view->show = show_blame_view;
6655 view->input = input_blame_view;
6656 view->reset = reset_blame_view;
6657 view->close = close_blame_view;
6658 view->search_start = search_start_blame_view;
6659 view->search_setup = search_setup_blame_view;
6660 view->search_next = search_next_view_match;
6662 if (using_mock_io) {
6663 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6664 int rc;
6666 rc = pthread_cond_init(&bta->blame_complete, NULL);
6667 if (rc)
6668 return got_error_set_errno(rc, "pthread_cond_init");
6671 return run_blame(view);
6674 static const struct got_error *
6675 close_blame_view(struct tog_view *view)
6677 const struct got_error *err = NULL;
6678 struct tog_blame_view_state *s = &view->state.blame;
6680 if (s->blame.thread)
6681 err = stop_blame(&s->blame);
6683 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6684 struct got_object_qid *blamed_commit;
6685 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6686 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6687 got_object_qid_free(blamed_commit);
6690 if (using_mock_io) {
6691 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6692 int rc;
6694 rc = pthread_cond_destroy(&bta->blame_complete);
6695 if (rc && err == NULL)
6696 err = got_error_set_errno(rc, "pthread_cond_destroy");
6699 free(s->path);
6700 free_colors(&s->colors);
6701 return err;
6704 static const struct got_error *
6705 search_start_blame_view(struct tog_view *view)
6707 struct tog_blame_view_state *s = &view->state.blame;
6709 s->matched_line = 0;
6710 return NULL;
6713 static void
6714 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6715 size_t *nlines, int **first, int **last, int **match, int **selected)
6717 struct tog_blame_view_state *s = &view->state.blame;
6719 *f = s->blame.f;
6720 *nlines = s->blame.nlines;
6721 *line_offsets = s->blame.line_offsets;
6722 *match = &s->matched_line;
6723 *first = &s->first_displayed_line;
6724 *last = &s->last_displayed_line;
6725 *selected = &s->selected_line;
6728 static const struct got_error *
6729 show_blame_view(struct tog_view *view)
6731 const struct got_error *err = NULL;
6732 struct tog_blame_view_state *s = &view->state.blame;
6733 int errcode;
6735 if (s->blame.thread == 0 && !s->blame_complete) {
6736 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6737 &s->blame.thread_args);
6738 if (errcode)
6739 return got_error_set_errno(errcode, "pthread_create");
6741 if (!using_mock_io)
6742 halfdelay(1); /* fast refresh while annotating */
6745 if (s->blame_complete && !using_mock_io)
6746 halfdelay(10); /* disable fast refresh */
6748 err = draw_blame(view);
6750 view_border(view);
6751 return err;
6754 static const struct got_error *
6755 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6756 struct got_repository *repo, struct got_object_id *id)
6758 struct tog_view *log_view;
6759 const struct got_error *err = NULL;
6761 *new_view = NULL;
6763 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6764 if (log_view == NULL)
6765 return got_error_from_errno("view_open");
6767 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6768 if (err)
6769 view_close(log_view);
6770 else
6771 *new_view = log_view;
6773 return err;
6776 static const struct got_error *
6777 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6779 const struct got_error *err = NULL, *thread_err = NULL;
6780 struct tog_view *diff_view;
6781 struct tog_blame_view_state *s = &view->state.blame;
6782 int eos, nscroll, begin_y = 0, begin_x = 0;
6784 eos = nscroll = view->nlines - 2;
6785 if (view_is_hsplit_top(view))
6786 --eos; /* border */
6788 switch (ch) {
6789 case '0':
6790 case '$':
6791 case KEY_RIGHT:
6792 case 'l':
6793 case KEY_LEFT:
6794 case 'h':
6795 horizontal_scroll_input(view, ch);
6796 break;
6797 case 'q':
6798 s->done = 1;
6799 break;
6800 case 'g':
6801 case KEY_HOME:
6802 s->selected_line = 1;
6803 s->first_displayed_line = 1;
6804 view->count = 0;
6805 break;
6806 case 'G':
6807 case KEY_END:
6808 if (s->blame.nlines < eos) {
6809 s->selected_line = s->blame.nlines;
6810 s->first_displayed_line = 1;
6811 } else {
6812 s->selected_line = eos;
6813 s->first_displayed_line = s->blame.nlines - (eos - 1);
6815 view->count = 0;
6816 break;
6817 case 'k':
6818 case KEY_UP:
6819 case CTRL('p'):
6820 if (s->selected_line > 1)
6821 s->selected_line--;
6822 else if (s->selected_line == 1 &&
6823 s->first_displayed_line > 1)
6824 s->first_displayed_line--;
6825 else
6826 view->count = 0;
6827 break;
6828 case CTRL('u'):
6829 case 'u':
6830 nscroll /= 2;
6831 /* FALL THROUGH */
6832 case KEY_PPAGE:
6833 case CTRL('b'):
6834 case 'b':
6835 if (s->first_displayed_line == 1) {
6836 if (view->count > 1)
6837 nscroll += nscroll;
6838 s->selected_line = MAX(1, s->selected_line - nscroll);
6839 view->count = 0;
6840 break;
6842 if (s->first_displayed_line > nscroll)
6843 s->first_displayed_line -= nscroll;
6844 else
6845 s->first_displayed_line = 1;
6846 break;
6847 case 'j':
6848 case KEY_DOWN:
6849 case CTRL('n'):
6850 if (s->selected_line < eos && s->first_displayed_line +
6851 s->selected_line <= s->blame.nlines)
6852 s->selected_line++;
6853 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6854 s->first_displayed_line++;
6855 else
6856 view->count = 0;
6857 break;
6858 case 'c':
6859 case 'p': {
6860 struct got_object_id *id = NULL;
6862 view->count = 0;
6863 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6864 s->first_displayed_line, s->selected_line);
6865 if (id == NULL)
6866 break;
6867 if (ch == 'p') {
6868 struct got_commit_object *commit, *pcommit;
6869 struct got_object_qid *pid;
6870 struct got_object_id *blob_id = NULL;
6871 int obj_type;
6872 err = got_object_open_as_commit(&commit,
6873 s->repo, id);
6874 if (err)
6875 break;
6876 pid = STAILQ_FIRST(
6877 got_object_commit_get_parent_ids(commit));
6878 if (pid == NULL) {
6879 got_object_commit_close(commit);
6880 break;
6882 /* Check if path history ends here. */
6883 err = got_object_open_as_commit(&pcommit,
6884 s->repo, &pid->id);
6885 if (err)
6886 break;
6887 err = got_object_id_by_path(&blob_id, s->repo,
6888 pcommit, s->path);
6889 got_object_commit_close(pcommit);
6890 if (err) {
6891 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6892 err = NULL;
6893 got_object_commit_close(commit);
6894 break;
6896 err = got_object_get_type(&obj_type, s->repo,
6897 blob_id);
6898 free(blob_id);
6899 /* Can't blame non-blob type objects. */
6900 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6901 got_object_commit_close(commit);
6902 break;
6904 err = got_object_qid_alloc(&s->blamed_commit,
6905 &pid->id);
6906 got_object_commit_close(commit);
6907 } else {
6908 if (got_object_id_cmp(id,
6909 &s->blamed_commit->id) == 0)
6910 break;
6911 err = got_object_qid_alloc(&s->blamed_commit,
6912 id);
6914 if (err)
6915 break;
6916 s->done = 1;
6917 thread_err = stop_blame(&s->blame);
6918 s->done = 0;
6919 if (thread_err)
6920 break;
6921 STAILQ_INSERT_HEAD(&s->blamed_commits,
6922 s->blamed_commit, entry);
6923 err = run_blame(view);
6924 if (err)
6925 break;
6926 break;
6928 case 'C': {
6929 struct got_object_qid *first;
6931 view->count = 0;
6932 first = STAILQ_FIRST(&s->blamed_commits);
6933 if (!got_object_id_cmp(&first->id, s->commit_id))
6934 break;
6935 s->done = 1;
6936 thread_err = stop_blame(&s->blame);
6937 s->done = 0;
6938 if (thread_err)
6939 break;
6940 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6941 got_object_qid_free(s->blamed_commit);
6942 s->blamed_commit =
6943 STAILQ_FIRST(&s->blamed_commits);
6944 err = run_blame(view);
6945 if (err)
6946 break;
6947 break;
6949 case 'L':
6950 view->count = 0;
6951 s->id_to_log = get_selected_commit_id(s->blame.lines,
6952 s->blame.nlines, s->first_displayed_line, s->selected_line);
6953 if (s->id_to_log)
6954 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6955 break;
6956 case KEY_ENTER:
6957 case '\r': {
6958 struct got_object_id *id = NULL;
6959 struct got_object_qid *pid;
6960 struct got_commit_object *commit = NULL;
6962 view->count = 0;
6963 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6964 s->first_displayed_line, s->selected_line);
6965 if (id == NULL)
6966 break;
6967 err = got_object_open_as_commit(&commit, s->repo, id);
6968 if (err)
6969 break;
6970 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6971 if (*new_view) {
6972 /* traversed from diff view, release diff resources */
6973 err = close_diff_view(*new_view);
6974 if (err)
6975 break;
6976 diff_view = *new_view;
6977 } else {
6978 if (view_is_parent_view(view))
6979 view_get_split(view, &begin_y, &begin_x);
6981 diff_view = view_open(0, 0, begin_y, begin_x,
6982 TOG_VIEW_DIFF);
6983 if (diff_view == NULL) {
6984 got_object_commit_close(commit);
6985 err = got_error_from_errno("view_open");
6986 break;
6989 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6990 id, NULL, NULL, 3, 0, 0, view, s->repo);
6991 got_object_commit_close(commit);
6992 if (err)
6993 break;
6994 s->last_diffed_line = s->first_displayed_line - 1 +
6995 s->selected_line;
6996 if (*new_view)
6997 break; /* still open from active diff view */
6998 if (view_is_parent_view(view) &&
6999 view->mode == TOG_VIEW_SPLIT_HRZN) {
7000 err = view_init_hsplit(view, begin_y);
7001 if (err)
7002 break;
7005 view->focussed = 0;
7006 diff_view->focussed = 1;
7007 diff_view->mode = view->mode;
7008 diff_view->nlines = view->lines - begin_y;
7009 if (view_is_parent_view(view)) {
7010 view_transfer_size(diff_view, view);
7011 err = view_close_child(view);
7012 if (err)
7013 break;
7014 err = view_set_child(view, diff_view);
7015 if (err)
7016 break;
7017 view->focus_child = 1;
7018 } else
7019 *new_view = diff_view;
7020 if (err)
7021 break;
7022 break;
7024 case CTRL('d'):
7025 case 'd':
7026 nscroll /= 2;
7027 /* FALL THROUGH */
7028 case KEY_NPAGE:
7029 case CTRL('f'):
7030 case 'f':
7031 case ' ':
7032 if (s->last_displayed_line >= s->blame.nlines &&
7033 s->selected_line >= MIN(s->blame.nlines,
7034 view->nlines - 2)) {
7035 view->count = 0;
7036 break;
7038 if (s->last_displayed_line >= s->blame.nlines &&
7039 s->selected_line < view->nlines - 2) {
7040 s->selected_line +=
7041 MIN(nscroll, s->last_displayed_line -
7042 s->first_displayed_line - s->selected_line + 1);
7044 if (s->last_displayed_line + nscroll <= s->blame.nlines)
7045 s->first_displayed_line += nscroll;
7046 else
7047 s->first_displayed_line =
7048 s->blame.nlines - (view->nlines - 3);
7049 break;
7050 case KEY_RESIZE:
7051 if (s->selected_line > view->nlines - 2) {
7052 s->selected_line = MIN(s->blame.nlines,
7053 view->nlines - 2);
7055 break;
7056 default:
7057 view->count = 0;
7058 break;
7060 return thread_err ? thread_err : err;
7063 static const struct got_error *
7064 reset_blame_view(struct tog_view *view)
7066 const struct got_error *err;
7067 struct tog_blame_view_state *s = &view->state.blame;
7069 view->count = 0;
7070 s->done = 1;
7071 err = stop_blame(&s->blame);
7072 s->done = 0;
7073 if (err)
7074 return err;
7075 return run_blame(view);
7078 static const struct got_error *
7079 cmd_blame(int argc, char *argv[])
7081 const struct got_error *error;
7082 struct got_repository *repo = NULL;
7083 struct got_worktree *worktree = NULL;
7084 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7085 char *link_target = NULL;
7086 struct got_object_id *commit_id = NULL;
7087 struct got_commit_object *commit = NULL;
7088 char *keyword_idstr = NULL, *commit_id_str = NULL;
7089 int ch;
7090 struct tog_view *view = NULL;
7091 int *pack_fds = NULL;
7093 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7094 switch (ch) {
7095 case 'c':
7096 commit_id_str = optarg;
7097 break;
7098 case 'r':
7099 repo_path = realpath(optarg, NULL);
7100 if (repo_path == NULL)
7101 return got_error_from_errno2("realpath",
7102 optarg);
7103 break;
7104 default:
7105 usage_blame();
7106 /* NOTREACHED */
7110 argc -= optind;
7111 argv += optind;
7113 if (argc != 1)
7114 usage_blame();
7116 error = got_repo_pack_fds_open(&pack_fds);
7117 if (error != NULL)
7118 goto done;
7120 if (repo_path == NULL) {
7121 cwd = getcwd(NULL, 0);
7122 if (cwd == NULL)
7123 return got_error_from_errno("getcwd");
7124 error = got_worktree_open(&worktree, cwd, NULL);
7125 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7126 goto done;
7127 if (worktree)
7128 repo_path =
7129 strdup(got_worktree_get_repo_path(worktree));
7130 else
7131 repo_path = strdup(cwd);
7132 if (repo_path == NULL) {
7133 error = got_error_from_errno("strdup");
7134 goto done;
7138 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7139 if (error != NULL)
7140 goto done;
7142 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7143 worktree);
7144 if (error)
7145 goto done;
7147 init_curses();
7149 error = apply_unveil(got_repo_get_path(repo), NULL);
7150 if (error)
7151 goto done;
7153 error = tog_load_refs(repo, 0);
7154 if (error)
7155 goto done;
7157 if (commit_id_str == NULL) {
7158 struct got_reference *head_ref;
7159 error = got_ref_open(&head_ref, repo, worktree ?
7160 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7161 if (error != NULL)
7162 goto done;
7163 error = got_ref_resolve(&commit_id, repo, head_ref);
7164 got_ref_close(head_ref);
7165 } else {
7166 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
7167 repo, worktree);
7168 if (error != NULL)
7169 goto done;
7170 if (keyword_idstr != NULL)
7171 commit_id_str = keyword_idstr;
7173 error = got_repo_match_object_id(&commit_id, NULL,
7174 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7176 if (error != NULL)
7177 goto done;
7179 error = got_object_open_as_commit(&commit, repo, commit_id);
7180 if (error)
7181 goto done;
7183 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7184 commit, repo);
7185 if (error)
7186 goto done;
7188 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7189 if (view == NULL) {
7190 error = got_error_from_errno("view_open");
7191 goto done;
7193 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7194 commit_id, repo);
7195 if (error != NULL) {
7196 if (view->close == NULL)
7197 close_blame_view(view);
7198 view_close(view);
7199 goto done;
7201 if (worktree) {
7202 /* Release work tree lock. */
7203 got_worktree_close(worktree);
7204 worktree = NULL;
7206 error = view_loop(view);
7207 done:
7208 free(repo_path);
7209 free(in_repo_path);
7210 free(link_target);
7211 free(cwd);
7212 free(commit_id);
7213 free(keyword_idstr);
7214 if (commit)
7215 got_object_commit_close(commit);
7216 if (worktree)
7217 got_worktree_close(worktree);
7218 if (repo) {
7219 const struct got_error *close_err = got_repo_close(repo);
7220 if (error == NULL)
7221 error = close_err;
7223 if (pack_fds) {
7224 const struct got_error *pack_err =
7225 got_repo_pack_fds_close(pack_fds);
7226 if (error == NULL)
7227 error = pack_err;
7229 tog_free_refs();
7230 return error;
7233 static const struct got_error *
7234 draw_tree_entries(struct tog_view *view, const char *parent_path)
7236 struct tog_tree_view_state *s = &view->state.tree;
7237 const struct got_error *err = NULL;
7238 struct got_tree_entry *te;
7239 wchar_t *wline;
7240 char *index = NULL;
7241 struct tog_color *tc;
7242 int width, n, nentries, scrollx, i = 1;
7243 int limit = view->nlines;
7245 s->ndisplayed = 0;
7246 if (view_is_hsplit_top(view))
7247 --limit; /* border */
7249 werase(view->window);
7251 if (limit == 0)
7252 return NULL;
7254 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7255 0, 0);
7256 if (err)
7257 return err;
7258 if (view_needs_focus_indication(view))
7259 wstandout(view->window);
7260 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7261 if (tc)
7262 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7263 waddwstr(view->window, wline);
7264 free(wline);
7265 wline = NULL;
7266 while (width++ < view->ncols)
7267 waddch(view->window, ' ');
7268 if (tc)
7269 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7270 if (view_needs_focus_indication(view))
7271 wstandend(view->window);
7272 if (--limit <= 0)
7273 return NULL;
7275 i += s->selected;
7276 if (s->first_displayed_entry) {
7277 i += got_tree_entry_get_index(s->first_displayed_entry);
7278 if (s->tree != s->root)
7279 ++i; /* account for ".." entry */
7281 nentries = got_object_tree_get_nentries(s->tree);
7282 if (asprintf(&index, "[%d/%d] %s",
7283 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7284 return got_error_from_errno("asprintf");
7285 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7286 free(index);
7287 if (err)
7288 return err;
7289 waddwstr(view->window, wline);
7290 free(wline);
7291 wline = NULL;
7292 if (width < view->ncols - 1)
7293 waddch(view->window, '\n');
7294 if (--limit <= 0)
7295 return NULL;
7296 waddch(view->window, '\n');
7297 if (--limit <= 0)
7298 return NULL;
7300 if (s->first_displayed_entry == NULL) {
7301 te = got_object_tree_get_first_entry(s->tree);
7302 if (s->selected == 0) {
7303 if (view->focussed)
7304 wstandout(view->window);
7305 s->selected_entry = NULL;
7307 waddstr(view->window, " ..\n"); /* parent directory */
7308 if (s->selected == 0 && view->focussed)
7309 wstandend(view->window);
7310 s->ndisplayed++;
7311 if (--limit <= 0)
7312 return NULL;
7313 n = 1;
7314 } else {
7315 n = 0;
7316 te = s->first_displayed_entry;
7319 view->maxx = 0;
7320 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7321 char *line = NULL, *id_str = NULL, *link_target = NULL;
7322 const char *modestr = "";
7323 mode_t mode;
7325 te = got_object_tree_get_entry(s->tree, i);
7326 mode = got_tree_entry_get_mode(te);
7328 if (s->show_ids) {
7329 err = got_object_id_str(&id_str,
7330 got_tree_entry_get_id(te));
7331 if (err)
7332 return got_error_from_errno(
7333 "got_object_id_str");
7335 if (got_object_tree_entry_is_submodule(te))
7336 modestr = "$";
7337 else if (S_ISLNK(mode)) {
7338 int i;
7340 err = got_tree_entry_get_symlink_target(&link_target,
7341 te, s->repo);
7342 if (err) {
7343 free(id_str);
7344 return err;
7346 for (i = 0; link_target[i] != '\0'; i++) {
7347 if (!isprint((unsigned char)link_target[i]))
7348 link_target[i] = '?';
7350 modestr = "@";
7352 else if (S_ISDIR(mode))
7353 modestr = "/";
7354 else if (mode & S_IXUSR)
7355 modestr = "*";
7356 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7357 got_tree_entry_get_name(te), modestr,
7358 link_target ? " -> ": "",
7359 link_target ? link_target : "") == -1) {
7360 free(id_str);
7361 free(link_target);
7362 return got_error_from_errno("asprintf");
7364 free(id_str);
7365 free(link_target);
7367 /* use full line width to determine view->maxx */
7368 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7369 if (err) {
7370 free(line);
7371 break;
7373 view->maxx = MAX(view->maxx, width);
7374 free(wline);
7375 wline = NULL;
7377 err = format_line(&wline, &width, &scrollx, line, view->x,
7378 view->ncols, 0, 0);
7379 if (err) {
7380 free(line);
7381 break;
7383 if (n == s->selected) {
7384 if (view->focussed)
7385 wstandout(view->window);
7386 s->selected_entry = te;
7388 tc = match_color(&s->colors, line);
7389 if (tc)
7390 wattr_on(view->window,
7391 COLOR_PAIR(tc->colorpair), NULL);
7392 waddwstr(view->window, &wline[scrollx]);
7393 if (tc)
7394 wattr_off(view->window,
7395 COLOR_PAIR(tc->colorpair), NULL);
7396 if (width < view->ncols)
7397 waddch(view->window, '\n');
7398 if (n == s->selected && view->focussed)
7399 wstandend(view->window);
7400 free(line);
7401 free(wline);
7402 wline = NULL;
7403 n++;
7404 s->ndisplayed++;
7405 s->last_displayed_entry = te;
7406 if (--limit <= 0)
7407 break;
7410 return err;
7413 static void
7414 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7416 struct got_tree_entry *te;
7417 int isroot = s->tree == s->root;
7418 int i = 0;
7420 if (s->first_displayed_entry == NULL)
7421 return;
7423 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7424 while (i++ < maxscroll) {
7425 if (te == NULL) {
7426 if (!isroot)
7427 s->first_displayed_entry = NULL;
7428 break;
7430 s->first_displayed_entry = te;
7431 te = got_tree_entry_get_prev(s->tree, te);
7435 static const struct got_error *
7436 tree_scroll_down(struct tog_view *view, int maxscroll)
7438 struct tog_tree_view_state *s = &view->state.tree;
7439 struct got_tree_entry *next, *last;
7440 int n = 0;
7442 if (s->first_displayed_entry)
7443 next = got_tree_entry_get_next(s->tree,
7444 s->first_displayed_entry);
7445 else
7446 next = got_object_tree_get_first_entry(s->tree);
7448 last = s->last_displayed_entry;
7449 while (next && n++ < maxscroll) {
7450 if (last) {
7451 s->last_displayed_entry = last;
7452 last = got_tree_entry_get_next(s->tree, last);
7454 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7455 s->first_displayed_entry = next;
7456 next = got_tree_entry_get_next(s->tree, next);
7460 return NULL;
7463 static const struct got_error *
7464 tree_entry_path(char **path, struct tog_parent_trees *parents,
7465 struct got_tree_entry *te)
7467 const struct got_error *err = NULL;
7468 struct tog_parent_tree *pt;
7469 size_t len = 2; /* for leading slash and NUL */
7471 TAILQ_FOREACH(pt, parents, entry)
7472 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7473 + 1 /* slash */;
7474 if (te)
7475 len += strlen(got_tree_entry_get_name(te));
7477 *path = calloc(1, len);
7478 if (path == NULL)
7479 return got_error_from_errno("calloc");
7481 (*path)[0] = '/';
7482 pt = TAILQ_LAST(parents, tog_parent_trees);
7483 while (pt) {
7484 const char *name = got_tree_entry_get_name(pt->selected_entry);
7485 if (strlcat(*path, name, len) >= len) {
7486 err = got_error(GOT_ERR_NO_SPACE);
7487 goto done;
7489 if (strlcat(*path, "/", len) >= len) {
7490 err = got_error(GOT_ERR_NO_SPACE);
7491 goto done;
7493 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7495 if (te) {
7496 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7497 err = got_error(GOT_ERR_NO_SPACE);
7498 goto done;
7501 done:
7502 if (err) {
7503 free(*path);
7504 *path = NULL;
7506 return err;
7509 static const struct got_error *
7510 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7511 struct got_tree_entry *te, struct tog_parent_trees *parents,
7512 struct got_object_id *commit_id, struct got_repository *repo)
7514 const struct got_error *err = NULL;
7515 char *path;
7516 struct tog_view *blame_view;
7518 *new_view = NULL;
7520 err = tree_entry_path(&path, parents, te);
7521 if (err)
7522 return err;
7524 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7525 if (blame_view == NULL) {
7526 err = got_error_from_errno("view_open");
7527 goto done;
7530 err = open_blame_view(blame_view, path, commit_id, repo);
7531 if (err) {
7532 if (err->code == GOT_ERR_CANCELLED)
7533 err = NULL;
7534 view_close(blame_view);
7535 } else
7536 *new_view = blame_view;
7537 done:
7538 free(path);
7539 return err;
7542 static const struct got_error *
7543 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7544 struct tog_tree_view_state *s)
7546 struct tog_view *log_view;
7547 const struct got_error *err = NULL;
7548 char *path;
7550 *new_view = NULL;
7552 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7553 if (log_view == NULL)
7554 return got_error_from_errno("view_open");
7556 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7557 if (err)
7558 return err;
7560 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7561 path, 0);
7562 if (err)
7563 view_close(log_view);
7564 else
7565 *new_view = log_view;
7566 free(path);
7567 return err;
7570 static const struct got_error *
7571 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7572 const char *head_ref_name, struct got_repository *repo)
7574 const struct got_error *err = NULL;
7575 char *commit_id_str = NULL;
7576 struct tog_tree_view_state *s = &view->state.tree;
7577 struct got_commit_object *commit = NULL;
7579 TAILQ_INIT(&s->parents);
7580 STAILQ_INIT(&s->colors);
7582 s->commit_id = got_object_id_dup(commit_id);
7583 if (s->commit_id == NULL) {
7584 err = got_error_from_errno("got_object_id_dup");
7585 goto done;
7588 err = got_object_open_as_commit(&commit, repo, commit_id);
7589 if (err)
7590 goto done;
7593 * The root is opened here and will be closed when the view is closed.
7594 * Any visited subtrees and their path-wise parents are opened and
7595 * closed on demand.
7597 err = got_object_open_as_tree(&s->root, repo,
7598 got_object_commit_get_tree_id(commit));
7599 if (err)
7600 goto done;
7601 s->tree = s->root;
7603 err = got_object_id_str(&commit_id_str, commit_id);
7604 if (err != NULL)
7605 goto done;
7607 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7608 err = got_error_from_errno("asprintf");
7609 goto done;
7612 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7613 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7614 if (head_ref_name) {
7615 s->head_ref_name = strdup(head_ref_name);
7616 if (s->head_ref_name == NULL) {
7617 err = got_error_from_errno("strdup");
7618 goto done;
7621 s->repo = repo;
7623 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7624 err = add_color(&s->colors, "\\$$",
7625 TOG_COLOR_TREE_SUBMODULE,
7626 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7627 if (err)
7628 goto done;
7629 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7630 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7631 if (err)
7632 goto done;
7633 err = add_color(&s->colors, "/$",
7634 TOG_COLOR_TREE_DIRECTORY,
7635 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7636 if (err)
7637 goto done;
7639 err = add_color(&s->colors, "\\*$",
7640 TOG_COLOR_TREE_EXECUTABLE,
7641 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7642 if (err)
7643 goto done;
7645 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7646 get_color_value("TOG_COLOR_COMMIT"));
7647 if (err)
7648 goto done;
7651 view->show = show_tree_view;
7652 view->input = input_tree_view;
7653 view->close = close_tree_view;
7654 view->search_start = search_start_tree_view;
7655 view->search_next = search_next_tree_view;
7656 done:
7657 free(commit_id_str);
7658 if (commit)
7659 got_object_commit_close(commit);
7660 if (err) {
7661 if (view->close == NULL)
7662 close_tree_view(view);
7663 view_close(view);
7665 return err;
7668 static const struct got_error *
7669 close_tree_view(struct tog_view *view)
7671 struct tog_tree_view_state *s = &view->state.tree;
7673 free_colors(&s->colors);
7674 free(s->tree_label);
7675 s->tree_label = NULL;
7676 free(s->commit_id);
7677 s->commit_id = NULL;
7678 free(s->head_ref_name);
7679 s->head_ref_name = NULL;
7680 while (!TAILQ_EMPTY(&s->parents)) {
7681 struct tog_parent_tree *parent;
7682 parent = TAILQ_FIRST(&s->parents);
7683 TAILQ_REMOVE(&s->parents, parent, entry);
7684 if (parent->tree != s->root)
7685 got_object_tree_close(parent->tree);
7686 free(parent);
7689 if (s->tree != NULL && s->tree != s->root)
7690 got_object_tree_close(s->tree);
7691 if (s->root)
7692 got_object_tree_close(s->root);
7693 return NULL;
7696 static const struct got_error *
7697 search_start_tree_view(struct tog_view *view)
7699 struct tog_tree_view_state *s = &view->state.tree;
7701 s->matched_entry = NULL;
7702 return NULL;
7705 static int
7706 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7708 regmatch_t regmatch;
7710 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7711 0) == 0;
7714 static const struct got_error *
7715 search_next_tree_view(struct tog_view *view)
7717 struct tog_tree_view_state *s = &view->state.tree;
7718 struct got_tree_entry *te = NULL;
7720 if (!view->searching) {
7721 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7722 return NULL;
7725 if (s->matched_entry) {
7726 if (view->searching == TOG_SEARCH_FORWARD) {
7727 if (s->selected_entry)
7728 te = got_tree_entry_get_next(s->tree,
7729 s->selected_entry);
7730 else
7731 te = got_object_tree_get_first_entry(s->tree);
7732 } else {
7733 if (s->selected_entry == NULL)
7734 te = got_object_tree_get_last_entry(s->tree);
7735 else
7736 te = got_tree_entry_get_prev(s->tree,
7737 s->selected_entry);
7739 } else {
7740 if (s->selected_entry)
7741 te = s->selected_entry;
7742 else if (view->searching == TOG_SEARCH_FORWARD)
7743 te = got_object_tree_get_first_entry(s->tree);
7744 else
7745 te = got_object_tree_get_last_entry(s->tree);
7748 while (1) {
7749 if (te == NULL) {
7750 if (s->matched_entry == NULL) {
7751 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7752 return NULL;
7754 if (view->searching == TOG_SEARCH_FORWARD)
7755 te = got_object_tree_get_first_entry(s->tree);
7756 else
7757 te = got_object_tree_get_last_entry(s->tree);
7760 if (match_tree_entry(te, &view->regex)) {
7761 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7762 s->matched_entry = te;
7763 break;
7766 if (view->searching == TOG_SEARCH_FORWARD)
7767 te = got_tree_entry_get_next(s->tree, te);
7768 else
7769 te = got_tree_entry_get_prev(s->tree, te);
7772 if (s->matched_entry) {
7773 s->first_displayed_entry = s->matched_entry;
7774 s->selected = 0;
7777 return NULL;
7780 static const struct got_error *
7781 show_tree_view(struct tog_view *view)
7783 const struct got_error *err = NULL;
7784 struct tog_tree_view_state *s = &view->state.tree;
7785 char *parent_path;
7787 err = tree_entry_path(&parent_path, &s->parents, NULL);
7788 if (err)
7789 return err;
7791 err = draw_tree_entries(view, parent_path);
7792 free(parent_path);
7794 view_border(view);
7795 return err;
7798 static const struct got_error *
7799 tree_goto_line(struct tog_view *view, int nlines)
7801 const struct got_error *err = NULL;
7802 struct tog_tree_view_state *s = &view->state.tree;
7803 struct got_tree_entry **fte, **lte, **ste;
7804 int g, last, first = 1, i = 1;
7805 int root = s->tree == s->root;
7806 int off = root ? 1 : 2;
7808 g = view->gline;
7809 view->gline = 0;
7811 if (g == 0)
7812 g = 1;
7813 else if (g > got_object_tree_get_nentries(s->tree))
7814 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7816 fte = &s->first_displayed_entry;
7817 lte = &s->last_displayed_entry;
7818 ste = &s->selected_entry;
7820 if (*fte != NULL) {
7821 first = got_tree_entry_get_index(*fte);
7822 first += off; /* account for ".." */
7824 last = got_tree_entry_get_index(*lte);
7825 last += off;
7827 if (g >= first && g <= last && g - first < nlines) {
7828 s->selected = g - first;
7829 return NULL; /* gline is on the current page */
7832 if (*ste != NULL) {
7833 i = got_tree_entry_get_index(*ste);
7834 i += off;
7837 if (i < g) {
7838 err = tree_scroll_down(view, g - i);
7839 if (err)
7840 return err;
7841 if (got_tree_entry_get_index(*lte) >=
7842 got_object_tree_get_nentries(s->tree) - 1 &&
7843 first + s->selected < g &&
7844 s->selected < s->ndisplayed - 1) {
7845 first = got_tree_entry_get_index(*fte);
7846 first += off;
7847 s->selected = g - first;
7849 } else if (i > g)
7850 tree_scroll_up(s, i - g);
7852 if (g < nlines &&
7853 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7854 s->selected = g - 1;
7856 return NULL;
7859 static const struct got_error *
7860 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7862 const struct got_error *err = NULL;
7863 struct tog_tree_view_state *s = &view->state.tree;
7864 struct got_tree_entry *te;
7865 int n, nscroll = view->nlines - 3;
7867 if (view->gline)
7868 return tree_goto_line(view, nscroll);
7870 switch (ch) {
7871 case '0':
7872 case '$':
7873 case KEY_RIGHT:
7874 case 'l':
7875 case KEY_LEFT:
7876 case 'h':
7877 horizontal_scroll_input(view, ch);
7878 break;
7879 case 'i':
7880 s->show_ids = !s->show_ids;
7881 view->count = 0;
7882 break;
7883 case 'L':
7884 view->count = 0;
7885 if (!s->selected_entry)
7886 break;
7887 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7888 break;
7889 case 'R':
7890 view->count = 0;
7891 err = view_request_new(new_view, view, TOG_VIEW_REF);
7892 break;
7893 case 'g':
7894 case '=':
7895 case KEY_HOME:
7896 s->selected = 0;
7897 view->count = 0;
7898 if (s->tree == s->root)
7899 s->first_displayed_entry =
7900 got_object_tree_get_first_entry(s->tree);
7901 else
7902 s->first_displayed_entry = NULL;
7903 break;
7904 case 'G':
7905 case '*':
7906 case KEY_END: {
7907 int eos = view->nlines - 3;
7909 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7910 --eos; /* border */
7911 s->selected = 0;
7912 view->count = 0;
7913 te = got_object_tree_get_last_entry(s->tree);
7914 for (n = 0; n < eos; n++) {
7915 if (te == NULL) {
7916 if (s->tree != s->root) {
7917 s->first_displayed_entry = NULL;
7918 n++;
7920 break;
7922 s->first_displayed_entry = te;
7923 te = got_tree_entry_get_prev(s->tree, te);
7925 if (n > 0)
7926 s->selected = n - 1;
7927 break;
7929 case 'k':
7930 case KEY_UP:
7931 case CTRL('p'):
7932 if (s->selected > 0) {
7933 s->selected--;
7934 break;
7936 tree_scroll_up(s, 1);
7937 if (s->selected_entry == NULL ||
7938 (s->tree == s->root && s->selected_entry ==
7939 got_object_tree_get_first_entry(s->tree)))
7940 view->count = 0;
7941 break;
7942 case CTRL('u'):
7943 case 'u':
7944 nscroll /= 2;
7945 /* FALL THROUGH */
7946 case KEY_PPAGE:
7947 case CTRL('b'):
7948 case 'b':
7949 if (s->tree == s->root) {
7950 if (got_object_tree_get_first_entry(s->tree) ==
7951 s->first_displayed_entry)
7952 s->selected -= MIN(s->selected, nscroll);
7953 } else {
7954 if (s->first_displayed_entry == NULL)
7955 s->selected -= MIN(s->selected, nscroll);
7957 tree_scroll_up(s, MAX(0, nscroll));
7958 if (s->selected_entry == NULL ||
7959 (s->tree == s->root && s->selected_entry ==
7960 got_object_tree_get_first_entry(s->tree)))
7961 view->count = 0;
7962 break;
7963 case 'j':
7964 case KEY_DOWN:
7965 case CTRL('n'):
7966 if (s->selected < s->ndisplayed - 1) {
7967 s->selected++;
7968 break;
7970 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7971 == NULL) {
7972 /* can't scroll any further */
7973 view->count = 0;
7974 break;
7976 tree_scroll_down(view, 1);
7977 break;
7978 case CTRL('d'):
7979 case 'd':
7980 nscroll /= 2;
7981 /* FALL THROUGH */
7982 case KEY_NPAGE:
7983 case CTRL('f'):
7984 case 'f':
7985 case ' ':
7986 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7987 == NULL) {
7988 /* can't scroll any further; move cursor down */
7989 if (s->selected < s->ndisplayed - 1)
7990 s->selected += MIN(nscroll,
7991 s->ndisplayed - s->selected - 1);
7992 else
7993 view->count = 0;
7994 break;
7996 tree_scroll_down(view, nscroll);
7997 break;
7998 case KEY_ENTER:
7999 case '\r':
8000 case KEY_BACKSPACE:
8001 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
8002 struct tog_parent_tree *parent;
8003 /* user selected '..' */
8004 if (s->tree == s->root) {
8005 view->count = 0;
8006 break;
8008 parent = TAILQ_FIRST(&s->parents);
8009 TAILQ_REMOVE(&s->parents, parent,
8010 entry);
8011 got_object_tree_close(s->tree);
8012 s->tree = parent->tree;
8013 s->first_displayed_entry =
8014 parent->first_displayed_entry;
8015 s->selected_entry =
8016 parent->selected_entry;
8017 s->selected = parent->selected;
8018 if (s->selected > view->nlines - 3) {
8019 err = offset_selection_down(view);
8020 if (err)
8021 break;
8023 free(parent);
8024 } else if (S_ISDIR(got_tree_entry_get_mode(
8025 s->selected_entry))) {
8026 struct got_tree_object *subtree;
8027 view->count = 0;
8028 err = got_object_open_as_tree(&subtree, s->repo,
8029 got_tree_entry_get_id(s->selected_entry));
8030 if (err)
8031 break;
8032 err = tree_view_visit_subtree(s, subtree);
8033 if (err) {
8034 got_object_tree_close(subtree);
8035 break;
8037 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
8038 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
8039 break;
8040 case KEY_RESIZE:
8041 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
8042 s->selected = view->nlines - 4;
8043 view->count = 0;
8044 break;
8045 default:
8046 view->count = 0;
8047 break;
8050 return err;
8053 __dead static void
8054 usage_tree(void)
8056 endwin();
8057 fprintf(stderr,
8058 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
8059 getprogname());
8060 exit(1);
8063 static const struct got_error *
8064 cmd_tree(int argc, char *argv[])
8066 const struct got_error *error;
8067 struct got_repository *repo = NULL;
8068 struct got_worktree *worktree = NULL;
8069 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8070 struct got_object_id *commit_id = NULL;
8071 struct got_commit_object *commit = NULL;
8072 const char *commit_id_arg = NULL;
8073 char *keyword_idstr = NULL, *label = NULL;
8074 struct got_reference *ref = NULL;
8075 const char *head_ref_name = NULL;
8076 int ch;
8077 struct tog_view *view;
8078 int *pack_fds = NULL;
8080 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
8081 switch (ch) {
8082 case 'c':
8083 commit_id_arg = optarg;
8084 break;
8085 case 'r':
8086 repo_path = realpath(optarg, NULL);
8087 if (repo_path == NULL)
8088 return got_error_from_errno2("realpath",
8089 optarg);
8090 break;
8091 default:
8092 usage_tree();
8093 /* NOTREACHED */
8097 argc -= optind;
8098 argv += optind;
8100 if (argc > 1)
8101 usage_tree();
8103 error = got_repo_pack_fds_open(&pack_fds);
8104 if (error != NULL)
8105 goto done;
8107 if (repo_path == NULL) {
8108 cwd = getcwd(NULL, 0);
8109 if (cwd == NULL)
8110 return got_error_from_errno("getcwd");
8111 error = got_worktree_open(&worktree, cwd, NULL);
8112 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8113 goto done;
8114 if (worktree)
8115 repo_path =
8116 strdup(got_worktree_get_repo_path(worktree));
8117 else
8118 repo_path = strdup(cwd);
8119 if (repo_path == NULL) {
8120 error = got_error_from_errno("strdup");
8121 goto done;
8125 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8126 if (error != NULL)
8127 goto done;
8129 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8130 repo, worktree);
8131 if (error)
8132 goto done;
8134 init_curses();
8136 error = apply_unveil(got_repo_get_path(repo), NULL);
8137 if (error)
8138 goto done;
8140 error = tog_load_refs(repo, 0);
8141 if (error)
8142 goto done;
8144 if (commit_id_arg == NULL) {
8145 error = got_repo_match_object_id(&commit_id, &label,
8146 worktree ? got_worktree_get_head_ref_name(worktree) :
8147 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8148 if (error)
8149 goto done;
8150 head_ref_name = label;
8151 } else {
8152 error = got_keyword_to_idstr(&keyword_idstr, commit_id_arg,
8153 repo, worktree);
8154 if (error != NULL)
8155 goto done;
8156 if (keyword_idstr != NULL)
8157 commit_id_arg = keyword_idstr;
8159 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8160 if (error == NULL)
8161 head_ref_name = got_ref_get_name(ref);
8162 else if (error->code != GOT_ERR_NOT_REF)
8163 goto done;
8164 error = got_repo_match_object_id(&commit_id, NULL,
8165 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8166 if (error)
8167 goto done;
8170 error = got_object_open_as_commit(&commit, repo, commit_id);
8171 if (error)
8172 goto done;
8174 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8175 if (view == NULL) {
8176 error = got_error_from_errno("view_open");
8177 goto done;
8179 error = open_tree_view(view, commit_id, head_ref_name, repo);
8180 if (error)
8181 goto done;
8182 if (!got_path_is_root_dir(in_repo_path)) {
8183 error = tree_view_walk_path(&view->state.tree, commit,
8184 in_repo_path);
8185 if (error)
8186 goto done;
8189 if (worktree) {
8190 /* Release work tree lock. */
8191 got_worktree_close(worktree);
8192 worktree = NULL;
8194 error = view_loop(view);
8195 done:
8196 free(keyword_idstr);
8197 free(repo_path);
8198 free(cwd);
8199 free(commit_id);
8200 free(label);
8201 if (ref)
8202 got_ref_close(ref);
8203 if (repo) {
8204 const struct got_error *close_err = got_repo_close(repo);
8205 if (error == NULL)
8206 error = close_err;
8208 if (pack_fds) {
8209 const struct got_error *pack_err =
8210 got_repo_pack_fds_close(pack_fds);
8211 if (error == NULL)
8212 error = pack_err;
8214 tog_free_refs();
8215 return error;
8218 static const struct got_error *
8219 ref_view_load_refs(struct tog_ref_view_state *s)
8221 struct got_reflist_entry *sre;
8222 struct tog_reflist_entry *re;
8224 s->nrefs = 0;
8225 TAILQ_FOREACH(sre, &tog_refs, entry) {
8226 if (strncmp(got_ref_get_name(sre->ref),
8227 "refs/got/", 9) == 0 &&
8228 strncmp(got_ref_get_name(sre->ref),
8229 "refs/got/backup/", 16) != 0)
8230 continue;
8232 re = malloc(sizeof(*re));
8233 if (re == NULL)
8234 return got_error_from_errno("malloc");
8236 re->ref = got_ref_dup(sre->ref);
8237 if (re->ref == NULL)
8238 return got_error_from_errno("got_ref_dup");
8239 re->idx = s->nrefs++;
8240 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8243 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8244 return NULL;
8247 static void
8248 ref_view_free_refs(struct tog_ref_view_state *s)
8250 struct tog_reflist_entry *re;
8252 while (!TAILQ_EMPTY(&s->refs)) {
8253 re = TAILQ_FIRST(&s->refs);
8254 TAILQ_REMOVE(&s->refs, re, entry);
8255 got_ref_close(re->ref);
8256 free(re);
8260 static const struct got_error *
8261 open_ref_view(struct tog_view *view, struct got_repository *repo)
8263 const struct got_error *err = NULL;
8264 struct tog_ref_view_state *s = &view->state.ref;
8266 s->selected_entry = 0;
8267 s->repo = repo;
8269 TAILQ_INIT(&s->refs);
8270 STAILQ_INIT(&s->colors);
8272 err = ref_view_load_refs(s);
8273 if (err)
8274 goto done;
8276 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8277 err = add_color(&s->colors, "^refs/heads/",
8278 TOG_COLOR_REFS_HEADS,
8279 get_color_value("TOG_COLOR_REFS_HEADS"));
8280 if (err)
8281 goto done;
8283 err = add_color(&s->colors, "^refs/tags/",
8284 TOG_COLOR_REFS_TAGS,
8285 get_color_value("TOG_COLOR_REFS_TAGS"));
8286 if (err)
8287 goto done;
8289 err = add_color(&s->colors, "^refs/remotes/",
8290 TOG_COLOR_REFS_REMOTES,
8291 get_color_value("TOG_COLOR_REFS_REMOTES"));
8292 if (err)
8293 goto done;
8295 err = add_color(&s->colors, "^refs/got/backup/",
8296 TOG_COLOR_REFS_BACKUP,
8297 get_color_value("TOG_COLOR_REFS_BACKUP"));
8298 if (err)
8299 goto done;
8302 view->show = show_ref_view;
8303 view->input = input_ref_view;
8304 view->close = close_ref_view;
8305 view->search_start = search_start_ref_view;
8306 view->search_next = search_next_ref_view;
8307 done:
8308 if (err) {
8309 if (view->close == NULL)
8310 close_ref_view(view);
8311 view_close(view);
8313 return err;
8316 static const struct got_error *
8317 close_ref_view(struct tog_view *view)
8319 struct tog_ref_view_state *s = &view->state.ref;
8321 ref_view_free_refs(s);
8322 free_colors(&s->colors);
8324 return NULL;
8327 static const struct got_error *
8328 resolve_reflist_entry(struct got_object_id **commit_id,
8329 struct tog_reflist_entry *re, struct got_repository *repo)
8331 const struct got_error *err = NULL;
8332 struct got_object_id *obj_id;
8333 struct got_tag_object *tag = NULL;
8334 int obj_type;
8336 *commit_id = NULL;
8338 err = got_ref_resolve(&obj_id, repo, re->ref);
8339 if (err)
8340 return err;
8342 err = got_object_get_type(&obj_type, repo, obj_id);
8343 if (err)
8344 goto done;
8346 switch (obj_type) {
8347 case GOT_OBJ_TYPE_COMMIT:
8348 *commit_id = obj_id;
8349 break;
8350 case GOT_OBJ_TYPE_TAG:
8351 err = got_object_open_as_tag(&tag, repo, obj_id);
8352 if (err)
8353 goto done;
8354 free(obj_id);
8355 err = got_object_get_type(&obj_type, repo,
8356 got_object_tag_get_object_id(tag));
8357 if (err)
8358 goto done;
8359 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8360 err = got_error(GOT_ERR_OBJ_TYPE);
8361 goto done;
8363 *commit_id = got_object_id_dup(
8364 got_object_tag_get_object_id(tag));
8365 if (*commit_id == NULL) {
8366 err = got_error_from_errno("got_object_id_dup");
8367 goto done;
8369 break;
8370 default:
8371 err = got_error(GOT_ERR_OBJ_TYPE);
8372 break;
8375 done:
8376 if (tag)
8377 got_object_tag_close(tag);
8378 if (err) {
8379 free(*commit_id);
8380 *commit_id = NULL;
8382 return err;
8385 static const struct got_error *
8386 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8387 struct tog_reflist_entry *re, struct got_repository *repo)
8389 struct tog_view *log_view;
8390 const struct got_error *err = NULL;
8391 struct got_object_id *commit_id = NULL;
8393 *new_view = NULL;
8395 err = resolve_reflist_entry(&commit_id, re, repo);
8396 if (err) {
8397 if (err->code != GOT_ERR_OBJ_TYPE)
8398 return err;
8399 else
8400 return NULL;
8403 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8404 if (log_view == NULL) {
8405 err = got_error_from_errno("view_open");
8406 goto done;
8409 err = open_log_view(log_view, commit_id, repo,
8410 got_ref_get_name(re->ref), "", 0);
8411 done:
8412 if (err)
8413 view_close(log_view);
8414 else
8415 *new_view = log_view;
8416 free(commit_id);
8417 return err;
8420 static void
8421 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8423 struct tog_reflist_entry *re;
8424 int i = 0;
8426 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8427 return;
8429 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8430 while (i++ < maxscroll) {
8431 if (re == NULL)
8432 break;
8433 s->first_displayed_entry = re;
8434 re = TAILQ_PREV(re, tog_reflist_head, entry);
8438 static const struct got_error *
8439 ref_scroll_down(struct tog_view *view, int maxscroll)
8441 struct tog_ref_view_state *s = &view->state.ref;
8442 struct tog_reflist_entry *next, *last;
8443 int n = 0;
8445 if (s->first_displayed_entry)
8446 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8447 else
8448 next = TAILQ_FIRST(&s->refs);
8450 last = s->last_displayed_entry;
8451 while (next && n++ < maxscroll) {
8452 if (last) {
8453 s->last_displayed_entry = last;
8454 last = TAILQ_NEXT(last, entry);
8456 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8457 s->first_displayed_entry = next;
8458 next = TAILQ_NEXT(next, entry);
8462 return NULL;
8465 static const struct got_error *
8466 search_start_ref_view(struct tog_view *view)
8468 struct tog_ref_view_state *s = &view->state.ref;
8470 s->matched_entry = NULL;
8471 return NULL;
8474 static int
8475 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8477 regmatch_t regmatch;
8479 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8480 0) == 0;
8483 static const struct got_error *
8484 search_next_ref_view(struct tog_view *view)
8486 struct tog_ref_view_state *s = &view->state.ref;
8487 struct tog_reflist_entry *re = NULL;
8489 if (!view->searching) {
8490 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8491 return NULL;
8494 if (s->matched_entry) {
8495 if (view->searching == TOG_SEARCH_FORWARD) {
8496 if (s->selected_entry)
8497 re = TAILQ_NEXT(s->selected_entry, entry);
8498 else
8499 re = TAILQ_PREV(s->selected_entry,
8500 tog_reflist_head, entry);
8501 } else {
8502 if (s->selected_entry == NULL)
8503 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8504 else
8505 re = TAILQ_PREV(s->selected_entry,
8506 tog_reflist_head, entry);
8508 } else {
8509 if (s->selected_entry)
8510 re = s->selected_entry;
8511 else if (view->searching == TOG_SEARCH_FORWARD)
8512 re = TAILQ_FIRST(&s->refs);
8513 else
8514 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8517 while (1) {
8518 if (re == NULL) {
8519 if (s->matched_entry == NULL) {
8520 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8521 return NULL;
8523 if (view->searching == TOG_SEARCH_FORWARD)
8524 re = TAILQ_FIRST(&s->refs);
8525 else
8526 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8529 if (match_reflist_entry(re, &view->regex)) {
8530 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8531 s->matched_entry = re;
8532 break;
8535 if (view->searching == TOG_SEARCH_FORWARD)
8536 re = TAILQ_NEXT(re, entry);
8537 else
8538 re = TAILQ_PREV(re, tog_reflist_head, entry);
8541 if (s->matched_entry) {
8542 s->first_displayed_entry = s->matched_entry;
8543 s->selected = 0;
8546 return NULL;
8549 static const struct got_error *
8550 show_ref_view(struct tog_view *view)
8552 const struct got_error *err = NULL;
8553 struct tog_ref_view_state *s = &view->state.ref;
8554 struct tog_reflist_entry *re;
8555 char *line = NULL;
8556 wchar_t *wline;
8557 struct tog_color *tc;
8558 int width, n, scrollx;
8559 int limit = view->nlines;
8561 werase(view->window);
8563 s->ndisplayed = 0;
8564 if (view_is_hsplit_top(view))
8565 --limit; /* border */
8567 if (limit == 0)
8568 return NULL;
8570 re = s->first_displayed_entry;
8572 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8573 s->nrefs) == -1)
8574 return got_error_from_errno("asprintf");
8576 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8577 if (err) {
8578 free(line);
8579 return err;
8581 if (view_needs_focus_indication(view))
8582 wstandout(view->window);
8583 waddwstr(view->window, wline);
8584 while (width++ < view->ncols)
8585 waddch(view->window, ' ');
8586 if (view_needs_focus_indication(view))
8587 wstandend(view->window);
8588 free(wline);
8589 wline = NULL;
8590 free(line);
8591 line = NULL;
8592 if (--limit <= 0)
8593 return NULL;
8595 n = 0;
8596 view->maxx = 0;
8597 while (re && limit > 0) {
8598 char *line = NULL;
8599 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8601 if (s->show_date) {
8602 struct got_commit_object *ci;
8603 struct got_tag_object *tag;
8604 struct got_object_id *id;
8605 struct tm tm;
8606 time_t t;
8608 err = got_ref_resolve(&id, s->repo, re->ref);
8609 if (err)
8610 return err;
8611 err = got_object_open_as_tag(&tag, s->repo, id);
8612 if (err) {
8613 if (err->code != GOT_ERR_OBJ_TYPE) {
8614 free(id);
8615 return err;
8617 err = got_object_open_as_commit(&ci, s->repo,
8618 id);
8619 if (err) {
8620 free(id);
8621 return err;
8623 t = got_object_commit_get_committer_time(ci);
8624 got_object_commit_close(ci);
8625 } else {
8626 t = got_object_tag_get_tagger_time(tag);
8627 got_object_tag_close(tag);
8629 free(id);
8630 if (gmtime_r(&t, &tm) == NULL)
8631 return got_error_from_errno("gmtime_r");
8632 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8633 return got_error(GOT_ERR_NO_SPACE);
8635 if (got_ref_is_symbolic(re->ref)) {
8636 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8637 ymd : "", got_ref_get_name(re->ref),
8638 got_ref_get_symref_target(re->ref)) == -1)
8639 return got_error_from_errno("asprintf");
8640 } else if (s->show_ids) {
8641 struct got_object_id *id;
8642 char *id_str;
8643 err = got_ref_resolve(&id, s->repo, re->ref);
8644 if (err)
8645 return err;
8646 err = got_object_id_str(&id_str, id);
8647 if (err) {
8648 free(id);
8649 return err;
8651 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8652 got_ref_get_name(re->ref), id_str) == -1) {
8653 err = got_error_from_errno("asprintf");
8654 free(id);
8655 free(id_str);
8656 return err;
8658 free(id);
8659 free(id_str);
8660 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8661 got_ref_get_name(re->ref)) == -1)
8662 return got_error_from_errno("asprintf");
8664 /* use full line width to determine view->maxx */
8665 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8666 if (err) {
8667 free(line);
8668 return err;
8670 view->maxx = MAX(view->maxx, width);
8671 free(wline);
8672 wline = NULL;
8674 err = format_line(&wline, &width, &scrollx, line, view->x,
8675 view->ncols, 0, 0);
8676 if (err) {
8677 free(line);
8678 return err;
8680 if (n == s->selected) {
8681 if (view->focussed)
8682 wstandout(view->window);
8683 s->selected_entry = re;
8685 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8686 if (tc)
8687 wattr_on(view->window,
8688 COLOR_PAIR(tc->colorpair), NULL);
8689 waddwstr(view->window, &wline[scrollx]);
8690 if (tc)
8691 wattr_off(view->window,
8692 COLOR_PAIR(tc->colorpair), NULL);
8693 if (width < view->ncols)
8694 waddch(view->window, '\n');
8695 if (n == s->selected && view->focussed)
8696 wstandend(view->window);
8697 free(line);
8698 free(wline);
8699 wline = NULL;
8700 n++;
8701 s->ndisplayed++;
8702 s->last_displayed_entry = re;
8704 limit--;
8705 re = TAILQ_NEXT(re, entry);
8708 view_border(view);
8709 return err;
8712 static const struct got_error *
8713 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8714 struct tog_reflist_entry *re, struct got_repository *repo)
8716 const struct got_error *err = NULL;
8717 struct got_object_id *commit_id = NULL;
8718 struct tog_view *tree_view;
8720 *new_view = NULL;
8722 err = resolve_reflist_entry(&commit_id, re, repo);
8723 if (err) {
8724 if (err->code != GOT_ERR_OBJ_TYPE)
8725 return err;
8726 else
8727 return NULL;
8731 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8732 if (tree_view == NULL) {
8733 err = got_error_from_errno("view_open");
8734 goto done;
8737 err = open_tree_view(tree_view, commit_id,
8738 got_ref_get_name(re->ref), repo);
8739 if (err)
8740 goto done;
8742 *new_view = tree_view;
8743 done:
8744 free(commit_id);
8745 return err;
8748 static const struct got_error *
8749 ref_goto_line(struct tog_view *view, int nlines)
8751 const struct got_error *err = NULL;
8752 struct tog_ref_view_state *s = &view->state.ref;
8753 int g, idx = s->selected_entry->idx;
8755 g = view->gline;
8756 view->gline = 0;
8758 if (g == 0)
8759 g = 1;
8760 else if (g > s->nrefs)
8761 g = s->nrefs;
8763 if (g >= s->first_displayed_entry->idx + 1 &&
8764 g <= s->last_displayed_entry->idx + 1 &&
8765 g - s->first_displayed_entry->idx - 1 < nlines) {
8766 s->selected = g - s->first_displayed_entry->idx - 1;
8767 return NULL;
8770 if (idx + 1 < g) {
8771 err = ref_scroll_down(view, g - idx - 1);
8772 if (err)
8773 return err;
8774 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8775 s->first_displayed_entry->idx + s->selected < g &&
8776 s->selected < s->ndisplayed - 1)
8777 s->selected = g - s->first_displayed_entry->idx - 1;
8778 } else if (idx + 1 > g)
8779 ref_scroll_up(s, idx - g + 1);
8781 if (g < nlines && s->first_displayed_entry->idx == 0)
8782 s->selected = g - 1;
8784 return NULL;
8788 static const struct got_error *
8789 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8791 const struct got_error *err = NULL;
8792 struct tog_ref_view_state *s = &view->state.ref;
8793 struct tog_reflist_entry *re;
8794 int n, nscroll = view->nlines - 1;
8796 if (view->gline)
8797 return ref_goto_line(view, nscroll);
8799 switch (ch) {
8800 case '0':
8801 case '$':
8802 case KEY_RIGHT:
8803 case 'l':
8804 case KEY_LEFT:
8805 case 'h':
8806 horizontal_scroll_input(view, ch);
8807 break;
8808 case 'i':
8809 s->show_ids = !s->show_ids;
8810 view->count = 0;
8811 break;
8812 case 'm':
8813 s->show_date = !s->show_date;
8814 view->count = 0;
8815 break;
8816 case 'o':
8817 s->sort_by_date = !s->sort_by_date;
8818 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8819 view->count = 0;
8820 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8821 got_ref_cmp_by_commit_timestamp_descending :
8822 tog_ref_cmp_by_name, s->repo);
8823 if (err)
8824 break;
8825 got_reflist_object_id_map_free(tog_refs_idmap);
8826 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8827 &tog_refs, s->repo);
8828 if (err)
8829 break;
8830 ref_view_free_refs(s);
8831 err = ref_view_load_refs(s);
8832 break;
8833 case KEY_ENTER:
8834 case '\r':
8835 view->count = 0;
8836 if (!s->selected_entry)
8837 break;
8838 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8839 break;
8840 case 'T':
8841 view->count = 0;
8842 if (!s->selected_entry)
8843 break;
8844 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8845 break;
8846 case 'g':
8847 case '=':
8848 case KEY_HOME:
8849 s->selected = 0;
8850 view->count = 0;
8851 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8852 break;
8853 case 'G':
8854 case '*':
8855 case KEY_END: {
8856 int eos = view->nlines - 1;
8858 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8859 --eos; /* border */
8860 s->selected = 0;
8861 view->count = 0;
8862 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8863 for (n = 0; n < eos; n++) {
8864 if (re == NULL)
8865 break;
8866 s->first_displayed_entry = re;
8867 re = TAILQ_PREV(re, tog_reflist_head, entry);
8869 if (n > 0)
8870 s->selected = n - 1;
8871 break;
8873 case 'k':
8874 case KEY_UP:
8875 case CTRL('p'):
8876 if (s->selected > 0) {
8877 s->selected--;
8878 break;
8880 ref_scroll_up(s, 1);
8881 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8882 view->count = 0;
8883 break;
8884 case CTRL('u'):
8885 case 'u':
8886 nscroll /= 2;
8887 /* FALL THROUGH */
8888 case KEY_PPAGE:
8889 case CTRL('b'):
8890 case 'b':
8891 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8892 s->selected -= MIN(nscroll, s->selected);
8893 ref_scroll_up(s, MAX(0, nscroll));
8894 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8895 view->count = 0;
8896 break;
8897 case 'j':
8898 case KEY_DOWN:
8899 case CTRL('n'):
8900 if (s->selected < s->ndisplayed - 1) {
8901 s->selected++;
8902 break;
8904 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8905 /* can't scroll any further */
8906 view->count = 0;
8907 break;
8909 ref_scroll_down(view, 1);
8910 break;
8911 case CTRL('d'):
8912 case 'd':
8913 nscroll /= 2;
8914 /* FALL THROUGH */
8915 case KEY_NPAGE:
8916 case CTRL('f'):
8917 case 'f':
8918 case ' ':
8919 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8920 /* can't scroll any further; move cursor down */
8921 if (s->selected < s->ndisplayed - 1)
8922 s->selected += MIN(nscroll,
8923 s->ndisplayed - s->selected - 1);
8924 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8925 s->selected += s->ndisplayed - s->selected - 1;
8926 view->count = 0;
8927 break;
8929 ref_scroll_down(view, nscroll);
8930 break;
8931 case CTRL('l'):
8932 view->count = 0;
8933 tog_free_refs();
8934 err = tog_load_refs(s->repo, s->sort_by_date);
8935 if (err)
8936 break;
8937 ref_view_free_refs(s);
8938 err = ref_view_load_refs(s);
8939 break;
8940 case KEY_RESIZE:
8941 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8942 s->selected = view->nlines - 2;
8943 break;
8944 default:
8945 view->count = 0;
8946 break;
8949 return err;
8952 __dead static void
8953 usage_ref(void)
8955 endwin();
8956 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8957 getprogname());
8958 exit(1);
8961 static const struct got_error *
8962 cmd_ref(int argc, char *argv[])
8964 const struct got_error *error;
8965 struct got_repository *repo = NULL;
8966 struct got_worktree *worktree = NULL;
8967 char *cwd = NULL, *repo_path = NULL;
8968 int ch;
8969 struct tog_view *view;
8970 int *pack_fds = NULL;
8972 while ((ch = getopt(argc, argv, "r:")) != -1) {
8973 switch (ch) {
8974 case 'r':
8975 repo_path = realpath(optarg, NULL);
8976 if (repo_path == NULL)
8977 return got_error_from_errno2("realpath",
8978 optarg);
8979 break;
8980 default:
8981 usage_ref();
8982 /* NOTREACHED */
8986 argc -= optind;
8987 argv += optind;
8989 if (argc > 1)
8990 usage_ref();
8992 error = got_repo_pack_fds_open(&pack_fds);
8993 if (error != NULL)
8994 goto done;
8996 if (repo_path == NULL) {
8997 cwd = getcwd(NULL, 0);
8998 if (cwd == NULL)
8999 return got_error_from_errno("getcwd");
9000 error = got_worktree_open(&worktree, cwd, NULL);
9001 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9002 goto done;
9003 if (worktree)
9004 repo_path =
9005 strdup(got_worktree_get_repo_path(worktree));
9006 else
9007 repo_path = strdup(cwd);
9008 if (repo_path == NULL) {
9009 error = got_error_from_errno("strdup");
9010 goto done;
9014 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9015 if (error != NULL)
9016 goto done;
9018 init_curses();
9020 error = apply_unveil(got_repo_get_path(repo), NULL);
9021 if (error)
9022 goto done;
9024 error = tog_load_refs(repo, 0);
9025 if (error)
9026 goto done;
9028 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
9029 if (view == NULL) {
9030 error = got_error_from_errno("view_open");
9031 goto done;
9034 error = open_ref_view(view, repo);
9035 if (error)
9036 goto done;
9038 if (worktree) {
9039 /* Release work tree lock. */
9040 got_worktree_close(worktree);
9041 worktree = NULL;
9043 error = view_loop(view);
9044 done:
9045 free(repo_path);
9046 free(cwd);
9047 if (repo) {
9048 const struct got_error *close_err = got_repo_close(repo);
9049 if (close_err)
9050 error = close_err;
9052 if (pack_fds) {
9053 const struct got_error *pack_err =
9054 got_repo_pack_fds_close(pack_fds);
9055 if (error == NULL)
9056 error = pack_err;
9058 tog_free_refs();
9059 return error;
9062 static const struct got_error*
9063 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
9064 const char *str)
9066 size_t len;
9068 if (win == NULL)
9069 win = stdscr;
9071 len = strlen(str);
9072 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
9074 if (focus)
9075 wstandout(win);
9076 if (mvwprintw(win, y, x, "%s", str) == ERR)
9077 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
9078 if (focus)
9079 wstandend(win);
9081 return NULL;
9084 static const struct got_error *
9085 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
9087 off_t *p;
9089 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
9090 if (p == NULL) {
9091 free(*line_offsets);
9092 *line_offsets = NULL;
9093 return got_error_from_errno("reallocarray");
9096 *line_offsets = p;
9097 (*line_offsets)[*nlines] = off;
9098 ++(*nlines);
9099 return NULL;
9102 static const struct got_error *
9103 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
9105 *ret = 0;
9107 for (;n > 0; --n, ++km) {
9108 char *t0, *t, *k;
9109 size_t len = 1;
9111 if (km->keys == NULL)
9112 continue;
9114 t = t0 = strdup(km->keys);
9115 if (t0 == NULL)
9116 return got_error_from_errno("strdup");
9118 len += strlen(t);
9119 while ((k = strsep(&t, " ")) != NULL)
9120 len += strlen(k) > 1 ? 2 : 0;
9121 free(t0);
9122 *ret = MAX(*ret, len);
9125 return NULL;
9129 * Write keymap section headers, keys, and key info in km to f.
9130 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9131 * wrap control and symbolic keys in guillemets, else use <>.
9133 static const struct got_error *
9134 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9136 int n, len = width;
9138 if (km->keys) {
9139 static const char *u8_glyph[] = {
9140 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9141 "\xe2\x80\xba" /* U+203A (utf8 >) */
9143 char *t0, *t, *k;
9144 int cs, s, first = 1;
9146 cs = got_locale_is_utf8();
9148 t = t0 = strdup(km->keys);
9149 if (t0 == NULL)
9150 return got_error_from_errno("strdup");
9152 len = strlen(km->keys);
9153 while ((k = strsep(&t, " ")) != NULL) {
9154 s = strlen(k) > 1; /* control or symbolic key */
9155 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9156 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9157 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9158 if (n < 0) {
9159 free(t0);
9160 return got_error_from_errno("fprintf");
9162 first = 0;
9163 len += s ? 2 : 0;
9164 *off += n;
9166 free(t0);
9168 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9169 if (n < 0)
9170 return got_error_from_errno("fprintf");
9171 *off += n;
9173 return NULL;
9176 static const struct got_error *
9177 format_help(struct tog_help_view_state *s)
9179 const struct got_error *err = NULL;
9180 off_t off = 0;
9181 int i, max, n, show = s->all;
9182 static const struct tog_key_map km[] = {
9183 #define KEYMAP_(info, type) { NULL, (info), type }
9184 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9185 GENERATE_HELP
9186 #undef KEYMAP_
9187 #undef KEY_
9190 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9191 if (err)
9192 return err;
9194 n = nitems(km);
9195 err = max_key_str(&max, km, n);
9196 if (err)
9197 return err;
9199 for (i = 0; i < n; ++i) {
9200 if (km[i].keys == NULL) {
9201 show = s->all;
9202 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9203 km[i].type == s->type || s->all)
9204 show = 1;
9206 if (show) {
9207 err = format_help_line(&off, s->f, &km[i], max);
9208 if (err)
9209 return err;
9210 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9211 if (err)
9212 return err;
9215 fputc('\n', s->f);
9216 ++off;
9217 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9218 return err;
9221 static const struct got_error *
9222 create_help(struct tog_help_view_state *s)
9224 FILE *f;
9225 const struct got_error *err;
9227 free(s->line_offsets);
9228 s->line_offsets = NULL;
9229 s->nlines = 0;
9231 f = got_opentemp();
9232 if (f == NULL)
9233 return got_error_from_errno("got_opentemp");
9234 s->f = f;
9236 err = format_help(s);
9237 if (err)
9238 return err;
9240 if (s->f && fflush(s->f) != 0)
9241 return got_error_from_errno("fflush");
9243 return NULL;
9246 static const struct got_error *
9247 search_start_help_view(struct tog_view *view)
9249 view->state.help.matched_line = 0;
9250 return NULL;
9253 static void
9254 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9255 size_t *nlines, int **first, int **last, int **match, int **selected)
9257 struct tog_help_view_state *s = &view->state.help;
9259 *f = s->f;
9260 *nlines = s->nlines;
9261 *line_offsets = s->line_offsets;
9262 *match = &s->matched_line;
9263 *first = &s->first_displayed_line;
9264 *last = &s->last_displayed_line;
9265 *selected = &s->selected_line;
9268 static const struct got_error *
9269 show_help_view(struct tog_view *view)
9271 struct tog_help_view_state *s = &view->state.help;
9272 const struct got_error *err;
9273 regmatch_t *regmatch = &view->regmatch;
9274 wchar_t *wline;
9275 char *line;
9276 ssize_t linelen;
9277 size_t linesz = 0;
9278 int width, nprinted = 0, rc = 0;
9279 int eos = view->nlines;
9281 if (view_is_hsplit_top(view))
9282 --eos; /* account for border */
9284 s->lineno = 0;
9285 rewind(s->f);
9286 werase(view->window);
9288 if (view->gline > s->nlines - 1)
9289 view->gline = s->nlines - 1;
9291 err = win_draw_center(view->window, 0, 0, view->ncols,
9292 view_needs_focus_indication(view),
9293 "tog help (press q to return to tog)");
9294 if (err)
9295 return err;
9296 if (eos <= 1)
9297 return NULL;
9298 waddstr(view->window, "\n\n");
9299 eos -= 2;
9301 s->eof = 0;
9302 view->maxx = 0;
9303 line = NULL;
9304 while (eos > 0 && nprinted < eos) {
9305 attr_t attr = 0;
9307 linelen = getline(&line, &linesz, s->f);
9308 if (linelen == -1) {
9309 if (!feof(s->f)) {
9310 free(line);
9311 return got_ferror(s->f, GOT_ERR_IO);
9313 s->eof = 1;
9314 break;
9316 if (++s->lineno < s->first_displayed_line)
9317 continue;
9318 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9319 continue;
9320 if (s->lineno == view->hiline)
9321 attr = A_STANDOUT;
9323 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9324 view->x ? 1 : 0);
9325 if (err) {
9326 free(line);
9327 return err;
9329 view->maxx = MAX(view->maxx, width);
9330 free(wline);
9331 wline = NULL;
9333 if (attr)
9334 wattron(view->window, attr);
9335 if (s->first_displayed_line + nprinted == s->matched_line &&
9336 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9337 err = add_matched_line(&width, line, view->ncols - 1, 0,
9338 view->window, view->x, regmatch);
9339 if (err) {
9340 free(line);
9341 return err;
9343 } else {
9344 int skip;
9346 err = format_line(&wline, &width, &skip, line,
9347 view->x, view->ncols, 0, view->x ? 1 : 0);
9348 if (err) {
9349 free(line);
9350 return err;
9352 waddwstr(view->window, &wline[skip]);
9353 free(wline);
9354 wline = NULL;
9356 if (s->lineno == view->hiline) {
9357 while (width++ < view->ncols)
9358 waddch(view->window, ' ');
9359 } else {
9360 if (width < view->ncols)
9361 waddch(view->window, '\n');
9363 if (attr)
9364 wattroff(view->window, attr);
9365 if (++nprinted == 1)
9366 s->first_displayed_line = s->lineno;
9368 free(line);
9369 if (nprinted > 0)
9370 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9371 else
9372 s->last_displayed_line = s->first_displayed_line;
9374 view_border(view);
9376 if (s->eof) {
9377 rc = waddnstr(view->window,
9378 "See the tog(1) manual page for full documentation",
9379 view->ncols - 1);
9380 if (rc == ERR)
9381 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9382 } else {
9383 wmove(view->window, view->nlines - 1, 0);
9384 wclrtoeol(view->window);
9385 wstandout(view->window);
9386 rc = waddnstr(view->window, "scroll down for more...",
9387 view->ncols - 1);
9388 if (rc == ERR)
9389 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9390 if (getcurx(view->window) < view->ncols - 6) {
9391 rc = wprintw(view->window, "[%.0f%%]",
9392 100.00 * s->last_displayed_line / s->nlines);
9393 if (rc == ERR)
9394 return got_error_msg(GOT_ERR_IO, "wprintw");
9396 wstandend(view->window);
9399 return NULL;
9402 static const struct got_error *
9403 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9405 struct tog_help_view_state *s = &view->state.help;
9406 const struct got_error *err = NULL;
9407 char *line = NULL;
9408 ssize_t linelen;
9409 size_t linesz = 0;
9410 int eos, nscroll;
9412 eos = nscroll = view->nlines;
9413 if (view_is_hsplit_top(view))
9414 --eos; /* border */
9416 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9418 switch (ch) {
9419 case '0':
9420 case '$':
9421 case KEY_RIGHT:
9422 case 'l':
9423 case KEY_LEFT:
9424 case 'h':
9425 horizontal_scroll_input(view, ch);
9426 break;
9427 case 'g':
9428 case KEY_HOME:
9429 s->first_displayed_line = 1;
9430 view->count = 0;
9431 break;
9432 case 'G':
9433 case KEY_END:
9434 view->count = 0;
9435 if (s->eof)
9436 break;
9437 s->first_displayed_line = (s->nlines - eos) + 3;
9438 s->eof = 1;
9439 break;
9440 case 'k':
9441 case KEY_UP:
9442 if (s->first_displayed_line > 1)
9443 --s->first_displayed_line;
9444 else
9445 view->count = 0;
9446 break;
9447 case CTRL('u'):
9448 case 'u':
9449 nscroll /= 2;
9450 /* FALL THROUGH */
9451 case KEY_PPAGE:
9452 case CTRL('b'):
9453 case 'b':
9454 if (s->first_displayed_line == 1) {
9455 view->count = 0;
9456 break;
9458 while (--nscroll > 0 && s->first_displayed_line > 1)
9459 s->first_displayed_line--;
9460 break;
9461 case 'j':
9462 case KEY_DOWN:
9463 case CTRL('n'):
9464 if (!s->eof)
9465 ++s->first_displayed_line;
9466 else
9467 view->count = 0;
9468 break;
9469 case CTRL('d'):
9470 case 'd':
9471 nscroll /= 2;
9472 /* FALL THROUGH */
9473 case KEY_NPAGE:
9474 case CTRL('f'):
9475 case 'f':
9476 case ' ':
9477 if (s->eof) {
9478 view->count = 0;
9479 break;
9481 while (!s->eof && --nscroll > 0) {
9482 linelen = getline(&line, &linesz, s->f);
9483 s->first_displayed_line++;
9484 if (linelen == -1) {
9485 if (feof(s->f))
9486 s->eof = 1;
9487 else
9488 err = got_ferror(s->f, GOT_ERR_IO);
9489 break;
9492 free(line);
9493 break;
9494 default:
9495 view->count = 0;
9496 break;
9499 return err;
9502 static const struct got_error *
9503 close_help_view(struct tog_view *view)
9505 struct tog_help_view_state *s = &view->state.help;
9507 free(s->line_offsets);
9508 s->line_offsets = NULL;
9509 if (fclose(s->f) == EOF)
9510 return got_error_from_errno("fclose");
9512 return NULL;
9515 static const struct got_error *
9516 reset_help_view(struct tog_view *view)
9518 struct tog_help_view_state *s = &view->state.help;
9521 if (s->f && fclose(s->f) == EOF)
9522 return got_error_from_errno("fclose");
9524 wclear(view->window);
9525 view->count = 0;
9526 view->x = 0;
9527 s->all = !s->all;
9528 s->first_displayed_line = 1;
9529 s->last_displayed_line = view->nlines;
9530 s->matched_line = 0;
9532 return create_help(s);
9535 static const struct got_error *
9536 open_help_view(struct tog_view *view, struct tog_view *parent)
9538 const struct got_error *err = NULL;
9539 struct tog_help_view_state *s = &view->state.help;
9541 s->type = (enum tog_keymap_type)parent->type;
9542 s->first_displayed_line = 1;
9543 s->last_displayed_line = view->nlines;
9544 s->selected_line = 1;
9546 view->show = show_help_view;
9547 view->input = input_help_view;
9548 view->reset = reset_help_view;
9549 view->close = close_help_view;
9550 view->search_start = search_start_help_view;
9551 view->search_setup = search_setup_help_view;
9552 view->search_next = search_next_view_match;
9554 err = create_help(s);
9555 return err;
9558 static const struct got_error *
9559 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9560 enum tog_view_type request, int y, int x)
9562 const struct got_error *err = NULL;
9564 *new_view = NULL;
9566 switch (request) {
9567 case TOG_VIEW_DIFF:
9568 if (view->type == TOG_VIEW_LOG) {
9569 struct tog_log_view_state *s = &view->state.log;
9571 err = open_diff_view_for_commit(new_view, y, x,
9572 s->selected_entry->commit, s->selected_entry->id,
9573 view, s->repo);
9574 } else
9575 return got_error_msg(GOT_ERR_NOT_IMPL,
9576 "parent/child view pair not supported");
9577 break;
9578 case TOG_VIEW_BLAME:
9579 if (view->type == TOG_VIEW_TREE) {
9580 struct tog_tree_view_state *s = &view->state.tree;
9582 err = blame_tree_entry(new_view, y, x,
9583 s->selected_entry, &s->parents, s->commit_id,
9584 s->repo);
9585 } else
9586 return got_error_msg(GOT_ERR_NOT_IMPL,
9587 "parent/child view pair not supported");
9588 break;
9589 case TOG_VIEW_LOG:
9590 if (view->type == TOG_VIEW_BLAME)
9591 err = log_annotated_line(new_view, y, x,
9592 view->state.blame.repo, view->state.blame.id_to_log);
9593 else if (view->type == TOG_VIEW_TREE)
9594 err = log_selected_tree_entry(new_view, y, x,
9595 &view->state.tree);
9596 else if (view->type == TOG_VIEW_REF)
9597 err = log_ref_entry(new_view, y, x,
9598 view->state.ref.selected_entry,
9599 view->state.ref.repo);
9600 else
9601 return got_error_msg(GOT_ERR_NOT_IMPL,
9602 "parent/child view pair not supported");
9603 break;
9604 case TOG_VIEW_TREE:
9605 if (view->type == TOG_VIEW_LOG)
9606 err = browse_commit_tree(new_view, y, x,
9607 view->state.log.selected_entry,
9608 view->state.log.in_repo_path,
9609 view->state.log.head_ref_name,
9610 view->state.log.repo);
9611 else if (view->type == TOG_VIEW_REF)
9612 err = browse_ref_tree(new_view, y, x,
9613 view->state.ref.selected_entry,
9614 view->state.ref.repo);
9615 else
9616 return got_error_msg(GOT_ERR_NOT_IMPL,
9617 "parent/child view pair not supported");
9618 break;
9619 case TOG_VIEW_REF:
9620 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9621 if (*new_view == NULL)
9622 return got_error_from_errno("view_open");
9623 if (view->type == TOG_VIEW_LOG)
9624 err = open_ref_view(*new_view, view->state.log.repo);
9625 else if (view->type == TOG_VIEW_TREE)
9626 err = open_ref_view(*new_view, view->state.tree.repo);
9627 else
9628 err = got_error_msg(GOT_ERR_NOT_IMPL,
9629 "parent/child view pair not supported");
9630 if (err)
9631 view_close(*new_view);
9632 break;
9633 case TOG_VIEW_HELP:
9634 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9635 if (*new_view == NULL)
9636 return got_error_from_errno("view_open");
9637 err = open_help_view(*new_view, view);
9638 if (err)
9639 view_close(*new_view);
9640 break;
9641 default:
9642 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9645 return err;
9649 * If view was scrolled down to move the selected line into view when opening a
9650 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9652 static void
9653 offset_selection_up(struct tog_view *view)
9655 switch (view->type) {
9656 case TOG_VIEW_BLAME: {
9657 struct tog_blame_view_state *s = &view->state.blame;
9658 if (s->first_displayed_line == 1) {
9659 s->selected_line = MAX(s->selected_line - view->offset,
9660 1);
9661 break;
9663 if (s->first_displayed_line > view->offset)
9664 s->first_displayed_line -= view->offset;
9665 else
9666 s->first_displayed_line = 1;
9667 s->selected_line += view->offset;
9668 break;
9670 case TOG_VIEW_LOG:
9671 log_scroll_up(&view->state.log, view->offset);
9672 view->state.log.selected += view->offset;
9673 break;
9674 case TOG_VIEW_REF:
9675 ref_scroll_up(&view->state.ref, view->offset);
9676 view->state.ref.selected += view->offset;
9677 break;
9678 case TOG_VIEW_TREE:
9679 tree_scroll_up(&view->state.tree, view->offset);
9680 view->state.tree.selected += view->offset;
9681 break;
9682 default:
9683 break;
9686 view->offset = 0;
9690 * If the selected line is in the section of screen covered by the bottom split,
9691 * scroll down offset lines to move it into view and index its new position.
9693 static const struct got_error *
9694 offset_selection_down(struct tog_view *view)
9696 const struct got_error *err = NULL;
9697 const struct got_error *(*scrolld)(struct tog_view *, int);
9698 int *selected = NULL;
9699 int header, offset;
9701 switch (view->type) {
9702 case TOG_VIEW_BLAME: {
9703 struct tog_blame_view_state *s = &view->state.blame;
9704 header = 3;
9705 scrolld = NULL;
9706 if (s->selected_line > view->nlines - header) {
9707 offset = abs(view->nlines - s->selected_line - header);
9708 s->first_displayed_line += offset;
9709 s->selected_line -= offset;
9710 view->offset = offset;
9712 break;
9714 case TOG_VIEW_LOG: {
9715 struct tog_log_view_state *s = &view->state.log;
9716 scrolld = &log_scroll_down;
9717 header = view_is_parent_view(view) ? 3 : 2;
9718 selected = &s->selected;
9719 break;
9721 case TOG_VIEW_REF: {
9722 struct tog_ref_view_state *s = &view->state.ref;
9723 scrolld = &ref_scroll_down;
9724 header = 3;
9725 selected = &s->selected;
9726 break;
9728 case TOG_VIEW_TREE: {
9729 struct tog_tree_view_state *s = &view->state.tree;
9730 scrolld = &tree_scroll_down;
9731 header = 5;
9732 selected = &s->selected;
9733 break;
9735 default:
9736 selected = NULL;
9737 scrolld = NULL;
9738 header = 0;
9739 break;
9742 if (selected && *selected > view->nlines - header) {
9743 offset = abs(view->nlines - *selected - header);
9744 view->offset = offset;
9745 if (scrolld && offset) {
9746 err = scrolld(view, offset);
9747 *selected -= offset;
9751 return err;
9754 static void
9755 list_commands(FILE *fp)
9757 size_t i;
9759 fprintf(fp, "commands:");
9760 for (i = 0; i < nitems(tog_commands); i++) {
9761 const struct tog_cmd *cmd = &tog_commands[i];
9762 fprintf(fp, " %s", cmd->name);
9764 fputc('\n', fp);
9767 __dead static void
9768 usage(int hflag, int status)
9770 FILE *fp = (status == 0) ? stdout : stderr;
9772 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9773 getprogname());
9774 if (hflag) {
9775 fprintf(fp, "lazy usage: %s path\n", getprogname());
9776 list_commands(fp);
9778 exit(status);
9781 static char **
9782 make_argv(int argc, ...)
9784 va_list ap;
9785 char **argv;
9786 int i;
9788 va_start(ap, argc);
9790 argv = calloc(argc, sizeof(char *));
9791 if (argv == NULL)
9792 err(1, "calloc");
9793 for (i = 0; i < argc; i++) {
9794 argv[i] = strdup(va_arg(ap, char *));
9795 if (argv[i] == NULL)
9796 err(1, "strdup");
9799 va_end(ap);
9800 return argv;
9804 * Try to convert 'tog path' into a 'tog log path' command.
9805 * The user could simply have mistyped the command rather than knowingly
9806 * provided a path. So check whether argv[0] can in fact be resolved
9807 * to a path in the HEAD commit and print a special error if not.
9808 * This hack is for mpi@ <3
9810 static const struct got_error *
9811 tog_log_with_path(int argc, char *argv[])
9813 const struct got_error *error = NULL, *close_err;
9814 const struct tog_cmd *cmd = NULL;
9815 struct got_repository *repo = NULL;
9816 struct got_worktree *worktree = NULL;
9817 struct got_object_id *commit_id = NULL, *id = NULL;
9818 struct got_commit_object *commit = NULL;
9819 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9820 char *commit_id_str = NULL, **cmd_argv = NULL;
9821 int *pack_fds = NULL;
9823 cwd = getcwd(NULL, 0);
9824 if (cwd == NULL)
9825 return got_error_from_errno("getcwd");
9827 error = got_repo_pack_fds_open(&pack_fds);
9828 if (error != NULL)
9829 goto done;
9831 error = got_worktree_open(&worktree, cwd, NULL);
9832 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9833 goto done;
9835 if (worktree)
9836 repo_path = strdup(got_worktree_get_repo_path(worktree));
9837 else
9838 repo_path = strdup(cwd);
9839 if (repo_path == NULL) {
9840 error = got_error_from_errno("strdup");
9841 goto done;
9844 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9845 if (error != NULL)
9846 goto done;
9848 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9849 repo, worktree);
9850 if (error)
9851 goto done;
9853 error = tog_load_refs(repo, 0);
9854 if (error)
9855 goto done;
9856 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9857 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9858 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9859 if (error)
9860 goto done;
9862 if (worktree) {
9863 got_worktree_close(worktree);
9864 worktree = NULL;
9867 error = got_object_open_as_commit(&commit, repo, commit_id);
9868 if (error)
9869 goto done;
9871 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9872 if (error) {
9873 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9874 goto done;
9875 fprintf(stderr, "%s: '%s' is no known command or path\n",
9876 getprogname(), argv[0]);
9877 usage(1, 1);
9878 /* not reached */
9881 error = got_object_id_str(&commit_id_str, commit_id);
9882 if (error)
9883 goto done;
9885 cmd = &tog_commands[0]; /* log */
9886 argc = 4;
9887 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9888 error = cmd->cmd_main(argc, cmd_argv);
9889 done:
9890 if (repo) {
9891 close_err = got_repo_close(repo);
9892 if (error == NULL)
9893 error = close_err;
9895 if (commit)
9896 got_object_commit_close(commit);
9897 if (worktree)
9898 got_worktree_close(worktree);
9899 if (pack_fds) {
9900 const struct got_error *pack_err =
9901 got_repo_pack_fds_close(pack_fds);
9902 if (error == NULL)
9903 error = pack_err;
9905 free(id);
9906 free(commit_id_str);
9907 free(commit_id);
9908 free(cwd);
9909 free(repo_path);
9910 free(in_repo_path);
9911 if (cmd_argv) {
9912 int i;
9913 for (i = 0; i < argc; i++)
9914 free(cmd_argv[i]);
9915 free(cmd_argv);
9917 tog_free_refs();
9918 return error;
9921 int
9922 main(int argc, char *argv[])
9924 const struct got_error *io_err, *error = NULL;
9925 const struct tog_cmd *cmd = NULL;
9926 int ch, hflag = 0, Vflag = 0;
9927 char **cmd_argv = NULL;
9928 static const struct option longopts[] = {
9929 { "version", no_argument, NULL, 'V' },
9930 { NULL, 0, NULL, 0}
9932 char *diff_algo_str = NULL;
9933 const char *test_script_path;
9935 setlocale(LC_CTYPE, "");
9938 * Test mode init must happen before pledge() because "tty" will
9939 * not allow TTY-related ioctls to occur via regular files.
9941 test_script_path = getenv("TOG_TEST_SCRIPT");
9942 if (test_script_path != NULL) {
9943 error = init_mock_term(test_script_path);
9944 if (error) {
9945 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9946 return 1;
9948 } else if (!isatty(STDIN_FILENO))
9949 errx(1, "standard input is not a tty");
9951 #if !defined(PROFILE)
9952 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9953 NULL) == -1)
9954 err(1, "pledge");
9955 #endif
9957 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9958 switch (ch) {
9959 case 'h':
9960 hflag = 1;
9961 break;
9962 case 'V':
9963 Vflag = 1;
9964 break;
9965 default:
9966 usage(hflag, 1);
9967 /* NOTREACHED */
9971 argc -= optind;
9972 argv += optind;
9973 optind = 1;
9974 optreset = 1;
9976 if (Vflag) {
9977 got_version_print_str();
9978 return 0;
9981 if (argc == 0) {
9982 if (hflag)
9983 usage(hflag, 0);
9984 /* Build an argument vector which runs a default command. */
9985 cmd = &tog_commands[0];
9986 argc = 1;
9987 cmd_argv = make_argv(argc, cmd->name);
9988 } else {
9989 size_t i;
9991 /* Did the user specify a command? */
9992 for (i = 0; i < nitems(tog_commands); i++) {
9993 if (strncmp(tog_commands[i].name, argv[0],
9994 strlen(argv[0])) == 0) {
9995 cmd = &tog_commands[i];
9996 break;
10001 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
10002 if (diff_algo_str) {
10003 if (strcasecmp(diff_algo_str, "patience") == 0)
10004 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
10005 if (strcasecmp(diff_algo_str, "myers") == 0)
10006 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
10009 if (cmd == NULL) {
10010 if (argc != 1)
10011 usage(0, 1);
10012 /* No command specified; try log with a path */
10013 error = tog_log_with_path(argc, argv);
10014 } else {
10015 if (hflag)
10016 cmd->cmd_usage();
10017 else
10018 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
10021 if (using_mock_io) {
10022 io_err = tog_io_close();
10023 if (error == NULL)
10024 error = io_err;
10026 endwin();
10027 if (cmd_argv) {
10028 int i;
10029 for (i = 0; i < argc; i++)
10030 free(cmd_argv[i]);
10031 free(cmd_argv);
10034 if (error && error->code != GOT_ERR_CANCELLED &&
10035 error->code != GOT_ERR_EOF &&
10036 error->code != GOT_ERR_PRIVSEP_EXIT &&
10037 error->code != GOT_ERR_PRIVSEP_PIPE &&
10038 !(error->code == GOT_ERR_ERRNO && errno == EINTR)) {
10039 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10040 return 1;
10042 return 0;