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 struct {
159 struct got_object_id *id;
160 int idx;
161 char marker;
162 } tog_base_commit;
163 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
165 static const struct got_error *
166 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
167 struct got_reference* re2)
169 const char *name1 = got_ref_get_name(re1);
170 const char *name2 = got_ref_get_name(re2);
171 int isbackup1, isbackup2;
173 /* Sort backup refs towards the bottom of the list. */
174 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
175 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
176 if (!isbackup1 && isbackup2) {
177 *cmp = -1;
178 return NULL;
179 } else if (isbackup1 && !isbackup2) {
180 *cmp = 1;
181 return NULL;
184 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
185 return NULL;
188 static const struct got_error *
189 tog_load_refs(struct got_repository *repo, int sort_by_date)
191 const struct got_error *err;
193 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
194 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
195 repo);
196 if (err)
197 return err;
199 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
200 repo);
203 static void
204 tog_free_refs(void)
206 if (tog_refs_idmap) {
207 got_reflist_object_id_map_free(tog_refs_idmap);
208 tog_refs_idmap = NULL;
210 got_ref_list_free(&tog_refs);
213 static const struct got_error *
214 add_color(struct tog_colors *colors, const char *pattern,
215 int idx, short color)
217 const struct got_error *err = NULL;
218 struct tog_color *tc;
219 int regerr = 0;
221 if (idx < 1 || idx > COLOR_PAIRS - 1)
222 return NULL;
224 init_pair(idx, color, -1);
226 tc = calloc(1, sizeof(*tc));
227 if (tc == NULL)
228 return got_error_from_errno("calloc");
229 regerr = regcomp(&tc->regex, pattern,
230 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
231 if (regerr) {
232 static char regerr_msg[512];
233 static char err_msg[512];
234 regerror(regerr, &tc->regex, regerr_msg,
235 sizeof(regerr_msg));
236 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
237 regerr_msg);
238 err = got_error_msg(GOT_ERR_REGEX, err_msg);
239 free(tc);
240 return err;
242 tc->colorpair = idx;
243 STAILQ_INSERT_HEAD(colors, tc, entry);
244 return NULL;
247 static void
248 free_colors(struct tog_colors *colors)
250 struct tog_color *tc;
252 while (!STAILQ_EMPTY(colors)) {
253 tc = STAILQ_FIRST(colors);
254 STAILQ_REMOVE_HEAD(colors, entry);
255 regfree(&tc->regex);
256 free(tc);
260 static struct tog_color *
261 get_color(struct tog_colors *colors, int colorpair)
263 struct tog_color *tc = NULL;
265 STAILQ_FOREACH(tc, colors, entry) {
266 if (tc->colorpair == colorpair)
267 return tc;
270 return NULL;
273 static int
274 default_color_value(const char *envvar)
276 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
277 return COLOR_MAGENTA;
278 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
279 return COLOR_CYAN;
280 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
281 return COLOR_YELLOW;
282 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
283 return COLOR_GREEN;
284 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
285 return COLOR_MAGENTA;
286 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
287 return COLOR_MAGENTA;
288 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
289 return COLOR_CYAN;
290 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
291 return COLOR_GREEN;
292 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
293 return COLOR_GREEN;
294 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
295 return COLOR_CYAN;
296 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
297 return COLOR_YELLOW;
298 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
299 return COLOR_GREEN;
300 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
301 return COLOR_MAGENTA;
302 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
303 return COLOR_YELLOW;
304 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
305 return COLOR_CYAN;
307 return -1;
310 static int
311 get_color_value(const char *envvar)
313 const char *val = getenv(envvar);
315 if (val == NULL)
316 return default_color_value(envvar);
318 if (strcasecmp(val, "black") == 0)
319 return COLOR_BLACK;
320 if (strcasecmp(val, "red") == 0)
321 return COLOR_RED;
322 if (strcasecmp(val, "green") == 0)
323 return COLOR_GREEN;
324 if (strcasecmp(val, "yellow") == 0)
325 return COLOR_YELLOW;
326 if (strcasecmp(val, "blue") == 0)
327 return COLOR_BLUE;
328 if (strcasecmp(val, "magenta") == 0)
329 return COLOR_MAGENTA;
330 if (strcasecmp(val, "cyan") == 0)
331 return COLOR_CYAN;
332 if (strcasecmp(val, "white") == 0)
333 return COLOR_WHITE;
334 if (strcasecmp(val, "default") == 0)
335 return -1;
337 return default_color_value(envvar);
340 struct tog_diff_view_state {
341 struct got_object_id *id1, *id2;
342 const char *label1, *label2;
343 FILE *f, *f1, *f2;
344 int fd1, fd2;
345 int lineno;
346 int first_displayed_line;
347 int last_displayed_line;
348 int eof;
349 int diff_context;
350 int ignore_whitespace;
351 int force_text_diff;
352 struct got_repository *repo;
353 struct got_diff_line *lines;
354 size_t nlines;
355 int matched_line;
356 int selected_line;
358 /* passed from log or blame view; may be NULL */
359 struct tog_view *parent_view;
360 };
362 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
363 static volatile sig_atomic_t tog_thread_error;
365 struct tog_log_thread_args {
366 pthread_cond_t need_commits;
367 pthread_cond_t commit_loaded;
368 int commits_needed;
369 int load_all;
370 struct got_commit_graph *graph;
371 struct commit_queue *real_commits;
372 const char *in_repo_path;
373 struct got_object_id *start_id;
374 struct got_repository *repo;
375 int *pack_fds;
376 int log_complete;
377 sig_atomic_t *quit;
378 struct commit_queue_entry **first_displayed_entry;
379 struct commit_queue_entry **selected_entry;
380 int *searching;
381 int *search_next_done;
382 regex_t *regex;
383 int *limiting;
384 int limit_match;
385 regex_t *limit_regex;
386 struct commit_queue *limit_commits;
387 };
389 struct tog_log_view_state {
390 struct commit_queue *commits;
391 struct commit_queue_entry *first_displayed_entry;
392 struct commit_queue_entry *last_displayed_entry;
393 struct commit_queue_entry *selected_entry;
394 struct commit_queue real_commits;
395 int selected;
396 char *in_repo_path;
397 char *head_ref_name;
398 int log_branches;
399 struct got_repository *repo;
400 struct got_object_id *start_id;
401 sig_atomic_t quit;
402 pthread_t thread;
403 struct tog_log_thread_args thread_args;
404 struct commit_queue_entry *matched_entry;
405 struct commit_queue_entry *search_entry;
406 struct tog_colors colors;
407 int use_committer;
408 int limit_view;
409 regex_t limit_regex;
410 struct commit_queue limit_commits;
411 };
413 #define TOG_COLOR_DIFF_MINUS 1
414 #define TOG_COLOR_DIFF_PLUS 2
415 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
416 #define TOG_COLOR_DIFF_META 4
417 #define TOG_COLOR_TREE_SUBMODULE 5
418 #define TOG_COLOR_TREE_SYMLINK 6
419 #define TOG_COLOR_TREE_DIRECTORY 7
420 #define TOG_COLOR_TREE_EXECUTABLE 8
421 #define TOG_COLOR_COMMIT 9
422 #define TOG_COLOR_AUTHOR 10
423 #define TOG_COLOR_DATE 11
424 #define TOG_COLOR_REFS_HEADS 12
425 #define TOG_COLOR_REFS_TAGS 13
426 #define TOG_COLOR_REFS_REMOTES 14
427 #define TOG_COLOR_REFS_BACKUP 15
429 struct tog_blame_cb_args {
430 struct tog_blame_line *lines; /* one per line */
431 int nlines;
433 struct tog_view *view;
434 struct got_object_id *commit_id;
435 int *quit;
436 };
438 struct tog_blame_thread_args {
439 const char *path;
440 struct got_repository *repo;
441 struct tog_blame_cb_args *cb_args;
442 int *complete;
443 got_cancel_cb cancel_cb;
444 void *cancel_arg;
445 pthread_cond_t blame_complete;
446 };
448 struct tog_blame {
449 FILE *f;
450 off_t filesize;
451 struct tog_blame_line *lines;
452 int nlines;
453 off_t *line_offsets;
454 pthread_t thread;
455 struct tog_blame_thread_args thread_args;
456 struct tog_blame_cb_args cb_args;
457 const char *path;
458 int *pack_fds;
459 };
461 struct tog_blame_view_state {
462 int first_displayed_line;
463 int last_displayed_line;
464 int selected_line;
465 int last_diffed_line;
466 int blame_complete;
467 int eof;
468 int done;
469 struct got_object_id_queue blamed_commits;
470 struct got_object_qid *blamed_commit;
471 char *path;
472 struct got_repository *repo;
473 struct got_object_id *commit_id;
474 struct got_object_id *id_to_log;
475 struct tog_blame blame;
476 int matched_line;
477 struct tog_colors colors;
478 };
480 struct tog_parent_tree {
481 TAILQ_ENTRY(tog_parent_tree) entry;
482 struct got_tree_object *tree;
483 struct got_tree_entry *first_displayed_entry;
484 struct got_tree_entry *selected_entry;
485 int selected;
486 };
488 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
490 struct tog_tree_view_state {
491 char *tree_label;
492 struct got_object_id *commit_id;/* commit which this tree belongs to */
493 struct got_tree_object *root; /* the commit's root tree entry */
494 struct got_tree_object *tree; /* currently displayed (sub-)tree */
495 struct got_tree_entry *first_displayed_entry;
496 struct got_tree_entry *last_displayed_entry;
497 struct got_tree_entry *selected_entry;
498 int ndisplayed, selected, show_ids;
499 struct tog_parent_trees parents; /* parent trees of current sub-tree */
500 char *head_ref_name;
501 struct got_repository *repo;
502 struct got_tree_entry *matched_entry;
503 struct tog_colors colors;
504 };
506 struct tog_reflist_entry {
507 TAILQ_ENTRY(tog_reflist_entry) entry;
508 struct got_reference *ref;
509 int idx;
510 };
512 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
514 struct tog_ref_view_state {
515 struct tog_reflist_head refs;
516 struct tog_reflist_entry *first_displayed_entry;
517 struct tog_reflist_entry *last_displayed_entry;
518 struct tog_reflist_entry *selected_entry;
519 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
520 struct got_repository *repo;
521 struct tog_reflist_entry *matched_entry;
522 struct tog_colors colors;
523 };
525 struct tog_help_view_state {
526 FILE *f;
527 off_t *line_offsets;
528 size_t nlines;
529 int lineno;
530 int first_displayed_line;
531 int last_displayed_line;
532 int eof;
533 int matched_line;
534 int selected_line;
535 int all;
536 enum tog_keymap_type type;
537 };
539 #define GENERATE_HELP \
540 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
541 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
542 KEY_("k C-p Up", "Move cursor or page up one line"), \
543 KEY_("j C-n Down", "Move cursor or page down one line"), \
544 KEY_("C-b b PgUp", "Scroll the view up one page"), \
545 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
546 KEY_("C-u u", "Scroll the view up one half page"), \
547 KEY_("C-d d", "Scroll the view down one half page"), \
548 KEY_("g", "Go to line N (default: first line)"), \
549 KEY_("Home =", "Go to the first line"), \
550 KEY_("G", "Go to line N (default: last line)"), \
551 KEY_("End *", "Go to the last line"), \
552 KEY_("l Right", "Scroll the view right"), \
553 KEY_("h Left", "Scroll the view left"), \
554 KEY_("$", "Scroll view to the rightmost position"), \
555 KEY_("0", "Scroll view to the leftmost position"), \
556 KEY_("-", "Decrease size of the focussed split"), \
557 KEY_("+", "Increase size of the focussed split"), \
558 KEY_("Tab", "Switch focus between views"), \
559 KEY_("F", "Toggle fullscreen mode"), \
560 KEY_("S", "Switch split-screen layout"), \
561 KEY_("/", "Open prompt to enter search term"), \
562 KEY_("n", "Find next line/token matching the current search term"), \
563 KEY_("N", "Find previous line/token matching the current search term"),\
564 KEY_("q", "Quit the focussed view; Quit help screen"), \
565 KEY_("Q", "Quit tog"), \
567 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
568 KEY_("< ,", "Move cursor up one commit"), \
569 KEY_("> .", "Move cursor down one commit"), \
570 KEY_("Enter", "Open diff view of the selected commit"), \
571 KEY_("B", "Reload the log view and toggle display of merged commits"), \
572 KEY_("R", "Open ref view of all repository references"), \
573 KEY_("T", "Display tree view of the repository from the selected" \
574 " commit"), \
575 KEY_("@", "Toggle between displaying author and committer name"), \
576 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
577 KEY_("C-g Backspace", "Cancel current search or log operation"), \
578 KEY_("C-l", "Reload the log view with new commits in the repository"), \
580 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
581 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
582 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
583 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
584 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
585 " data"), \
586 KEY_("(", "Go to the previous file in the diff"), \
587 KEY_(")", "Go to the next file in the diff"), \
588 KEY_("{", "Go to the previous hunk in the diff"), \
589 KEY_("}", "Go to the next hunk in the diff"), \
590 KEY_("[", "Decrease the number of context lines"), \
591 KEY_("]", "Increase the number of context lines"), \
592 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
594 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
595 KEY_("Enter", "Display diff view of the selected line's commit"), \
596 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
597 KEY_("L", "Open log view for the currently selected annotated line"), \
598 KEY_("C", "Reload view with the previously blamed commit"), \
599 KEY_("c", "Reload view with the version of the file found in the" \
600 " selected line's commit"), \
601 KEY_("p", "Reload view with the version of the file found in the" \
602 " selected line's parent commit"), \
604 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
605 KEY_("Enter", "Enter selected directory or open blame view of the" \
606 " selected file"), \
607 KEY_("L", "Open log view for the selected entry"), \
608 KEY_("R", "Open ref view of all repository references"), \
609 KEY_("i", "Show object IDs for all tree entries"), \
610 KEY_("Backspace", "Return to the parent directory"), \
612 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
613 KEY_("Enter", "Display log view of the selected reference"), \
614 KEY_("T", "Display tree view of the selected reference"), \
615 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
616 KEY_("m", "Toggle display of last modified date for each reference"), \
617 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
618 KEY_("C-l", "Reload view with all repository references")
620 struct tog_key_map {
621 const char *keys;
622 const char *info;
623 enum tog_keymap_type type;
624 };
626 /* curses io for tog regress */
627 struct tog_io {
628 FILE *cin;
629 FILE *cout;
630 FILE *f;
631 FILE *sdump;
632 int wait_for_ui;
633 } tog_io;
634 static int using_mock_io;
636 #define TOG_KEY_SCRDUMP SHRT_MIN
638 /*
639 * We implement two types of views: parent views and child views.
641 * The 'Tab' key switches focus between a parent view and its child view.
642 * Child views are shown side-by-side to their parent view, provided
643 * there is enough screen estate.
645 * When a new view is opened from within a parent view, this new view
646 * becomes a child view of the parent view, replacing any existing child.
648 * When a new view is opened from within a child view, this new view
649 * becomes a parent view which will obscure the views below until the
650 * user quits the new parent view by typing 'q'.
652 * This list of views contains parent views only.
653 * Child views are only pointed to by their parent view.
654 */
655 TAILQ_HEAD(tog_view_list_head, tog_view);
657 struct tog_view {
658 TAILQ_ENTRY(tog_view) entry;
659 WINDOW *window;
660 PANEL *panel;
661 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
662 int resized_y, resized_x; /* begin_y/x based on user resizing */
663 int maxx, x; /* max column and current start column */
664 int lines, cols; /* copies of LINES and COLS */
665 int nscrolled, offset; /* lines scrolled and hsplit line offset */
666 int gline, hiline; /* navigate to and highlight this nG line */
667 int ch, count; /* current keymap and count prefix */
668 int resized; /* set when in a resize event */
669 int focussed; /* Only set on one parent or child view at a time. */
670 int dying;
671 struct tog_view *parent;
672 struct tog_view *child;
674 /*
675 * This flag is initially set on parent views when a new child view
676 * is created. It gets toggled when the 'Tab' key switches focus
677 * between parent and child.
678 * The flag indicates whether focus should be passed on to our child
679 * view if this parent view gets picked for focus after another parent
680 * view was closed. This prevents child views from losing focus in such
681 * situations.
682 */
683 int focus_child;
685 enum tog_view_mode mode;
686 /* type-specific state */
687 enum tog_view_type type;
688 union {
689 struct tog_diff_view_state diff;
690 struct tog_log_view_state log;
691 struct tog_blame_view_state blame;
692 struct tog_tree_view_state tree;
693 struct tog_ref_view_state ref;
694 struct tog_help_view_state help;
695 } state;
697 const struct got_error *(*show)(struct tog_view *);
698 const struct got_error *(*input)(struct tog_view **,
699 struct tog_view *, int);
700 const struct got_error *(*reset)(struct tog_view *);
701 const struct got_error *(*resize)(struct tog_view *, int);
702 const struct got_error *(*close)(struct tog_view *);
704 const struct got_error *(*search_start)(struct tog_view *);
705 const struct got_error *(*search_next)(struct tog_view *);
706 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
707 int **, int **, int **, int **);
708 int search_started;
709 int searching;
710 #define TOG_SEARCH_FORWARD 1
711 #define TOG_SEARCH_BACKWARD 2
712 int search_next_done;
713 #define TOG_SEARCH_HAVE_MORE 1
714 #define TOG_SEARCH_NO_MORE 2
715 #define TOG_SEARCH_HAVE_NONE 3
716 regex_t regex;
717 regmatch_t regmatch;
718 const char *action;
719 };
721 static const struct got_error *open_diff_view(struct tog_view *,
722 struct got_object_id *, struct got_object_id *,
723 const char *, const char *, int, int, int, struct tog_view *,
724 struct got_repository *);
725 static const struct got_error *show_diff_view(struct tog_view *);
726 static const struct got_error *input_diff_view(struct tog_view **,
727 struct tog_view *, int);
728 static const struct got_error *reset_diff_view(struct tog_view *);
729 static const struct got_error* close_diff_view(struct tog_view *);
730 static const struct got_error *search_start_diff_view(struct tog_view *);
731 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
732 size_t *, int **, int **, int **, int **);
733 static const struct got_error *search_next_view_match(struct tog_view *);
735 static const struct got_error *open_log_view(struct tog_view *,
736 struct got_object_id *, struct got_repository *,
737 const char *, const char *, int);
738 static const struct got_error * show_log_view(struct tog_view *);
739 static const struct got_error *input_log_view(struct tog_view **,
740 struct tog_view *, int);
741 static const struct got_error *resize_log_view(struct tog_view *, int);
742 static const struct got_error *close_log_view(struct tog_view *);
743 static const struct got_error *search_start_log_view(struct tog_view *);
744 static const struct got_error *search_next_log_view(struct tog_view *);
746 static const struct got_error *open_blame_view(struct tog_view *, char *,
747 struct got_object_id *, struct got_repository *);
748 static const struct got_error *show_blame_view(struct tog_view *);
749 static const struct got_error *input_blame_view(struct tog_view **,
750 struct tog_view *, int);
751 static const struct got_error *reset_blame_view(struct tog_view *);
752 static const struct got_error *close_blame_view(struct tog_view *);
753 static const struct got_error *search_start_blame_view(struct tog_view *);
754 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
755 size_t *, int **, int **, int **, int **);
757 static const struct got_error *open_tree_view(struct tog_view *,
758 struct got_object_id *, const char *, struct got_repository *);
759 static const struct got_error *show_tree_view(struct tog_view *);
760 static const struct got_error *input_tree_view(struct tog_view **,
761 struct tog_view *, int);
762 static const struct got_error *close_tree_view(struct tog_view *);
763 static const struct got_error *search_start_tree_view(struct tog_view *);
764 static const struct got_error *search_next_tree_view(struct tog_view *);
766 static const struct got_error *open_ref_view(struct tog_view *,
767 struct got_repository *);
768 static const struct got_error *show_ref_view(struct tog_view *);
769 static const struct got_error *input_ref_view(struct tog_view **,
770 struct tog_view *, int);
771 static const struct got_error *close_ref_view(struct tog_view *);
772 static const struct got_error *search_start_ref_view(struct tog_view *);
773 static const struct got_error *search_next_ref_view(struct tog_view *);
775 static const struct got_error *open_help_view(struct tog_view *,
776 struct tog_view *);
777 static const struct got_error *show_help_view(struct tog_view *);
778 static const struct got_error *input_help_view(struct tog_view **,
779 struct tog_view *, int);
780 static const struct got_error *reset_help_view(struct tog_view *);
781 static const struct got_error* close_help_view(struct tog_view *);
782 static const struct got_error *search_start_help_view(struct tog_view *);
783 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
784 size_t *, int **, int **, int **, int **);
786 static volatile sig_atomic_t tog_sigwinch_received;
787 static volatile sig_atomic_t tog_sigpipe_received;
788 static volatile sig_atomic_t tog_sigcont_received;
789 static volatile sig_atomic_t tog_sigint_received;
790 static volatile sig_atomic_t tog_sigterm_received;
792 static void
793 tog_sigwinch(int signo)
795 tog_sigwinch_received = 1;
798 static void
799 tog_sigpipe(int signo)
801 tog_sigpipe_received = 1;
804 static void
805 tog_sigcont(int signo)
807 tog_sigcont_received = 1;
810 static void
811 tog_sigint(int signo)
813 tog_sigint_received = 1;
816 static void
817 tog_sigterm(int signo)
819 tog_sigterm_received = 1;
822 static int
823 tog_fatal_signal_received(void)
825 return (tog_sigpipe_received ||
826 tog_sigint_received || tog_sigterm_received);
829 static const struct got_error *
830 view_close(struct tog_view *view)
832 const struct got_error *err = NULL, *child_err = NULL;
834 if (view->child) {
835 child_err = view_close(view->child);
836 view->child = NULL;
838 if (view->close)
839 err = view->close(view);
840 if (view->panel)
841 del_panel(view->panel);
842 if (view->window)
843 delwin(view->window);
844 free(view);
845 return err ? err : child_err;
848 static struct tog_view *
849 view_open(int nlines, int ncols, int begin_y, int begin_x,
850 enum tog_view_type type)
852 struct tog_view *view = calloc(1, sizeof(*view));
854 if (view == NULL)
855 return NULL;
857 view->type = type;
858 view->lines = LINES;
859 view->cols = COLS;
860 view->nlines = nlines ? nlines : LINES - begin_y;
861 view->ncols = ncols ? ncols : COLS - begin_x;
862 view->begin_y = begin_y;
863 view->begin_x = begin_x;
864 view->window = newwin(nlines, ncols, begin_y, begin_x);
865 if (view->window == NULL) {
866 view_close(view);
867 return NULL;
869 view->panel = new_panel(view->window);
870 if (view->panel == NULL ||
871 set_panel_userptr(view->panel, view) != OK) {
872 view_close(view);
873 return NULL;
876 keypad(view->window, TRUE);
877 return view;
880 static int
881 view_split_begin_x(int begin_x)
883 if (begin_x > 0 || COLS < 120)
884 return 0;
885 return (COLS - MAX(COLS / 2, 80));
888 /* XXX Stub till we decide what to do. */
889 static int
890 view_split_begin_y(int lines)
892 return lines * HSPLIT_SCALE;
895 static const struct got_error *view_resize(struct tog_view *);
897 static const struct got_error *
898 view_splitscreen(struct tog_view *view)
900 const struct got_error *err = NULL;
902 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
903 if (view->resized_y && view->resized_y < view->lines)
904 view->begin_y = view->resized_y;
905 else
906 view->begin_y = view_split_begin_y(view->nlines);
907 view->begin_x = 0;
908 } else if (!view->resized) {
909 if (view->resized_x && view->resized_x < view->cols - 1 &&
910 view->cols > 119)
911 view->begin_x = view->resized_x;
912 else
913 view->begin_x = view_split_begin_x(0);
914 view->begin_y = 0;
916 view->nlines = LINES - view->begin_y;
917 view->ncols = COLS - view->begin_x;
918 view->lines = LINES;
919 view->cols = COLS;
920 err = view_resize(view);
921 if (err)
922 return err;
924 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
925 view->parent->nlines = view->begin_y;
927 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
928 return got_error_from_errno("mvwin");
930 return NULL;
933 static const struct got_error *
934 view_fullscreen(struct tog_view *view)
936 const struct got_error *err = NULL;
938 view->begin_x = 0;
939 view->begin_y = view->resized ? view->begin_y : 0;
940 view->nlines = view->resized ? view->nlines : LINES;
941 view->ncols = COLS;
942 view->lines = LINES;
943 view->cols = COLS;
944 err = view_resize(view);
945 if (err)
946 return err;
948 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
949 return got_error_from_errno("mvwin");
951 return NULL;
954 static int
955 view_is_parent_view(struct tog_view *view)
957 return view->parent == NULL;
960 static int
961 view_is_splitscreen(struct tog_view *view)
963 return view->begin_x > 0 || view->begin_y > 0;
966 static int
967 view_is_fullscreen(struct tog_view *view)
969 return view->nlines == LINES && view->ncols == COLS;
972 static int
973 view_is_hsplit_top(struct tog_view *view)
975 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
976 view_is_splitscreen(view->child);
979 static void
980 view_border(struct tog_view *view)
982 PANEL *panel;
983 const struct tog_view *view_above;
985 if (view->parent)
986 return view_border(view->parent);
988 panel = panel_above(view->panel);
989 if (panel == NULL)
990 return;
992 view_above = panel_userptr(panel);
993 if (view->mode == TOG_VIEW_SPLIT_HRZN)
994 mvwhline(view->window, view_above->begin_y - 1,
995 view->begin_x, ACS_HLINE, view->ncols);
996 else
997 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
998 ACS_VLINE, view->nlines);
1001 static const struct got_error *view_init_hsplit(struct tog_view *, int);
1002 static const struct got_error *request_log_commits(struct tog_view *);
1003 static const struct got_error *offset_selection_down(struct tog_view *);
1004 static void offset_selection_up(struct tog_view *);
1005 static void view_get_split(struct tog_view *, int *, int *);
1007 static const struct got_error *
1008 view_resize(struct tog_view *view)
1010 const struct got_error *err = NULL;
1011 int dif, nlines, ncols;
1013 dif = LINES - view->lines; /* line difference */
1015 if (view->lines > LINES)
1016 nlines = view->nlines - (view->lines - LINES);
1017 else
1018 nlines = view->nlines + (LINES - view->lines);
1019 if (view->cols > COLS)
1020 ncols = view->ncols - (view->cols - COLS);
1021 else
1022 ncols = view->ncols + (COLS - view->cols);
1024 if (view->child) {
1025 int hs = view->child->begin_y;
1027 if (!view_is_fullscreen(view))
1028 view->child->begin_x = view_split_begin_x(view->begin_x);
1029 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1030 view->child->begin_x == 0) {
1031 ncols = COLS;
1033 view_fullscreen(view->child);
1034 if (view->child->focussed)
1035 show_panel(view->child->panel);
1036 else
1037 show_panel(view->panel);
1038 } else {
1039 ncols = view->child->begin_x;
1041 view_splitscreen(view->child);
1042 show_panel(view->child->panel);
1045 * XXX This is ugly and needs to be moved into the above
1046 * logic but "works" for now and my attempts at moving it
1047 * break either 'tab' or 'F' key maps in horizontal splits.
1049 if (hs) {
1050 err = view_splitscreen(view->child);
1051 if (err)
1052 return err;
1053 if (dif < 0) { /* top split decreased */
1054 err = offset_selection_down(view);
1055 if (err)
1056 return err;
1058 view_border(view);
1059 update_panels();
1060 doupdate();
1061 show_panel(view->child->panel);
1062 nlines = view->nlines;
1064 } else if (view->parent == NULL)
1065 ncols = COLS;
1067 if (view->resize && dif > 0) {
1068 err = view->resize(view, dif);
1069 if (err)
1070 return err;
1073 if (wresize(view->window, nlines, ncols) == ERR)
1074 return got_error_from_errno("wresize");
1075 if (replace_panel(view->panel, view->window) == ERR)
1076 return got_error_from_errno("replace_panel");
1077 wclear(view->window);
1079 view->nlines = nlines;
1080 view->ncols = ncols;
1081 view->lines = LINES;
1082 view->cols = COLS;
1084 return NULL;
1087 static const struct got_error *
1088 resize_log_view(struct tog_view *view, int increase)
1090 struct tog_log_view_state *s = &view->state.log;
1091 const struct got_error *err = NULL;
1092 int n = 0;
1094 if (s->selected_entry)
1095 n = s->selected_entry->idx + view->lines - s->selected;
1098 * Request commits to account for the increased
1099 * height so we have enough to populate the view.
1101 if (s->commits->ncommits < n) {
1102 view->nscrolled = n - s->commits->ncommits + increase + 1;
1103 err = request_log_commits(view);
1106 return err;
1109 static void
1110 view_adjust_offset(struct tog_view *view, int n)
1112 if (n == 0)
1113 return;
1115 if (view->parent && view->parent->offset) {
1116 if (view->parent->offset + n >= 0)
1117 view->parent->offset += n;
1118 else
1119 view->parent->offset = 0;
1120 } else if (view->offset) {
1121 if (view->offset - n >= 0)
1122 view->offset -= n;
1123 else
1124 view->offset = 0;
1128 static const struct got_error *
1129 view_resize_split(struct tog_view *view, int resize)
1131 const struct got_error *err = NULL;
1132 struct tog_view *v = NULL;
1134 if (view->parent)
1135 v = view->parent;
1136 else
1137 v = view;
1139 if (!v->child || !view_is_splitscreen(v->child))
1140 return NULL;
1142 v->resized = v->child->resized = resize; /* lock for resize event */
1144 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1145 if (v->child->resized_y)
1146 v->child->begin_y = v->child->resized_y;
1147 if (view->parent)
1148 v->child->begin_y -= resize;
1149 else
1150 v->child->begin_y += resize;
1151 if (v->child->begin_y < 3) {
1152 view->count = 0;
1153 v->child->begin_y = 3;
1154 } else if (v->child->begin_y > LINES - 1) {
1155 view->count = 0;
1156 v->child->begin_y = LINES - 1;
1158 v->ncols = COLS;
1159 v->child->ncols = COLS;
1160 view_adjust_offset(view, resize);
1161 err = view_init_hsplit(v, v->child->begin_y);
1162 if (err)
1163 return err;
1164 v->child->resized_y = v->child->begin_y;
1165 } else {
1166 if (v->child->resized_x)
1167 v->child->begin_x = v->child->resized_x;
1168 if (view->parent)
1169 v->child->begin_x -= resize;
1170 else
1171 v->child->begin_x += resize;
1172 if (v->child->begin_x < 11) {
1173 view->count = 0;
1174 v->child->begin_x = 11;
1175 } else if (v->child->begin_x > COLS - 1) {
1176 view->count = 0;
1177 v->child->begin_x = COLS - 1;
1179 v->child->resized_x = v->child->begin_x;
1182 v->child->mode = v->mode;
1183 v->child->nlines = v->lines - v->child->begin_y;
1184 v->child->ncols = v->cols - v->child->begin_x;
1185 v->focus_child = 1;
1187 err = view_fullscreen(v);
1188 if (err)
1189 return err;
1190 err = view_splitscreen(v->child);
1191 if (err)
1192 return err;
1194 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1195 err = offset_selection_down(v->child);
1196 if (err)
1197 return err;
1200 if (v->resize)
1201 err = v->resize(v, 0);
1202 else if (v->child->resize)
1203 err = v->child->resize(v->child, 0);
1205 v->resized = v->child->resized = 0;
1207 return err;
1210 static void
1211 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1213 struct tog_view *v = src->child ? src->child : src;
1215 dst->resized_x = v->resized_x;
1216 dst->resized_y = v->resized_y;
1219 static const struct got_error *
1220 view_close_child(struct tog_view *view)
1222 const struct got_error *err = NULL;
1224 if (view->child == NULL)
1225 return NULL;
1227 err = view_close(view->child);
1228 view->child = NULL;
1229 return err;
1232 static const struct got_error *
1233 view_set_child(struct tog_view *view, struct tog_view *child)
1235 const struct got_error *err = NULL;
1237 view->child = child;
1238 child->parent = view;
1240 err = view_resize(view);
1241 if (err)
1242 return err;
1244 if (view->child->resized_x || view->child->resized_y)
1245 err = view_resize_split(view, 0);
1247 return err;
1250 static const struct got_error *view_dispatch_request(struct tog_view **,
1251 struct tog_view *, enum tog_view_type, int, int);
1253 static const struct got_error *
1254 view_request_new(struct tog_view **requested, struct tog_view *view,
1255 enum tog_view_type request)
1257 struct tog_view *new_view = NULL;
1258 const struct got_error *err;
1259 int y = 0, x = 0;
1261 *requested = NULL;
1263 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1264 view_get_split(view, &y, &x);
1266 err = view_dispatch_request(&new_view, view, request, y, x);
1267 if (err)
1268 return err;
1270 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1271 request != TOG_VIEW_HELP) {
1272 err = view_init_hsplit(view, y);
1273 if (err)
1274 return err;
1277 view->focussed = 0;
1278 new_view->focussed = 1;
1279 new_view->mode = view->mode;
1280 new_view->nlines = request == TOG_VIEW_HELP ?
1281 view->lines : view->lines - y;
1283 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1284 view_transfer_size(new_view, view);
1285 err = view_close_child(view);
1286 if (err)
1287 return err;
1288 err = view_set_child(view, new_view);
1289 if (err)
1290 return err;
1291 view->focus_child = 1;
1292 } else
1293 *requested = new_view;
1295 return NULL;
1298 static void
1299 tog_resizeterm(void)
1301 int cols, lines;
1302 struct winsize size;
1304 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1305 cols = 80; /* Default */
1306 lines = 24;
1307 } else {
1308 cols = size.ws_col;
1309 lines = size.ws_row;
1311 resize_term(lines, cols);
1314 static const struct got_error *
1315 view_search_start(struct tog_view *view, int fast_refresh)
1317 const struct got_error *err = NULL;
1318 struct tog_view *v = view;
1319 char pattern[1024];
1320 int ret;
1322 if (view->search_started) {
1323 regfree(&view->regex);
1324 view->searching = 0;
1325 memset(&view->regmatch, 0, sizeof(view->regmatch));
1327 view->search_started = 0;
1329 if (view->nlines < 1)
1330 return NULL;
1332 if (view_is_hsplit_top(view))
1333 v = view->child;
1334 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1335 v = view->parent;
1337 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1338 wclrtoeol(v->window);
1340 nodelay(v->window, FALSE); /* block for search term input */
1341 nocbreak();
1342 echo();
1343 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1344 wrefresh(v->window);
1345 cbreak();
1346 noecho();
1347 nodelay(v->window, TRUE);
1348 if (!fast_refresh && !using_mock_io)
1349 halfdelay(10);
1350 if (ret == ERR)
1351 return NULL;
1353 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1354 err = view->search_start(view);
1355 if (err) {
1356 regfree(&view->regex);
1357 return err;
1359 view->search_started = 1;
1360 view->searching = TOG_SEARCH_FORWARD;
1361 view->search_next_done = 0;
1362 view->search_next(view);
1365 return NULL;
1368 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1369 static const struct got_error *
1370 switch_split(struct tog_view *view)
1372 const struct got_error *err = NULL;
1373 struct tog_view *v = NULL;
1375 if (view->parent)
1376 v = view->parent;
1377 else
1378 v = view;
1380 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1381 v->mode = TOG_VIEW_SPLIT_VERT;
1382 else
1383 v->mode = TOG_VIEW_SPLIT_HRZN;
1385 if (!v->child)
1386 return NULL;
1387 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1388 v->mode = TOG_VIEW_SPLIT_NONE;
1390 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1391 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1392 v->child->begin_y = v->child->resized_y;
1393 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1394 v->child->begin_x = v->child->resized_x;
1397 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1398 v->ncols = COLS;
1399 v->child->ncols = COLS;
1400 v->child->nscrolled = LINES - v->child->nlines;
1402 err = view_init_hsplit(v, v->child->begin_y);
1403 if (err)
1404 return err;
1406 v->child->mode = v->mode;
1407 v->child->nlines = v->lines - v->child->begin_y;
1408 v->focus_child = 1;
1410 err = view_fullscreen(v);
1411 if (err)
1412 return err;
1413 err = view_splitscreen(v->child);
1414 if (err)
1415 return err;
1417 if (v->mode == TOG_VIEW_SPLIT_NONE)
1418 v->mode = TOG_VIEW_SPLIT_VERT;
1419 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1420 err = offset_selection_down(v);
1421 if (err)
1422 return err;
1423 err = offset_selection_down(v->child);
1424 if (err)
1425 return err;
1426 } else {
1427 offset_selection_up(v);
1428 offset_selection_up(v->child);
1430 if (v->resize)
1431 err = v->resize(v, 0);
1432 else if (v->child->resize)
1433 err = v->child->resize(v->child, 0);
1435 return err;
1439 * Strip trailing whitespace from str starting at byte *n;
1440 * if *n < 0, use strlen(str). Return new str length in *n.
1442 static void
1443 strip_trailing_ws(char *str, int *n)
1445 size_t x = *n;
1447 if (str == NULL || *str == '\0')
1448 return;
1450 if (x < 0)
1451 x = strlen(str);
1453 while (x-- > 0 && isspace((unsigned char)str[x]))
1454 str[x] = '\0';
1456 *n = x + 1;
1460 * Extract visible substring of line y from the curses screen
1461 * and strip trailing whitespace. If vline is set, overwrite
1462 * line[vline] with '|' because the ACS_VLINE character is
1463 * written out as 'x'. Write the line to file f.
1465 static const struct got_error *
1466 view_write_line(FILE *f, int y, int vline)
1468 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1469 int r, w;
1471 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1472 if (r == ERR)
1473 return got_error_fmt(GOT_ERR_RANGE,
1474 "failed to extract line %d", y);
1477 * In some views, lines are padded with blanks to COLS width.
1478 * Strip them so we can diff without the -b flag when testing.
1480 strip_trailing_ws(line, &r);
1482 if (vline > 0)
1483 line[vline] = '|';
1485 w = fprintf(f, "%s\n", line);
1486 if (w != r + 1) /* \n */
1487 return got_ferror(f, GOT_ERR_IO);
1489 return NULL;
1493 * Capture the visible curses screen by writing each line to the
1494 * file at the path set via the TOG_SCR_DUMP environment variable.
1496 static const struct got_error *
1497 screendump(struct tog_view *view)
1499 const struct got_error *err;
1500 int i;
1502 err = got_opentemp_truncate(tog_io.sdump);
1503 if (err)
1504 return err;
1506 if ((view->child && view->child->begin_x) ||
1507 (view->parent && view->begin_x)) {
1508 int ncols = view->child ? view->ncols : view->parent->ncols;
1510 /* vertical splitscreen */
1511 for (i = 0; i < view->nlines; ++i) {
1512 err = view_write_line(tog_io.sdump, i, ncols - 1);
1513 if (err)
1514 goto done;
1516 } else {
1517 int hline = 0;
1519 /* fullscreen or horizontal splitscreen */
1520 if ((view->child && view->child->begin_y) ||
1521 (view->parent && view->begin_y)) /* hsplit */
1522 hline = view->child ?
1523 view->child->begin_y : view->begin_y;
1525 for (i = 0; i < view->lines; i++) {
1526 if (hline && i == hline - 1) {
1527 int c;
1529 /* ACS_HLINE writes out as 'q', overwrite it */
1530 for (c = 0; c < view->cols; ++c)
1531 fputc('-', tog_io.sdump);
1532 fputc('\n', tog_io.sdump);
1533 continue;
1536 err = view_write_line(tog_io.sdump, i, 0);
1537 if (err)
1538 goto done;
1542 done:
1543 return err;
1547 * Compute view->count from numeric input. Assign total to view->count and
1548 * return first non-numeric key entered.
1550 static int
1551 get_compound_key(struct tog_view *view, int c)
1553 struct tog_view *v = view;
1554 int x, n = 0;
1556 if (view_is_hsplit_top(view))
1557 v = view->child;
1558 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1559 v = view->parent;
1561 view->count = 0;
1562 cbreak(); /* block for input */
1563 nodelay(view->window, FALSE);
1564 wmove(v->window, v->nlines - 1, 0);
1565 wclrtoeol(v->window);
1566 waddch(v->window, ':');
1568 do {
1569 x = getcurx(v->window);
1570 if (x != ERR && x < view->ncols) {
1571 waddch(v->window, c);
1572 wrefresh(v->window);
1576 * Don't overflow. Max valid request should be the greatest
1577 * between the longest and total lines; cap at 10 million.
1579 if (n >= 9999999)
1580 n = 9999999;
1581 else
1582 n = n * 10 + (c - '0');
1583 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1585 if (c == 'G' || c == 'g') { /* nG key map */
1586 view->gline = view->hiline = n;
1587 n = 0;
1588 c = 0;
1591 /* Massage excessive or inapplicable values at the input handler. */
1592 view->count = n;
1594 return c;
1597 static void
1598 action_report(struct tog_view *view)
1600 struct tog_view *v = view;
1602 if (view_is_hsplit_top(view))
1603 v = view->child;
1604 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1605 v = view->parent;
1607 wmove(v->window, v->nlines - 1, 0);
1608 wclrtoeol(v->window);
1609 wprintw(v->window, ":%s", view->action);
1610 wrefresh(v->window);
1613 * Clear action status report. Only clear in blame view
1614 * once annotating is complete, otherwise it's too fast.
1616 if (view->type == TOG_VIEW_BLAME) {
1617 if (view->state.blame.blame_complete)
1618 view->action = NULL;
1619 } else
1620 view->action = NULL;
1624 * Read the next line from the test script and assign
1625 * key instruction to *ch. If at EOF, set the *done flag.
1627 static const struct got_error *
1628 tog_read_script_key(FILE *script, struct tog_view *view, int *ch, int *done)
1630 const struct got_error *err = NULL;
1631 char *line = NULL;
1632 size_t linesz = 0;
1634 if (view->count && --view->count) {
1635 *ch = view->ch;
1636 return NULL;
1637 } else
1638 *ch = -1;
1640 if (getline(&line, &linesz, script) == -1) {
1641 if (feof(script)) {
1642 *done = 1;
1643 goto done;
1644 } else {
1645 err = got_ferror(script, GOT_ERR_IO);
1646 goto done;
1650 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1651 tog_io.wait_for_ui = 1;
1652 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1653 *ch = KEY_ENTER;
1654 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1655 *ch = KEY_RIGHT;
1656 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1657 *ch = KEY_LEFT;
1658 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1659 *ch = KEY_DOWN;
1660 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1661 *ch = KEY_UP;
1662 else if (strncasecmp(line, "TAB", 3) == 0)
1663 *ch = '\t';
1664 else if (strncasecmp(line, "SCREENDUMP", 10) == 0)
1665 *ch = TOG_KEY_SCRDUMP;
1666 else if (isdigit((unsigned char)*line)) {
1667 char *t = line;
1669 while (isdigit((unsigned char)*t))
1670 ++t;
1671 view->ch = *ch = *t;
1672 *t = '\0';
1673 /* ignore error, view->count is 0 if instruction is invalid */
1674 view->count = strtonum(line, 0, INT_MAX, NULL);
1675 } else
1676 *ch = *line;
1678 done:
1679 free(line);
1680 return err;
1683 static const struct got_error *
1684 view_input(struct tog_view **new, int *done, struct tog_view *view,
1685 struct tog_view_list_head *views, int fast_refresh)
1687 const struct got_error *err = NULL;
1688 struct tog_view *v;
1689 int ch, errcode;
1691 *new = NULL;
1693 if (view->action)
1694 action_report(view);
1696 /* Clear "no matches" indicator. */
1697 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1698 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1699 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1700 view->count = 0;
1703 if (view->searching && !view->search_next_done) {
1704 errcode = pthread_mutex_unlock(&tog_mutex);
1705 if (errcode)
1706 return got_error_set_errno(errcode,
1707 "pthread_mutex_unlock");
1708 sched_yield();
1709 errcode = pthread_mutex_lock(&tog_mutex);
1710 if (errcode)
1711 return got_error_set_errno(errcode,
1712 "pthread_mutex_lock");
1713 view->search_next(view);
1714 return NULL;
1717 /* Allow threads to make progress while we are waiting for input. */
1718 errcode = pthread_mutex_unlock(&tog_mutex);
1719 if (errcode)
1720 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1722 if (using_mock_io) {
1723 err = tog_read_script_key(tog_io.f, view, &ch, done);
1724 if (err) {
1725 errcode = pthread_mutex_lock(&tog_mutex);
1726 return err;
1728 } else if (view->count && --view->count) {
1729 cbreak();
1730 nodelay(view->window, TRUE);
1731 ch = wgetch(view->window);
1732 /* let C-g or backspace abort unfinished count */
1733 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1734 view->count = 0;
1735 else
1736 ch = view->ch;
1737 } else {
1738 ch = wgetch(view->window);
1739 if (ch >= '1' && ch <= '9')
1740 view->ch = ch = get_compound_key(view, ch);
1742 if (view->hiline && ch != ERR && ch != 0)
1743 view->hiline = 0; /* key pressed, clear line highlight */
1744 nodelay(view->window, TRUE);
1745 errcode = pthread_mutex_lock(&tog_mutex);
1746 if (errcode)
1747 return got_error_set_errno(errcode, "pthread_mutex_lock");
1749 if (tog_sigwinch_received || tog_sigcont_received) {
1750 tog_resizeterm();
1751 tog_sigwinch_received = 0;
1752 tog_sigcont_received = 0;
1753 TAILQ_FOREACH(v, views, entry) {
1754 err = view_resize(v);
1755 if (err)
1756 return err;
1757 err = v->input(new, v, KEY_RESIZE);
1758 if (err)
1759 return err;
1760 if (v->child) {
1761 err = view_resize(v->child);
1762 if (err)
1763 return err;
1764 err = v->child->input(new, v->child,
1765 KEY_RESIZE);
1766 if (err)
1767 return err;
1768 if (v->child->resized_x || v->child->resized_y) {
1769 err = view_resize_split(v, 0);
1770 if (err)
1771 return err;
1777 switch (ch) {
1778 case '?':
1779 case 'H':
1780 case KEY_F(1):
1781 if (view->type == TOG_VIEW_HELP)
1782 err = view->reset(view);
1783 else
1784 err = view_request_new(new, view, TOG_VIEW_HELP);
1785 break;
1786 case '\t':
1787 view->count = 0;
1788 if (view->child) {
1789 view->focussed = 0;
1790 view->child->focussed = 1;
1791 view->focus_child = 1;
1792 } else if (view->parent) {
1793 view->focussed = 0;
1794 view->parent->focussed = 1;
1795 view->parent->focus_child = 0;
1796 if (!view_is_splitscreen(view)) {
1797 if (view->parent->resize) {
1798 err = view->parent->resize(view->parent,
1799 0);
1800 if (err)
1801 return err;
1803 offset_selection_up(view->parent);
1804 err = view_fullscreen(view->parent);
1805 if (err)
1806 return err;
1809 break;
1810 case 'q':
1811 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1812 if (view->parent->resize) {
1813 /* might need more commits to fill fullscreen */
1814 err = view->parent->resize(view->parent, 0);
1815 if (err)
1816 break;
1818 offset_selection_up(view->parent);
1820 err = view->input(new, view, ch);
1821 view->dying = 1;
1822 break;
1823 case 'Q':
1824 *done = 1;
1825 break;
1826 case 'F':
1827 view->count = 0;
1828 if (view_is_parent_view(view)) {
1829 if (view->child == NULL)
1830 break;
1831 if (view_is_splitscreen(view->child)) {
1832 view->focussed = 0;
1833 view->child->focussed = 1;
1834 err = view_fullscreen(view->child);
1835 } else {
1836 err = view_splitscreen(view->child);
1837 if (!err)
1838 err = view_resize_split(view, 0);
1840 if (err)
1841 break;
1842 err = view->child->input(new, view->child,
1843 KEY_RESIZE);
1844 } else {
1845 if (view_is_splitscreen(view)) {
1846 view->parent->focussed = 0;
1847 view->focussed = 1;
1848 err = view_fullscreen(view);
1849 } else {
1850 err = view_splitscreen(view);
1851 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1852 err = view_resize(view->parent);
1853 if (!err)
1854 err = view_resize_split(view, 0);
1856 if (err)
1857 break;
1858 err = view->input(new, view, KEY_RESIZE);
1860 if (err)
1861 break;
1862 if (view->resize) {
1863 err = view->resize(view, 0);
1864 if (err)
1865 break;
1867 if (view->parent) {
1868 if (view->parent->resize) {
1869 err = view->parent->resize(view->parent, 0);
1870 if (err != NULL)
1871 break;
1873 err = offset_selection_down(view->parent);
1874 if (err != NULL)
1875 break;
1877 err = offset_selection_down(view);
1878 break;
1879 case 'S':
1880 view->count = 0;
1881 err = switch_split(view);
1882 break;
1883 case '-':
1884 err = view_resize_split(view, -1);
1885 break;
1886 case '+':
1887 err = view_resize_split(view, 1);
1888 break;
1889 case KEY_RESIZE:
1890 break;
1891 case '/':
1892 view->count = 0;
1893 if (view->search_start)
1894 view_search_start(view, fast_refresh);
1895 else
1896 err = view->input(new, view, ch);
1897 break;
1898 case 'N':
1899 case 'n':
1900 if (view->search_started && view->search_next) {
1901 view->searching = (ch == 'n' ?
1902 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1903 view->search_next_done = 0;
1904 view->search_next(view);
1905 } else
1906 err = view->input(new, view, ch);
1907 break;
1908 case 'A':
1909 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1910 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1911 view->action = "Patience diff algorithm";
1912 } else {
1913 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1914 view->action = "Myers diff algorithm";
1916 TAILQ_FOREACH(v, views, entry) {
1917 if (v->reset) {
1918 err = v->reset(v);
1919 if (err)
1920 return err;
1922 if (v->child && v->child->reset) {
1923 err = v->child->reset(v->child);
1924 if (err)
1925 return err;
1928 break;
1929 case TOG_KEY_SCRDUMP:
1930 err = screendump(view);
1931 break;
1932 default:
1933 err = view->input(new, view, ch);
1934 break;
1937 return err;
1940 static int
1941 view_needs_focus_indication(struct tog_view *view)
1943 if (view_is_parent_view(view)) {
1944 if (view->child == NULL || view->child->focussed)
1945 return 0;
1946 if (!view_is_splitscreen(view->child))
1947 return 0;
1948 } else if (!view_is_splitscreen(view))
1949 return 0;
1951 return view->focussed;
1954 static const struct got_error *
1955 tog_io_close(void)
1957 const struct got_error *err = NULL;
1959 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1960 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1961 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1962 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1963 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1964 err = got_ferror(tog_io.f, GOT_ERR_IO);
1965 if (tog_io.sdump && fclose(tog_io.sdump) == EOF && err == NULL)
1966 err = got_ferror(tog_io.sdump, GOT_ERR_IO);
1968 return err;
1971 static const struct got_error *
1972 view_loop(struct tog_view *view)
1974 const struct got_error *err = NULL;
1975 struct tog_view_list_head views;
1976 struct tog_view *new_view;
1977 char *mode;
1978 int fast_refresh = 10;
1979 int done = 0, errcode;
1981 mode = getenv("TOG_VIEW_SPLIT_MODE");
1982 if (!mode || !(*mode == 'h' || *mode == 'H'))
1983 view->mode = TOG_VIEW_SPLIT_VERT;
1984 else
1985 view->mode = TOG_VIEW_SPLIT_HRZN;
1987 errcode = pthread_mutex_lock(&tog_mutex);
1988 if (errcode)
1989 return got_error_set_errno(errcode, "pthread_mutex_lock");
1991 TAILQ_INIT(&views);
1992 TAILQ_INSERT_HEAD(&views, view, entry);
1994 view->focussed = 1;
1995 err = view->show(view);
1996 if (err)
1997 return err;
1998 update_panels();
1999 doupdate();
2000 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
2001 !tog_fatal_signal_received()) {
2002 /* Refresh fast during initialization, then become slower. */
2003 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
2004 halfdelay(10); /* switch to once per second */
2006 err = view_input(&new_view, &done, view, &views, fast_refresh);
2007 if (err)
2008 break;
2010 if (view->dying && view == TAILQ_FIRST(&views) &&
2011 TAILQ_NEXT(view, entry) == NULL)
2012 done = 1;
2013 if (done) {
2014 struct tog_view *v;
2017 * When we quit, scroll the screen up a single line
2018 * so we don't lose any information.
2020 TAILQ_FOREACH(v, &views, entry) {
2021 wmove(v->window, 0, 0);
2022 wdeleteln(v->window);
2023 wnoutrefresh(v->window);
2024 if (v->child && !view_is_fullscreen(v)) {
2025 wmove(v->child->window, 0, 0);
2026 wdeleteln(v->child->window);
2027 wnoutrefresh(v->child->window);
2030 doupdate();
2033 if (view->dying) {
2034 struct tog_view *v, *prev = NULL;
2036 if (view_is_parent_view(view))
2037 prev = TAILQ_PREV(view, tog_view_list_head,
2038 entry);
2039 else if (view->parent)
2040 prev = view->parent;
2042 if (view->parent) {
2043 view->parent->child = NULL;
2044 view->parent->focus_child = 0;
2045 /* Restore fullscreen line height. */
2046 view->parent->nlines = view->parent->lines;
2047 err = view_resize(view->parent);
2048 if (err)
2049 break;
2050 /* Make resized splits persist. */
2051 view_transfer_size(view->parent, view);
2052 } else
2053 TAILQ_REMOVE(&views, view, entry);
2055 err = view_close(view);
2056 if (err)
2057 goto done;
2059 view = NULL;
2060 TAILQ_FOREACH(v, &views, entry) {
2061 if (v->focussed)
2062 break;
2064 if (view == NULL && new_view == NULL) {
2065 /* No view has focus. Try to pick one. */
2066 if (prev)
2067 view = prev;
2068 else if (!TAILQ_EMPTY(&views)) {
2069 view = TAILQ_LAST(&views,
2070 tog_view_list_head);
2072 if (view) {
2073 if (view->focus_child) {
2074 view->child->focussed = 1;
2075 view = view->child;
2076 } else
2077 view->focussed = 1;
2081 if (new_view) {
2082 struct tog_view *v, *t;
2083 /* Only allow one parent view per type. */
2084 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2085 if (v->type != new_view->type)
2086 continue;
2087 TAILQ_REMOVE(&views, v, entry);
2088 err = view_close(v);
2089 if (err)
2090 goto done;
2091 break;
2093 TAILQ_INSERT_TAIL(&views, new_view, entry);
2094 view = new_view;
2096 if (view && !done) {
2097 if (view_is_parent_view(view)) {
2098 if (view->child && view->child->focussed)
2099 view = view->child;
2100 } else {
2101 if (view->parent && view->parent->focussed)
2102 view = view->parent;
2104 show_panel(view->panel);
2105 if (view->child && view_is_splitscreen(view->child))
2106 show_panel(view->child->panel);
2107 if (view->parent && view_is_splitscreen(view)) {
2108 err = view->parent->show(view->parent);
2109 if (err)
2110 goto done;
2112 err = view->show(view);
2113 if (err)
2114 goto done;
2115 if (view->child) {
2116 err = view->child->show(view->child);
2117 if (err)
2118 goto done;
2120 update_panels();
2121 doupdate();
2124 done:
2125 while (!TAILQ_EMPTY(&views)) {
2126 const struct got_error *close_err;
2127 view = TAILQ_FIRST(&views);
2128 TAILQ_REMOVE(&views, view, entry);
2129 close_err = view_close(view);
2130 if (close_err && err == NULL)
2131 err = close_err;
2134 errcode = pthread_mutex_unlock(&tog_mutex);
2135 if (errcode && err == NULL)
2136 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2138 return err;
2141 __dead static void
2142 usage_log(void)
2144 endwin();
2145 fprintf(stderr,
2146 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2147 getprogname());
2148 exit(1);
2151 /* Create newly allocated wide-character string equivalent to a byte string. */
2152 static const struct got_error *
2153 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2155 char *vis = NULL;
2156 const struct got_error *err = NULL;
2158 *ws = NULL;
2159 *wlen = mbstowcs(NULL, s, 0);
2160 if (*wlen == (size_t)-1) {
2161 int vislen;
2162 if (errno != EILSEQ)
2163 return got_error_from_errno("mbstowcs");
2165 /* byte string invalid in current encoding; try to "fix" it */
2166 err = got_mbsavis(&vis, &vislen, s);
2167 if (err)
2168 return err;
2169 *wlen = mbstowcs(NULL, vis, 0);
2170 if (*wlen == (size_t)-1) {
2171 err = got_error_from_errno("mbstowcs"); /* give up */
2172 goto done;
2176 *ws = calloc(*wlen + 1, sizeof(**ws));
2177 if (*ws == NULL) {
2178 err = got_error_from_errno("calloc");
2179 goto done;
2182 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2183 err = got_error_from_errno("mbstowcs");
2184 done:
2185 free(vis);
2186 if (err) {
2187 free(*ws);
2188 *ws = NULL;
2189 *wlen = 0;
2191 return err;
2194 static const struct got_error *
2195 expand_tab(char **ptr, const char *src)
2197 char *dst;
2198 size_t len, n, idx = 0, sz = 0;
2200 *ptr = NULL;
2201 n = len = strlen(src);
2202 dst = malloc(n + 1);
2203 if (dst == NULL)
2204 return got_error_from_errno("malloc");
2206 while (idx < len && src[idx]) {
2207 const char c = src[idx];
2209 if (c == '\t') {
2210 size_t nb = TABSIZE - sz % TABSIZE;
2211 char *p;
2213 p = realloc(dst, n + nb);
2214 if (p == NULL) {
2215 free(dst);
2216 return got_error_from_errno("realloc");
2219 dst = p;
2220 n += nb;
2221 memset(dst + sz, ' ', nb);
2222 sz += nb;
2223 } else
2224 dst[sz++] = src[idx];
2225 ++idx;
2228 dst[sz] = '\0';
2229 *ptr = dst;
2230 return NULL;
2234 * Advance at most n columns from wline starting at offset off.
2235 * Return the index to the first character after the span operation.
2236 * Return the combined column width of all spanned wide characters in
2237 * *rcol.
2239 static int
2240 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2242 int width, i, cols = 0;
2244 if (n == 0) {
2245 *rcol = cols;
2246 return off;
2249 for (i = off; wline[i] != L'\0'; ++i) {
2250 if (wline[i] == L'\t')
2251 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2252 else
2253 width = wcwidth(wline[i]);
2255 if (width == -1) {
2256 width = 1;
2257 wline[i] = L'.';
2260 if (cols + width > n)
2261 break;
2262 cols += width;
2265 *rcol = cols;
2266 return i;
2270 * Format a line for display, ensuring that it won't overflow a width limit.
2271 * With scrolling, the width returned refers to the scrolled version of the
2272 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2274 static const struct got_error *
2275 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2276 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2278 const struct got_error *err = NULL;
2279 int cols;
2280 wchar_t *wline = NULL;
2281 char *exstr = NULL;
2282 size_t wlen;
2283 int i, scrollx;
2285 *wlinep = NULL;
2286 *widthp = 0;
2288 if (expand) {
2289 err = expand_tab(&exstr, line);
2290 if (err)
2291 return err;
2294 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2295 free(exstr);
2296 if (err)
2297 return err;
2299 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2301 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2302 wline[wlen - 1] = L'\0';
2303 wlen--;
2305 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2306 wline[wlen - 1] = L'\0';
2307 wlen--;
2310 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2311 wline[i] = L'\0';
2313 if (widthp)
2314 *widthp = cols;
2315 if (scrollxp)
2316 *scrollxp = scrollx;
2317 if (err)
2318 free(wline);
2319 else
2320 *wlinep = wline;
2321 return err;
2324 static const struct got_error*
2325 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2326 struct got_object_id *id, struct got_repository *repo)
2328 static const struct got_error *err = NULL;
2329 struct got_reflist_entry *re;
2330 char *s;
2331 const char *name;
2333 *refs_str = NULL;
2335 if (refs == NULL)
2336 return NULL;
2338 TAILQ_FOREACH(re, refs, entry) {
2339 struct got_tag_object *tag = NULL;
2340 struct got_object_id *ref_id;
2341 int cmp;
2343 name = got_ref_get_name(re->ref);
2344 if (strcmp(name, GOT_REF_HEAD) == 0)
2345 continue;
2346 if (strncmp(name, "refs/", 5) == 0)
2347 name += 5;
2348 if (strncmp(name, "got/", 4) == 0)
2349 continue;
2350 if (strncmp(name, "heads/", 6) == 0)
2351 name += 6;
2352 if (strncmp(name, "remotes/", 8) == 0) {
2353 name += 8;
2354 s = strstr(name, "/" GOT_REF_HEAD);
2355 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
2356 continue;
2358 err = got_ref_resolve(&ref_id, repo, re->ref);
2359 if (err)
2360 break;
2361 if (strncmp(name, "tags/", 5) == 0) {
2362 err = got_object_open_as_tag(&tag, repo, ref_id);
2363 if (err) {
2364 if (err->code != GOT_ERR_OBJ_TYPE) {
2365 free(ref_id);
2366 break;
2368 /* Ref points at something other than a tag. */
2369 err = NULL;
2370 tag = NULL;
2373 cmp = got_object_id_cmp(tag ?
2374 got_object_tag_get_object_id(tag) : ref_id, id);
2375 free(ref_id);
2376 if (tag)
2377 got_object_tag_close(tag);
2378 if (cmp != 0)
2379 continue;
2380 s = *refs_str;
2381 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2382 s ? ", " : "", name) == -1) {
2383 err = got_error_from_errno("asprintf");
2384 free(s);
2385 *refs_str = NULL;
2386 break;
2388 free(s);
2391 return err;
2394 static const struct got_error *
2395 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2396 int col_tab_align)
2398 char *smallerthan;
2400 smallerthan = strchr(author, '<');
2401 if (smallerthan && smallerthan[1] != '\0')
2402 author = smallerthan + 1;
2403 author[strcspn(author, "@>")] = '\0';
2404 return format_line(wauthor, author_width, NULL, author, 0, limit,
2405 col_tab_align, 0);
2408 static const struct got_error *
2409 draw_commit(struct tog_view *view, struct commit_queue_entry *entry,
2410 const size_t date_display_cols, int author_display_cols)
2412 struct tog_log_view_state *s = &view->state.log;
2413 const struct got_error *err = NULL;
2414 struct got_commit_object *commit = entry->commit;
2415 struct got_object_id *id = entry->id;
2416 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2417 char *refs_str = NULL;
2418 char *logmsg0 = NULL, *logmsg = NULL;
2419 char *author = NULL;
2420 wchar_t *wrefstr = NULL, *wlogmsg = NULL, *wauthor = NULL;
2421 int author_width, refstr_width, logmsg_width;
2422 char *newline, *line = NULL;
2423 int col, limit, scrollx, logmsg_x;
2424 const int avail = view->ncols, marker_column = author_display_cols + 1;
2425 struct tm tm;
2426 time_t committer_time;
2427 struct tog_color *tc;
2428 struct got_reflist_head *refs;
2430 committer_time = got_object_commit_get_committer_time(commit);
2431 if (gmtime_r(&committer_time, &tm) == NULL)
2432 return got_error_from_errno("gmtime_r");
2433 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2434 return got_error(GOT_ERR_NO_SPACE);
2436 if (avail <= date_display_cols)
2437 limit = MIN(sizeof(datebuf) - 1, avail);
2438 else
2439 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2440 tc = get_color(&s->colors, TOG_COLOR_DATE);
2441 if (tc)
2442 wattr_on(view->window,
2443 COLOR_PAIR(tc->colorpair), NULL);
2444 waddnstr(view->window, datebuf, limit);
2445 if (tc)
2446 wattr_off(view->window,
2447 COLOR_PAIR(tc->colorpair), NULL);
2448 col = limit;
2449 if (col > avail)
2450 goto done;
2452 if (avail >= 120) {
2453 char *id_str;
2454 err = got_object_id_str(&id_str, id);
2455 if (err)
2456 goto done;
2457 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2458 if (tc)
2459 wattr_on(view->window,
2460 COLOR_PAIR(tc->colorpair), NULL);
2461 wprintw(view->window, "%.8s ", id_str);
2462 if (tc)
2463 wattr_off(view->window,
2464 COLOR_PAIR(tc->colorpair), NULL);
2465 free(id_str);
2466 col += 9;
2467 if (col > avail)
2468 goto done;
2471 if (s->use_committer)
2472 author = strdup(got_object_commit_get_committer(commit));
2473 else
2474 author = strdup(got_object_commit_get_author(commit));
2475 if (author == NULL) {
2476 err = got_error_from_errno("strdup");
2477 goto done;
2479 err = format_author(&wauthor, &author_width, author, avail - col, col);
2480 if (err)
2481 goto done;
2482 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2483 if (tc)
2484 wattr_on(view->window,
2485 COLOR_PAIR(tc->colorpair), NULL);
2486 waddwstr(view->window, wauthor);
2487 col += author_width;
2488 while (col < avail && author_width < author_display_cols + 2) {
2489 if (tog_base_commit.id != NULL &&
2490 author_width == marker_column &&
2491 entry->idx == tog_base_commit.idx)
2492 waddch(view->window, tog_base_commit.marker);
2493 else
2494 waddch(view->window, ' ');
2495 col++;
2496 author_width++;
2498 if (tc)
2499 wattr_off(view->window,
2500 COLOR_PAIR(tc->colorpair), NULL);
2501 if (col > avail)
2502 goto done;
2504 err = got_object_commit_get_logmsg(&logmsg0, commit);
2505 if (err)
2506 goto done;
2507 logmsg = logmsg0;
2508 while (*logmsg == '\n')
2509 logmsg++;
2510 newline = strchr(logmsg, '\n');
2511 if (newline)
2512 *newline = '\0';
2514 limit = avail - col;
2515 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2516 limit--; /* for the border */
2518 /* Prepend reference labels to log message if possible .*/
2519 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, id);
2520 err = build_refs_str(&refs_str, refs, id, s->repo);
2521 if (err)
2522 goto done;
2523 if (refs_str) {
2524 char *rs;
2526 if (asprintf(&rs, "[%s]", refs_str) == -1) {
2527 err = got_error_from_errno("asprintf");
2528 goto done;
2530 err = format_line(&wrefstr, &refstr_width,
2531 &scrollx, rs, view->x, limit, col, 1);
2532 free(rs);
2533 if (err)
2534 goto done;
2535 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2536 if (tc)
2537 wattr_on(view->window,
2538 COLOR_PAIR(tc->colorpair), NULL);
2539 waddwstr(view->window, &wrefstr[scrollx]);
2540 if (tc)
2541 wattr_off(view->window,
2542 COLOR_PAIR(tc->colorpair), NULL);
2543 col += MAX(refstr_width, 0);
2544 if (col > avail)
2545 goto done;
2547 if (col < avail) {
2548 waddch(view->window, ' ');
2549 col++;
2552 if (refstr_width > 0)
2553 logmsg_x = 0;
2554 else {
2555 int unscrolled_refstr_width;
2556 size_t len = wcslen(wrefstr);
2559 * No need to check for -1 return value here since
2560 * unprintables have been replaced by span_wline().
2562 unscrolled_refstr_width = wcswidth(wrefstr, len);
2563 unscrolled_refstr_width += 1; /* trailing space */
2564 logmsg_x = view->x - unscrolled_refstr_width;
2567 limit = avail - col;
2568 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2569 limit--; /* for the border */
2570 } else
2571 logmsg_x = view->x;
2573 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, logmsg_x,
2574 limit, col, 1);
2575 if (err)
2576 goto done;
2577 waddwstr(view->window, &wlogmsg[scrollx]);
2578 col += MAX(logmsg_width, 0);
2579 while (col < avail) {
2580 waddch(view->window, ' ');
2581 col++;
2583 done:
2584 free(logmsg0);
2585 free(wlogmsg);
2586 free(wrefstr);
2587 free(refs_str);
2588 free(author);
2589 free(wauthor);
2590 free(line);
2591 return err;
2594 static struct commit_queue_entry *
2595 alloc_commit_queue_entry(struct got_commit_object *commit,
2596 struct got_object_id *id)
2598 struct commit_queue_entry *entry;
2599 struct got_object_id *dup;
2601 entry = calloc(1, sizeof(*entry));
2602 if (entry == NULL)
2603 return NULL;
2605 dup = got_object_id_dup(id);
2606 if (dup == NULL) {
2607 free(entry);
2608 return NULL;
2611 entry->id = dup;
2612 entry->commit = commit;
2613 return entry;
2616 static void
2617 pop_commit(struct commit_queue *commits)
2619 struct commit_queue_entry *entry;
2621 entry = TAILQ_FIRST(&commits->head);
2622 TAILQ_REMOVE(&commits->head, entry, entry);
2623 got_object_commit_close(entry->commit);
2624 commits->ncommits--;
2625 free(entry->id);
2626 free(entry);
2629 static void
2630 free_commits(struct commit_queue *commits)
2632 while (!TAILQ_EMPTY(&commits->head))
2633 pop_commit(commits);
2636 static const struct got_error *
2637 match_commit(int *have_match, struct got_object_id *id,
2638 struct got_commit_object *commit, regex_t *regex)
2640 const struct got_error *err = NULL;
2641 regmatch_t regmatch;
2642 char *id_str = NULL, *logmsg = NULL;
2644 *have_match = 0;
2646 err = got_object_id_str(&id_str, id);
2647 if (err)
2648 return err;
2650 err = got_object_commit_get_logmsg(&logmsg, commit);
2651 if (err)
2652 goto done;
2654 if (regexec(regex, got_object_commit_get_author(commit), 1,
2655 &regmatch, 0) == 0 ||
2656 regexec(regex, got_object_commit_get_committer(commit), 1,
2657 &regmatch, 0) == 0 ||
2658 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2659 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2660 *have_match = 1;
2661 done:
2662 free(id_str);
2663 free(logmsg);
2664 return err;
2667 static const struct got_error *
2668 queue_commits(struct tog_log_thread_args *a)
2670 const struct got_error *err = NULL;
2673 * We keep all commits open throughout the lifetime of the log
2674 * view in order to avoid having to re-fetch commits from disk
2675 * while updating the display.
2677 do {
2678 struct got_object_id id;
2679 struct got_commit_object *commit;
2680 struct commit_queue_entry *entry;
2681 int limit_match = 0;
2682 int errcode;
2684 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2685 NULL, NULL);
2686 if (err)
2687 break;
2689 err = got_object_open_as_commit(&commit, a->repo, &id);
2690 if (err)
2691 break;
2692 entry = alloc_commit_queue_entry(commit, &id);
2693 if (entry == NULL) {
2694 err = got_error_from_errno("alloc_commit_queue_entry");
2695 break;
2698 errcode = pthread_mutex_lock(&tog_mutex);
2699 if (errcode) {
2700 err = got_error_set_errno(errcode,
2701 "pthread_mutex_lock");
2702 break;
2705 entry->idx = a->real_commits->ncommits;
2706 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2707 a->real_commits->ncommits++;
2709 if (tog_base_commit.id != NULL && tog_base_commit.idx == -1 &&
2710 got_object_id_cmp(&id, tog_base_commit.id) == 0)
2711 tog_base_commit.idx = entry->idx;
2713 if (*a->limiting) {
2714 err = match_commit(&limit_match, &id, commit,
2715 a->limit_regex);
2716 if (err)
2717 break;
2719 if (limit_match) {
2720 struct commit_queue_entry *matched;
2722 matched = alloc_commit_queue_entry(
2723 entry->commit, entry->id);
2724 if (matched == NULL) {
2725 err = got_error_from_errno(
2726 "alloc_commit_queue_entry");
2727 break;
2729 matched->commit = entry->commit;
2730 got_object_commit_retain(entry->commit);
2732 matched->idx = a->limit_commits->ncommits;
2733 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2734 matched, entry);
2735 a->limit_commits->ncommits++;
2739 * This is how we signal log_thread() that we
2740 * have found a match, and that it should be
2741 * counted as a new entry for the view.
2743 a->limit_match = limit_match;
2746 if (*a->searching == TOG_SEARCH_FORWARD &&
2747 !*a->search_next_done) {
2748 int have_match;
2749 err = match_commit(&have_match, &id, commit, a->regex);
2750 if (err)
2751 break;
2753 if (*a->limiting) {
2754 if (limit_match && have_match)
2755 *a->search_next_done =
2756 TOG_SEARCH_HAVE_MORE;
2757 } else if (have_match)
2758 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2761 errcode = pthread_mutex_unlock(&tog_mutex);
2762 if (errcode && err == NULL)
2763 err = got_error_set_errno(errcode,
2764 "pthread_mutex_unlock");
2765 if (err)
2766 break;
2767 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2769 return err;
2772 static void
2773 select_commit(struct tog_log_view_state *s)
2775 struct commit_queue_entry *entry;
2776 int ncommits = 0;
2778 entry = s->first_displayed_entry;
2779 while (entry) {
2780 if (ncommits == s->selected) {
2781 s->selected_entry = entry;
2782 break;
2784 entry = TAILQ_NEXT(entry, entry);
2785 ncommits++;
2789 static const struct got_error *
2790 draw_commits(struct tog_view *view)
2792 const struct got_error *err = NULL;
2793 struct tog_log_view_state *s = &view->state.log;
2794 struct commit_queue_entry *entry = s->selected_entry;
2795 int limit = view->nlines;
2796 int width;
2797 int ncommits, author_cols = 4, refstr_cols;
2798 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2799 char *refs_str = NULL;
2800 wchar_t *wline;
2801 struct tog_color *tc;
2802 static const size_t date_display_cols = 12;
2803 struct got_reflist_head *refs;
2805 if (view_is_hsplit_top(view))
2806 --limit; /* account for border */
2808 if (s->selected_entry &&
2809 !(view->searching && view->search_next_done == 0)) {
2810 err = got_object_id_str(&id_str, s->selected_entry->id);
2811 if (err)
2812 return err;
2813 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2814 s->selected_entry->id);
2815 err = build_refs_str(&refs_str, refs, s->selected_entry->id,
2816 s->repo);
2817 if (err)
2818 goto done;
2821 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2822 halfdelay(10); /* disable fast refresh */
2824 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2825 if (asprintf(&ncommits_str, " [%d/%d] %s",
2826 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2827 (view->searching && !view->search_next_done) ?
2828 "searching..." : "loading...") == -1) {
2829 err = got_error_from_errno("asprintf");
2830 goto done;
2832 } else {
2833 const char *search_str = NULL;
2834 const char *limit_str = NULL;
2836 if (view->searching) {
2837 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2838 search_str = "no more matches";
2839 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2840 search_str = "no matches found";
2841 else if (!view->search_next_done)
2842 search_str = "searching...";
2845 if (s->limit_view && s->commits->ncommits == 0)
2846 limit_str = "no matches found";
2848 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2849 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2850 search_str ? search_str : (refs_str ? refs_str : ""),
2851 limit_str ? limit_str : "") == -1) {
2852 err = got_error_from_errno("asprintf");
2853 goto done;
2857 free(refs_str);
2858 refs_str = NULL;
2860 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2861 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2862 "........................................",
2863 s->in_repo_path, ncommits_str) == -1) {
2864 err = got_error_from_errno("asprintf");
2865 header = NULL;
2866 goto done;
2868 } else if (asprintf(&header, "commit %s%s",
2869 id_str ? id_str : "........................................",
2870 ncommits_str) == -1) {
2871 err = got_error_from_errno("asprintf");
2872 header = NULL;
2873 goto done;
2875 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2876 if (err)
2877 goto done;
2879 werase(view->window);
2881 if (view_needs_focus_indication(view))
2882 wstandout(view->window);
2883 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2884 if (tc)
2885 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2886 waddwstr(view->window, wline);
2887 while (width < view->ncols) {
2888 waddch(view->window, ' ');
2889 width++;
2891 if (tc)
2892 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2893 if (view_needs_focus_indication(view))
2894 wstandend(view->window);
2895 free(wline);
2896 if (limit <= 1)
2897 goto done;
2899 /* Grow author column size if necessary, and set view->maxx. */
2900 entry = s->first_displayed_entry;
2901 ncommits = 0;
2902 view->maxx = 0;
2903 while (entry) {
2904 struct got_commit_object *c = entry->commit;
2905 char *author, *eol, *msg, *msg0;
2906 wchar_t *wauthor, *wmsg;
2907 int width;
2908 if (ncommits >= limit - 1)
2909 break;
2910 if (s->use_committer)
2911 author = strdup(got_object_commit_get_committer(c));
2912 else
2913 author = strdup(got_object_commit_get_author(c));
2914 if (author == NULL) {
2915 err = got_error_from_errno("strdup");
2916 goto done;
2918 err = format_author(&wauthor, &width, author, COLS,
2919 date_display_cols);
2920 if (author_cols < width)
2921 author_cols = width;
2922 free(wauthor);
2923 free(author);
2924 if (err)
2925 goto done;
2926 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2927 entry->id);
2928 err = build_refs_str(&refs_str, refs, entry->id, s->repo);
2929 if (err)
2930 goto done;
2931 if (refs_str) {
2932 wchar_t *ws;
2933 err = format_line(&ws, &width, NULL, refs_str,
2934 0, INT_MAX, date_display_cols + author_cols, 0);
2935 free(ws);
2936 free(refs_str);
2937 refs_str = NULL;
2938 if (err)
2939 goto done;
2940 refstr_cols = width + 3; /* account for [ ] + space */
2941 } else
2942 refstr_cols = 0;
2943 err = got_object_commit_get_logmsg(&msg0, c);
2944 if (err)
2945 goto done;
2946 msg = msg0;
2947 while (*msg == '\n')
2948 ++msg;
2949 if ((eol = strchr(msg, '\n')))
2950 *eol = '\0';
2951 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2952 date_display_cols + author_cols + refstr_cols, 0);
2953 if (err)
2954 goto done;
2955 view->maxx = MAX(view->maxx, width + refstr_cols);
2956 free(msg0);
2957 free(wmsg);
2958 ncommits++;
2959 entry = TAILQ_NEXT(entry, entry);
2962 entry = s->first_displayed_entry;
2963 s->last_displayed_entry = s->first_displayed_entry;
2964 ncommits = 0;
2965 while (entry) {
2966 if (ncommits >= limit - 1)
2967 break;
2968 if (ncommits == s->selected)
2969 wstandout(view->window);
2970 err = draw_commit(view, entry, date_display_cols, author_cols);
2971 if (ncommits == s->selected)
2972 wstandend(view->window);
2973 if (err)
2974 goto done;
2975 ncommits++;
2976 s->last_displayed_entry = entry;
2977 entry = TAILQ_NEXT(entry, entry);
2980 view_border(view);
2981 done:
2982 free(id_str);
2983 free(refs_str);
2984 free(ncommits_str);
2985 free(header);
2986 return err;
2989 static void
2990 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2992 struct commit_queue_entry *entry;
2993 int nscrolled = 0;
2995 entry = TAILQ_FIRST(&s->commits->head);
2996 if (s->first_displayed_entry == entry)
2997 return;
2999 entry = s->first_displayed_entry;
3000 while (entry && nscrolled < maxscroll) {
3001 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3002 if (entry) {
3003 s->first_displayed_entry = entry;
3004 nscrolled++;
3009 static const struct got_error *
3010 trigger_log_thread(struct tog_view *view, int wait)
3012 struct tog_log_thread_args *ta = &view->state.log.thread_args;
3013 int errcode;
3015 if (!using_mock_io)
3016 halfdelay(1); /* fast refresh while loading commits */
3018 while (!ta->log_complete && !tog_thread_error &&
3019 (ta->commits_needed > 0 || ta->load_all)) {
3020 /* Wake the log thread. */
3021 errcode = pthread_cond_signal(&ta->need_commits);
3022 if (errcode)
3023 return got_error_set_errno(errcode,
3024 "pthread_cond_signal");
3027 * The mutex will be released while the view loop waits
3028 * in wgetch(), at which time the log thread will run.
3030 if (!wait)
3031 break;
3033 /* Display progress update in log view. */
3034 show_log_view(view);
3035 update_panels();
3036 doupdate();
3038 /* Wait right here while next commit is being loaded. */
3039 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
3040 if (errcode)
3041 return got_error_set_errno(errcode,
3042 "pthread_cond_wait");
3044 /* Display progress update in log view. */
3045 show_log_view(view);
3046 update_panels();
3047 doupdate();
3050 return NULL;
3053 static const struct got_error *
3054 request_log_commits(struct tog_view *view)
3056 struct tog_log_view_state *state = &view->state.log;
3057 const struct got_error *err = NULL;
3059 if (state->thread_args.log_complete)
3060 return NULL;
3062 state->thread_args.commits_needed += view->nscrolled;
3063 err = trigger_log_thread(view, 1);
3064 view->nscrolled = 0;
3066 return err;
3069 static const struct got_error *
3070 log_scroll_down(struct tog_view *view, int maxscroll)
3072 struct tog_log_view_state *s = &view->state.log;
3073 const struct got_error *err = NULL;
3074 struct commit_queue_entry *pentry;
3075 int nscrolled = 0, ncommits_needed;
3077 if (s->last_displayed_entry == NULL)
3078 return NULL;
3080 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
3081 if (s->commits->ncommits < ncommits_needed &&
3082 !s->thread_args.log_complete) {
3084 * Ask the log thread for required amount of commits.
3086 s->thread_args.commits_needed +=
3087 ncommits_needed - s->commits->ncommits;
3088 err = trigger_log_thread(view, 1);
3089 if (err)
3090 return err;
3093 do {
3094 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
3095 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
3096 break;
3098 s->last_displayed_entry = pentry ?
3099 pentry : s->last_displayed_entry;
3101 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3102 if (pentry == NULL)
3103 break;
3104 s->first_displayed_entry = pentry;
3105 } while (++nscrolled < maxscroll);
3107 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3108 view->nscrolled += nscrolled;
3109 else
3110 view->nscrolled = 0;
3112 return err;
3115 static const struct got_error *
3116 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3117 struct got_commit_object *commit, struct got_object_id *commit_id,
3118 struct tog_view *log_view, struct got_repository *repo)
3120 const struct got_error *err;
3121 struct got_object_qid *parent_id;
3122 struct tog_view *diff_view;
3124 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3125 if (diff_view == NULL)
3126 return got_error_from_errno("view_open");
3128 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3129 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3130 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3131 if (err == NULL)
3132 *new_view = diff_view;
3133 return err;
3136 static const struct got_error *
3137 tree_view_visit_subtree(struct tog_tree_view_state *s,
3138 struct got_tree_object *subtree)
3140 struct tog_parent_tree *parent;
3142 parent = calloc(1, sizeof(*parent));
3143 if (parent == NULL)
3144 return got_error_from_errno("calloc");
3146 parent->tree = s->tree;
3147 parent->first_displayed_entry = s->first_displayed_entry;
3148 parent->selected_entry = s->selected_entry;
3149 parent->selected = s->selected;
3150 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3151 s->tree = subtree;
3152 s->selected = 0;
3153 s->first_displayed_entry = NULL;
3154 return NULL;
3157 static const struct got_error *
3158 tree_view_walk_path(struct tog_tree_view_state *s,
3159 struct got_commit_object *commit, const char *path)
3161 const struct got_error *err = NULL;
3162 struct got_tree_object *tree = NULL;
3163 const char *p;
3164 char *slash, *subpath = NULL;
3166 /* Walk the path and open corresponding tree objects. */
3167 p = path;
3168 while (*p) {
3169 struct got_tree_entry *te;
3170 struct got_object_id *tree_id;
3171 char *te_name;
3173 while (p[0] == '/')
3174 p++;
3176 /* Ensure the correct subtree entry is selected. */
3177 slash = strchr(p, '/');
3178 if (slash == NULL)
3179 te_name = strdup(p);
3180 else
3181 te_name = strndup(p, slash - p);
3182 if (te_name == NULL) {
3183 err = got_error_from_errno("strndup");
3184 break;
3186 te = got_object_tree_find_entry(s->tree, te_name);
3187 if (te == NULL) {
3188 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3189 free(te_name);
3190 break;
3192 free(te_name);
3193 s->first_displayed_entry = s->selected_entry = te;
3195 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3196 break; /* jump to this file's entry */
3198 slash = strchr(p, '/');
3199 if (slash)
3200 subpath = strndup(path, slash - path);
3201 else
3202 subpath = strdup(path);
3203 if (subpath == NULL) {
3204 err = got_error_from_errno("strdup");
3205 break;
3208 err = got_object_id_by_path(&tree_id, s->repo, commit,
3209 subpath);
3210 if (err)
3211 break;
3213 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3214 free(tree_id);
3215 if (err)
3216 break;
3218 err = tree_view_visit_subtree(s, tree);
3219 if (err) {
3220 got_object_tree_close(tree);
3221 break;
3223 if (slash == NULL)
3224 break;
3225 free(subpath);
3226 subpath = NULL;
3227 p = slash;
3230 free(subpath);
3231 return err;
3234 static const struct got_error *
3235 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3236 struct commit_queue_entry *entry, const char *path,
3237 const char *head_ref_name, struct got_repository *repo)
3239 const struct got_error *err = NULL;
3240 struct tog_tree_view_state *s;
3241 struct tog_view *tree_view;
3243 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3244 if (tree_view == NULL)
3245 return got_error_from_errno("view_open");
3247 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3248 if (err)
3249 return err;
3250 s = &tree_view->state.tree;
3252 *new_view = tree_view;
3254 if (got_path_is_root_dir(path))
3255 return NULL;
3257 return tree_view_walk_path(s, entry->commit, path);
3260 static const struct got_error *
3261 block_signals_used_by_main_thread(void)
3263 sigset_t sigset;
3264 int errcode;
3266 if (sigemptyset(&sigset) == -1)
3267 return got_error_from_errno("sigemptyset");
3269 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3270 if (sigaddset(&sigset, SIGWINCH) == -1)
3271 return got_error_from_errno("sigaddset");
3272 if (sigaddset(&sigset, SIGCONT) == -1)
3273 return got_error_from_errno("sigaddset");
3274 if (sigaddset(&sigset, SIGINT) == -1)
3275 return got_error_from_errno("sigaddset");
3276 if (sigaddset(&sigset, SIGTERM) == -1)
3277 return got_error_from_errno("sigaddset");
3279 /* ncurses handles SIGTSTP */
3280 if (sigaddset(&sigset, SIGTSTP) == -1)
3281 return got_error_from_errno("sigaddset");
3283 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3284 if (errcode)
3285 return got_error_set_errno(errcode, "pthread_sigmask");
3287 return NULL;
3290 static void *
3291 log_thread(void *arg)
3293 const struct got_error *err = NULL;
3294 int errcode = 0;
3295 struct tog_log_thread_args *a = arg;
3296 int done = 0;
3299 * Sync startup with main thread such that we begin our
3300 * work once view_input() has released the mutex.
3302 errcode = pthread_mutex_lock(&tog_mutex);
3303 if (errcode) {
3304 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3305 return (void *)err;
3308 err = block_signals_used_by_main_thread();
3309 if (err) {
3310 pthread_mutex_unlock(&tog_mutex);
3311 goto done;
3314 while (!done && !err && !tog_fatal_signal_received()) {
3315 errcode = pthread_mutex_unlock(&tog_mutex);
3316 if (errcode) {
3317 err = got_error_set_errno(errcode,
3318 "pthread_mutex_unlock");
3319 goto done;
3321 err = queue_commits(a);
3322 if (err) {
3323 if (err->code != GOT_ERR_ITER_COMPLETED)
3324 goto done;
3325 err = NULL;
3326 done = 1;
3327 } else if (a->commits_needed > 0 && !a->load_all) {
3328 if (*a->limiting) {
3329 if (a->limit_match)
3330 a->commits_needed--;
3331 } else
3332 a->commits_needed--;
3335 errcode = pthread_mutex_lock(&tog_mutex);
3336 if (errcode) {
3337 err = got_error_set_errno(errcode,
3338 "pthread_mutex_lock");
3339 goto done;
3340 } else if (*a->quit)
3341 done = 1;
3342 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3343 *a->first_displayed_entry =
3344 TAILQ_FIRST(&a->limit_commits->head);
3345 *a->selected_entry = *a->first_displayed_entry;
3346 } else if (*a->first_displayed_entry == NULL) {
3347 *a->first_displayed_entry =
3348 TAILQ_FIRST(&a->real_commits->head);
3349 *a->selected_entry = *a->first_displayed_entry;
3352 errcode = pthread_cond_signal(&a->commit_loaded);
3353 if (errcode) {
3354 err = got_error_set_errno(errcode,
3355 "pthread_cond_signal");
3356 pthread_mutex_unlock(&tog_mutex);
3357 goto done;
3360 if (done)
3361 a->commits_needed = 0;
3362 else {
3363 if (a->commits_needed == 0 && !a->load_all) {
3364 errcode = pthread_cond_wait(&a->need_commits,
3365 &tog_mutex);
3366 if (errcode) {
3367 err = got_error_set_errno(errcode,
3368 "pthread_cond_wait");
3369 pthread_mutex_unlock(&tog_mutex);
3370 goto done;
3372 if (*a->quit)
3373 done = 1;
3377 a->log_complete = 1;
3378 errcode = pthread_mutex_unlock(&tog_mutex);
3379 if (errcode)
3380 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3381 done:
3382 if (err) {
3383 tog_thread_error = 1;
3384 pthread_cond_signal(&a->commit_loaded);
3386 return (void *)err;
3389 static const struct got_error *
3390 stop_log_thread(struct tog_log_view_state *s)
3392 const struct got_error *err = NULL, *thread_err = NULL;
3393 int errcode;
3395 if (s->thread) {
3396 s->quit = 1;
3397 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3398 if (errcode)
3399 return got_error_set_errno(errcode,
3400 "pthread_cond_signal");
3401 errcode = pthread_mutex_unlock(&tog_mutex);
3402 if (errcode)
3403 return got_error_set_errno(errcode,
3404 "pthread_mutex_unlock");
3405 errcode = pthread_join(s->thread, (void **)&thread_err);
3406 if (errcode)
3407 return got_error_set_errno(errcode, "pthread_join");
3408 errcode = pthread_mutex_lock(&tog_mutex);
3409 if (errcode)
3410 return got_error_set_errno(errcode,
3411 "pthread_mutex_lock");
3412 s->thread = 0; //NULL;
3415 if (s->thread_args.repo) {
3416 err = got_repo_close(s->thread_args.repo);
3417 s->thread_args.repo = NULL;
3420 if (s->thread_args.pack_fds) {
3421 const struct got_error *pack_err =
3422 got_repo_pack_fds_close(s->thread_args.pack_fds);
3423 if (err == NULL)
3424 err = pack_err;
3425 s->thread_args.pack_fds = NULL;
3428 if (s->thread_args.graph) {
3429 got_commit_graph_close(s->thread_args.graph);
3430 s->thread_args.graph = NULL;
3433 return err ? err : thread_err;
3436 static const struct got_error *
3437 close_log_view(struct tog_view *view)
3439 const struct got_error *err = NULL;
3440 struct tog_log_view_state *s = &view->state.log;
3441 int errcode;
3443 err = stop_log_thread(s);
3445 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3446 if (errcode && err == NULL)
3447 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3449 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3450 if (errcode && err == NULL)
3451 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3453 free_commits(&s->limit_commits);
3454 free_commits(&s->real_commits);
3455 free(s->in_repo_path);
3456 s->in_repo_path = NULL;
3457 free(s->start_id);
3458 s->start_id = NULL;
3459 free(s->head_ref_name);
3460 s->head_ref_name = NULL;
3461 return err;
3465 * We use two queues to implement the limit feature: first consists of
3466 * commits matching the current limit_regex; second is the real queue
3467 * of all known commits (real_commits). When the user starts limiting,
3468 * we swap queues such that all movement and displaying functionality
3469 * works with very slight change.
3471 static const struct got_error *
3472 limit_log_view(struct tog_view *view)
3474 struct tog_log_view_state *s = &view->state.log;
3475 struct commit_queue_entry *entry;
3476 struct tog_view *v = view;
3477 const struct got_error *err = NULL;
3478 char pattern[1024];
3479 int ret;
3481 if (view_is_hsplit_top(view))
3482 v = view->child;
3483 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3484 v = view->parent;
3486 /* Get the pattern */
3487 wmove(v->window, v->nlines - 1, 0);
3488 wclrtoeol(v->window);
3489 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3490 nodelay(v->window, FALSE);
3491 nocbreak();
3492 echo();
3493 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3494 cbreak();
3495 noecho();
3496 nodelay(v->window, TRUE);
3497 if (ret == ERR)
3498 return NULL;
3500 if (*pattern == '\0') {
3502 * Safety measure for the situation where the user
3503 * resets limit without previously limiting anything.
3505 if (!s->limit_view)
3506 return NULL;
3509 * User could have pressed Ctrl+L, which refreshed the
3510 * commit queues, it means we can't save previously
3511 * (before limit took place) displayed entries,
3512 * because they would point to already free'ed memory,
3513 * so we are forced to always select first entry of
3514 * the queue.
3516 s->commits = &s->real_commits;
3517 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3518 s->selected_entry = s->first_displayed_entry;
3519 s->selected = 0;
3520 s->limit_view = 0;
3522 return NULL;
3525 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3526 return NULL;
3528 s->limit_view = 1;
3530 /* Clear the screen while loading limit view */
3531 s->first_displayed_entry = NULL;
3532 s->last_displayed_entry = NULL;
3533 s->selected_entry = NULL;
3534 s->commits = &s->limit_commits;
3536 /* Prepare limit queue for new search */
3537 free_commits(&s->limit_commits);
3538 s->limit_commits.ncommits = 0;
3540 /* First process commits, which are in queue already */
3541 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3542 int have_match = 0;
3544 err = match_commit(&have_match, entry->id,
3545 entry->commit, &s->limit_regex);
3546 if (err)
3547 return err;
3549 if (have_match) {
3550 struct commit_queue_entry *matched;
3552 matched = alloc_commit_queue_entry(entry->commit,
3553 entry->id);
3554 if (matched == NULL) {
3555 err = got_error_from_errno(
3556 "alloc_commit_queue_entry");
3557 break;
3559 matched->commit = entry->commit;
3560 got_object_commit_retain(entry->commit);
3562 matched->idx = s->limit_commits.ncommits;
3563 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3564 matched, entry);
3565 s->limit_commits.ncommits++;
3569 /* Second process all the commits, until we fill the screen */
3570 if (s->limit_commits.ncommits < view->nlines - 1 &&
3571 !s->thread_args.log_complete) {
3572 s->thread_args.commits_needed +=
3573 view->nlines - s->limit_commits.ncommits - 1;
3574 err = trigger_log_thread(view, 1);
3575 if (err)
3576 return err;
3579 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3580 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3581 s->selected = 0;
3583 return NULL;
3586 static const struct got_error *
3587 search_start_log_view(struct tog_view *view)
3589 struct tog_log_view_state *s = &view->state.log;
3591 s->matched_entry = NULL;
3592 s->search_entry = NULL;
3593 return NULL;
3596 static const struct got_error *
3597 search_next_log_view(struct tog_view *view)
3599 const struct got_error *err = NULL;
3600 struct tog_log_view_state *s = &view->state.log;
3601 struct commit_queue_entry *entry;
3603 /* Display progress update in log view. */
3604 show_log_view(view);
3605 update_panels();
3606 doupdate();
3608 if (s->search_entry) {
3609 int errcode, ch;
3610 errcode = pthread_mutex_unlock(&tog_mutex);
3611 if (errcode)
3612 return got_error_set_errno(errcode,
3613 "pthread_mutex_unlock");
3614 ch = wgetch(view->window);
3615 errcode = pthread_mutex_lock(&tog_mutex);
3616 if (errcode)
3617 return got_error_set_errno(errcode,
3618 "pthread_mutex_lock");
3619 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3620 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3621 return NULL;
3623 if (view->searching == TOG_SEARCH_FORWARD)
3624 entry = TAILQ_NEXT(s->search_entry, entry);
3625 else
3626 entry = TAILQ_PREV(s->search_entry,
3627 commit_queue_head, entry);
3628 } else if (s->matched_entry) {
3630 * If the user has moved the cursor after we hit a match,
3631 * the position from where we should continue searching
3632 * might have changed.
3634 if (view->searching == TOG_SEARCH_FORWARD)
3635 entry = TAILQ_NEXT(s->selected_entry, entry);
3636 else
3637 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3638 entry);
3639 } else {
3640 entry = s->selected_entry;
3643 while (1) {
3644 int have_match = 0;
3646 if (entry == NULL) {
3647 if (s->thread_args.log_complete ||
3648 view->searching == TOG_SEARCH_BACKWARD) {
3649 view->search_next_done =
3650 (s->matched_entry == NULL ?
3651 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3652 s->search_entry = NULL;
3653 return NULL;
3656 * Poke the log thread for more commits and return,
3657 * allowing the main loop to make progress. Search
3658 * will resume at s->search_entry once we come back.
3660 s->thread_args.commits_needed++;
3661 return trigger_log_thread(view, 0);
3664 err = match_commit(&have_match, entry->id, entry->commit,
3665 &view->regex);
3666 if (err)
3667 break;
3668 if (have_match) {
3669 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3670 s->matched_entry = entry;
3671 break;
3674 s->search_entry = entry;
3675 if (view->searching == TOG_SEARCH_FORWARD)
3676 entry = TAILQ_NEXT(entry, entry);
3677 else
3678 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3681 if (s->matched_entry) {
3682 int cur = s->selected_entry->idx;
3683 while (cur < s->matched_entry->idx) {
3684 err = input_log_view(NULL, view, KEY_DOWN);
3685 if (err)
3686 return err;
3687 cur++;
3689 while (cur > s->matched_entry->idx) {
3690 err = input_log_view(NULL, view, KEY_UP);
3691 if (err)
3692 return err;
3693 cur--;
3697 s->search_entry = NULL;
3699 return NULL;
3702 static const struct got_error *
3703 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3704 struct got_repository *repo, const char *head_ref_name,
3705 const char *in_repo_path, int log_branches)
3707 const struct got_error *err = NULL;
3708 struct tog_log_view_state *s = &view->state.log;
3709 struct got_repository *thread_repo = NULL;
3710 struct got_commit_graph *thread_graph = NULL;
3711 int errcode;
3713 if (in_repo_path != s->in_repo_path) {
3714 free(s->in_repo_path);
3715 s->in_repo_path = strdup(in_repo_path);
3716 if (s->in_repo_path == NULL) {
3717 err = got_error_from_errno("strdup");
3718 goto done;
3722 /* The commit queue only contains commits being displayed. */
3723 TAILQ_INIT(&s->real_commits.head);
3724 s->real_commits.ncommits = 0;
3725 s->commits = &s->real_commits;
3727 TAILQ_INIT(&s->limit_commits.head);
3728 s->limit_view = 0;
3729 s->limit_commits.ncommits = 0;
3731 s->repo = repo;
3732 if (head_ref_name) {
3733 s->head_ref_name = strdup(head_ref_name);
3734 if (s->head_ref_name == NULL) {
3735 err = got_error_from_errno("strdup");
3736 goto done;
3739 s->start_id = got_object_id_dup(start_id);
3740 if (s->start_id == NULL) {
3741 err = got_error_from_errno("got_object_id_dup");
3742 goto done;
3744 s->log_branches = log_branches;
3745 s->use_committer = 1;
3747 STAILQ_INIT(&s->colors);
3748 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3749 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3750 get_color_value("TOG_COLOR_COMMIT"));
3751 if (err)
3752 goto done;
3753 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3754 get_color_value("TOG_COLOR_AUTHOR"));
3755 if (err) {
3756 free_colors(&s->colors);
3757 goto done;
3759 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3760 get_color_value("TOG_COLOR_DATE"));
3761 if (err) {
3762 free_colors(&s->colors);
3763 goto done;
3767 view->show = show_log_view;
3768 view->input = input_log_view;
3769 view->resize = resize_log_view;
3770 view->close = close_log_view;
3771 view->search_start = search_start_log_view;
3772 view->search_next = search_next_log_view;
3774 if (s->thread_args.pack_fds == NULL) {
3775 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3776 if (err)
3777 goto done;
3779 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3780 s->thread_args.pack_fds);
3781 if (err)
3782 goto done;
3783 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3784 !s->log_branches);
3785 if (err)
3786 goto done;
3787 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3788 s->repo, NULL, NULL);
3789 if (err)
3790 goto done;
3792 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3793 if (errcode) {
3794 err = got_error_set_errno(errcode, "pthread_cond_init");
3795 goto done;
3797 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3798 if (errcode) {
3799 err = got_error_set_errno(errcode, "pthread_cond_init");
3800 goto done;
3803 s->thread_args.commits_needed = view->nlines;
3804 s->thread_args.graph = thread_graph;
3805 s->thread_args.real_commits = &s->real_commits;
3806 s->thread_args.limit_commits = &s->limit_commits;
3807 s->thread_args.in_repo_path = s->in_repo_path;
3808 s->thread_args.start_id = s->start_id;
3809 s->thread_args.repo = thread_repo;
3810 s->thread_args.log_complete = 0;
3811 s->thread_args.quit = &s->quit;
3812 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3813 s->thread_args.selected_entry = &s->selected_entry;
3814 s->thread_args.searching = &view->searching;
3815 s->thread_args.search_next_done = &view->search_next_done;
3816 s->thread_args.regex = &view->regex;
3817 s->thread_args.limiting = &s->limit_view;
3818 s->thread_args.limit_regex = &s->limit_regex;
3819 s->thread_args.limit_commits = &s->limit_commits;
3820 done:
3821 if (err) {
3822 if (view->close == NULL)
3823 close_log_view(view);
3824 view_close(view);
3826 return err;
3829 static const struct got_error *
3830 show_log_view(struct tog_view *view)
3832 const struct got_error *err;
3833 struct tog_log_view_state *s = &view->state.log;
3835 if (s->thread == 0) { //NULL) {
3836 int errcode = pthread_create(&s->thread, NULL, log_thread,
3837 &s->thread_args);
3838 if (errcode)
3839 return got_error_set_errno(errcode, "pthread_create");
3840 if (s->thread_args.commits_needed > 0) {
3841 err = trigger_log_thread(view, 1);
3842 if (err)
3843 return err;
3847 return draw_commits(view);
3850 static void
3851 log_move_cursor_up(struct tog_view *view, int page, int home)
3853 struct tog_log_view_state *s = &view->state.log;
3855 if (s->first_displayed_entry == NULL)
3856 return;
3857 if (s->selected_entry->idx == 0)
3858 view->count = 0;
3860 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3861 || home)
3862 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3864 if (!page && !home && s->selected > 0)
3865 --s->selected;
3866 else
3867 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3869 select_commit(s);
3870 return;
3873 static const struct got_error *
3874 log_move_cursor_down(struct tog_view *view, int page)
3876 struct tog_log_view_state *s = &view->state.log;
3877 const struct got_error *err = NULL;
3878 int eos = view->nlines - 2;
3880 if (s->first_displayed_entry == NULL)
3881 return NULL;
3883 if (s->thread_args.log_complete &&
3884 s->selected_entry->idx >= s->commits->ncommits - 1)
3885 return NULL;
3887 if (view_is_hsplit_top(view))
3888 --eos; /* border consumes the last line */
3890 if (!page) {
3891 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3892 ++s->selected;
3893 else
3894 err = log_scroll_down(view, 1);
3895 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3896 struct commit_queue_entry *entry;
3897 int n;
3899 s->selected = 0;
3900 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3901 s->last_displayed_entry = entry;
3902 for (n = 0; n <= eos; n++) {
3903 if (entry == NULL)
3904 break;
3905 s->first_displayed_entry = entry;
3906 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3908 if (n > 0)
3909 s->selected = n - 1;
3910 } else {
3911 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3912 s->thread_args.log_complete)
3913 s->selected += MIN(page,
3914 s->commits->ncommits - s->selected_entry->idx - 1);
3915 else
3916 err = log_scroll_down(view, page);
3918 if (err)
3919 return err;
3922 * We might necessarily overshoot in horizontal
3923 * splits; if so, select the last displayed commit.
3925 if (s->first_displayed_entry && s->last_displayed_entry) {
3926 s->selected = MIN(s->selected,
3927 s->last_displayed_entry->idx -
3928 s->first_displayed_entry->idx);
3931 select_commit(s);
3933 if (s->thread_args.log_complete &&
3934 s->selected_entry->idx == s->commits->ncommits - 1)
3935 view->count = 0;
3937 return NULL;
3940 static void
3941 view_get_split(struct tog_view *view, int *y, int *x)
3943 *x = 0;
3944 *y = 0;
3946 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3947 if (view->child && view->child->resized_y)
3948 *y = view->child->resized_y;
3949 else if (view->resized_y)
3950 *y = view->resized_y;
3951 else
3952 *y = view_split_begin_y(view->lines);
3953 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3954 if (view->child && view->child->resized_x)
3955 *x = view->child->resized_x;
3956 else if (view->resized_x)
3957 *x = view->resized_x;
3958 else
3959 *x = view_split_begin_x(view->begin_x);
3963 /* Split view horizontally at y and offset view->state->selected line. */
3964 static const struct got_error *
3965 view_init_hsplit(struct tog_view *view, int y)
3967 const struct got_error *err = NULL;
3969 view->nlines = y;
3970 view->ncols = COLS;
3971 err = view_resize(view);
3972 if (err)
3973 return err;
3975 err = offset_selection_down(view);
3977 return err;
3980 static const struct got_error *
3981 log_goto_line(struct tog_view *view, int nlines)
3983 const struct got_error *err = NULL;
3984 struct tog_log_view_state *s = &view->state.log;
3985 int g, idx = s->selected_entry->idx;
3987 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3988 return NULL;
3990 g = view->gline;
3991 view->gline = 0;
3993 if (g >= s->first_displayed_entry->idx + 1 &&
3994 g <= s->last_displayed_entry->idx + 1 &&
3995 g - s->first_displayed_entry->idx - 1 < nlines) {
3996 s->selected = g - s->first_displayed_entry->idx - 1;
3997 select_commit(s);
3998 return NULL;
4001 if (idx + 1 < g) {
4002 err = log_move_cursor_down(view, g - idx - 1);
4003 if (!err && g > s->selected_entry->idx + 1)
4004 err = log_move_cursor_down(view,
4005 g - s->first_displayed_entry->idx - 1);
4006 if (err)
4007 return err;
4008 } else if (idx + 1 > g)
4009 log_move_cursor_up(view, idx - g + 1, 0);
4011 if (g < nlines && s->first_displayed_entry->idx == 0)
4012 s->selected = g - 1;
4014 select_commit(s);
4015 return NULL;
4019 static void
4020 horizontal_scroll_input(struct tog_view *view, int ch)
4023 switch (ch) {
4024 case KEY_LEFT:
4025 case 'h':
4026 view->x -= MIN(view->x, 2);
4027 if (view->x <= 0)
4028 view->count = 0;
4029 break;
4030 case KEY_RIGHT:
4031 case 'l':
4032 if (view->x + view->ncols / 2 < view->maxx)
4033 view->x += 2;
4034 else
4035 view->count = 0;
4036 break;
4037 case '0':
4038 view->x = 0;
4039 break;
4040 case '$':
4041 view->x = MAX(view->maxx - view->ncols / 2, 0);
4042 view->count = 0;
4043 break;
4044 default:
4045 break;
4049 static const struct got_error *
4050 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
4052 const struct got_error *err = NULL;
4053 struct tog_log_view_state *s = &view->state.log;
4054 int eos, nscroll;
4056 if (s->thread_args.load_all) {
4057 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
4058 s->thread_args.load_all = 0;
4059 else if (s->thread_args.log_complete) {
4060 err = log_move_cursor_down(view, s->commits->ncommits);
4061 s->thread_args.load_all = 0;
4063 if (err)
4064 return err;
4067 eos = nscroll = view->nlines - 1;
4068 if (view_is_hsplit_top(view))
4069 --eos; /* border */
4071 if (view->gline)
4072 return log_goto_line(view, eos);
4074 switch (ch) {
4075 case '&':
4076 err = limit_log_view(view);
4077 break;
4078 case 'q':
4079 s->quit = 1;
4080 break;
4081 case '0':
4082 case '$':
4083 case KEY_RIGHT:
4084 case 'l':
4085 case KEY_LEFT:
4086 case 'h':
4087 horizontal_scroll_input(view, ch);
4088 break;
4089 case 'k':
4090 case KEY_UP:
4091 case '<':
4092 case ',':
4093 case CTRL('p'):
4094 log_move_cursor_up(view, 0, 0);
4095 break;
4096 case 'g':
4097 case '=':
4098 case KEY_HOME:
4099 log_move_cursor_up(view, 0, 1);
4100 view->count = 0;
4101 break;
4102 case CTRL('u'):
4103 case 'u':
4104 nscroll /= 2;
4105 /* FALL THROUGH */
4106 case KEY_PPAGE:
4107 case CTRL('b'):
4108 case 'b':
4109 log_move_cursor_up(view, nscroll, 0);
4110 break;
4111 case 'j':
4112 case KEY_DOWN:
4113 case '>':
4114 case '.':
4115 case CTRL('n'):
4116 err = log_move_cursor_down(view, 0);
4117 break;
4118 case '@':
4119 s->use_committer = !s->use_committer;
4120 view->action = s->use_committer ?
4121 "show committer" : "show commit author";
4122 break;
4123 case 'G':
4124 case '*':
4125 case KEY_END: {
4126 /* We don't know yet how many commits, so we're forced to
4127 * traverse them all. */
4128 view->count = 0;
4129 s->thread_args.load_all = 1;
4130 if (!s->thread_args.log_complete)
4131 return trigger_log_thread(view, 0);
4132 err = log_move_cursor_down(view, s->commits->ncommits);
4133 s->thread_args.load_all = 0;
4134 break;
4136 case CTRL('d'):
4137 case 'd':
4138 nscroll /= 2;
4139 /* FALL THROUGH */
4140 case KEY_NPAGE:
4141 case CTRL('f'):
4142 case 'f':
4143 case ' ':
4144 err = log_move_cursor_down(view, nscroll);
4145 break;
4146 case KEY_RESIZE:
4147 if (s->selected > view->nlines - 2)
4148 s->selected = view->nlines - 2;
4149 if (s->selected > s->commits->ncommits - 1)
4150 s->selected = s->commits->ncommits - 1;
4151 select_commit(s);
4152 if (s->commits->ncommits < view->nlines - 1 &&
4153 !s->thread_args.log_complete) {
4154 s->thread_args.commits_needed += (view->nlines - 1) -
4155 s->commits->ncommits;
4156 err = trigger_log_thread(view, 1);
4158 break;
4159 case KEY_ENTER:
4160 case '\r':
4161 view->count = 0;
4162 if (s->selected_entry == NULL)
4163 break;
4164 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4165 break;
4166 case 'T':
4167 view->count = 0;
4168 if (s->selected_entry == NULL)
4169 break;
4170 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4171 break;
4172 case KEY_BACKSPACE:
4173 case CTRL('l'):
4174 case 'B':
4175 view->count = 0;
4176 if (ch == KEY_BACKSPACE &&
4177 got_path_is_root_dir(s->in_repo_path))
4178 break;
4179 err = stop_log_thread(s);
4180 if (err)
4181 return err;
4182 if (ch == KEY_BACKSPACE) {
4183 char *parent_path;
4184 err = got_path_dirname(&parent_path, s->in_repo_path);
4185 if (err)
4186 return err;
4187 free(s->in_repo_path);
4188 s->in_repo_path = parent_path;
4189 s->thread_args.in_repo_path = s->in_repo_path;
4190 } else if (ch == CTRL('l')) {
4191 struct got_object_id *start_id;
4192 err = got_repo_match_object_id(&start_id, NULL,
4193 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4194 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4195 if (err) {
4196 if (s->head_ref_name == NULL ||
4197 err->code != GOT_ERR_NOT_REF)
4198 return err;
4199 /* Try to cope with deleted references. */
4200 free(s->head_ref_name);
4201 s->head_ref_name = NULL;
4202 err = got_repo_match_object_id(&start_id,
4203 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4204 &tog_refs, s->repo);
4205 if (err)
4206 return err;
4208 free(s->start_id);
4209 s->start_id = start_id;
4210 s->thread_args.start_id = s->start_id;
4211 } else /* 'B' */
4212 s->log_branches = !s->log_branches;
4214 if (s->thread_args.pack_fds == NULL) {
4215 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4216 if (err)
4217 return err;
4219 err = got_repo_open(&s->thread_args.repo,
4220 got_repo_get_path(s->repo), NULL,
4221 s->thread_args.pack_fds);
4222 if (err)
4223 return err;
4224 tog_free_refs();
4225 err = tog_load_refs(s->repo, 0);
4226 if (err)
4227 return err;
4228 err = got_commit_graph_open(&s->thread_args.graph,
4229 s->in_repo_path, !s->log_branches);
4230 if (err)
4231 return err;
4232 err = got_commit_graph_iter_start(s->thread_args.graph,
4233 s->start_id, s->repo, NULL, NULL);
4234 if (err)
4235 return err;
4236 free_commits(&s->real_commits);
4237 free_commits(&s->limit_commits);
4238 s->first_displayed_entry = NULL;
4239 s->last_displayed_entry = NULL;
4240 s->selected_entry = NULL;
4241 s->selected = 0;
4242 s->thread_args.log_complete = 0;
4243 s->quit = 0;
4244 s->thread_args.commits_needed = view->lines;
4245 s->matched_entry = NULL;
4246 s->search_entry = NULL;
4247 view->offset = 0;
4248 break;
4249 case 'R':
4250 view->count = 0;
4251 err = view_request_new(new_view, view, TOG_VIEW_REF);
4252 break;
4253 default:
4254 view->count = 0;
4255 break;
4258 return err;
4261 static const struct got_error *
4262 apply_unveil(const char *repo_path, const char *worktree_path)
4264 const struct got_error *error;
4266 #ifdef PROFILE
4267 if (unveil("gmon.out", "rwc") != 0)
4268 return got_error_from_errno2("unveil", "gmon.out");
4269 #endif
4270 if (repo_path && unveil(repo_path, "r") != 0)
4271 return got_error_from_errno2("unveil", repo_path);
4273 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4274 return got_error_from_errno2("unveil", worktree_path);
4276 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4277 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4279 error = got_privsep_unveil_exec_helpers();
4280 if (error != NULL)
4281 return error;
4283 if (unveil(NULL, NULL) != 0)
4284 return got_error_from_errno("unveil");
4286 return NULL;
4289 static const struct got_error *
4290 init_mock_term(const char *test_script_path)
4292 const struct got_error *err = NULL;
4293 const char *screen_dump_path;
4294 int in;
4296 if (test_script_path == NULL || *test_script_path == '\0')
4297 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4299 tog_io.f = fopen(test_script_path, "re");
4300 if (tog_io.f == NULL) {
4301 err = got_error_from_errno_fmt("fopen: %s",
4302 test_script_path);
4303 goto done;
4306 /* test mode, we don't want any output */
4307 tog_io.cout = fopen("/dev/null", "w+");
4308 if (tog_io.cout == NULL) {
4309 err = got_error_from_errno2("fopen", "/dev/null");
4310 goto done;
4313 in = dup(fileno(tog_io.cout));
4314 if (in == -1) {
4315 err = got_error_from_errno("dup");
4316 goto done;
4318 tog_io.cin = fdopen(in, "r");
4319 if (tog_io.cin == NULL) {
4320 err = got_error_from_errno("fdopen");
4321 close(in);
4322 goto done;
4325 screen_dump_path = getenv("TOG_SCR_DUMP");
4326 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4327 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4328 tog_io.sdump = fopen(screen_dump_path, "we");
4329 if (tog_io.sdump == NULL) {
4330 err = got_error_from_errno2("fopen", screen_dump_path);
4331 goto done;
4334 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4335 err = got_error_from_errno("fseeko");
4336 goto done;
4339 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4340 err = got_error_msg(GOT_ERR_IO,
4341 "newterm: failed to initialise curses");
4343 using_mock_io = 1;
4345 done:
4346 if (err)
4347 tog_io_close();
4348 return err;
4351 static void
4352 init_curses(void)
4355 * Override default signal handlers before starting ncurses.
4356 * This should prevent ncurses from installing its own
4357 * broken cleanup() signal handler.
4359 signal(SIGWINCH, tog_sigwinch);
4360 signal(SIGPIPE, tog_sigpipe);
4361 signal(SIGCONT, tog_sigcont);
4362 signal(SIGINT, tog_sigint);
4363 signal(SIGTERM, tog_sigterm);
4365 if (using_mock_io) /* In test mode we use a fake terminal */
4366 return;
4368 initscr();
4370 cbreak();
4371 halfdelay(1); /* Fast refresh while initial view is loading. */
4372 noecho();
4373 nonl();
4374 intrflush(stdscr, FALSE);
4375 keypad(stdscr, TRUE);
4376 curs_set(0);
4377 if (getenv("TOG_COLORS") != NULL) {
4378 start_color();
4379 use_default_colors();
4382 return;
4385 static const struct got_error *
4386 set_tog_base_commit(struct got_repository *repo, struct got_worktree *worktree)
4388 tog_base_commit.id = got_object_id_dup(
4389 got_worktree_get_base_commit_id(worktree));
4390 if (tog_base_commit.id == NULL)
4391 return got_error_from_errno( "got_object_id_dup");
4393 tog_base_commit.idx = -1;
4395 return got_worktree_get_state(&tog_base_commit.marker, repo,
4396 worktree);
4399 static const struct got_error *
4400 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4401 struct got_repository *repo, struct got_worktree *worktree)
4403 const struct got_error *err = NULL;
4405 if (argc == 0) {
4406 *in_repo_path = strdup("/");
4407 if (*in_repo_path == NULL)
4408 return got_error_from_errno("strdup");
4409 return NULL;
4412 if (worktree) {
4413 const char *prefix = got_worktree_get_path_prefix(worktree);
4414 char *p;
4416 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4417 if (err)
4418 return err;
4419 if (asprintf(in_repo_path, "%s%s%s", prefix,
4420 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4421 p) == -1) {
4422 err = got_error_from_errno("asprintf");
4423 *in_repo_path = NULL;
4425 free(p);
4426 } else
4427 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4429 return err;
4432 static const struct got_error *
4433 cmd_log(int argc, char *argv[])
4435 const struct got_error *error;
4436 struct got_repository *repo = NULL;
4437 struct got_worktree *worktree = NULL;
4438 struct got_object_id *start_id = NULL;
4439 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4440 char *keyword_idstr = NULL, *start_commit = NULL, *label = NULL;
4441 struct got_reference *ref = NULL;
4442 const char *head_ref_name = NULL;
4443 int ch, log_branches = 0;
4444 struct tog_view *view;
4445 int *pack_fds = NULL;
4447 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4448 switch (ch) {
4449 case 'b':
4450 log_branches = 1;
4451 break;
4452 case 'c':
4453 start_commit = optarg;
4454 break;
4455 case 'r':
4456 repo_path = realpath(optarg, NULL);
4457 if (repo_path == NULL)
4458 return got_error_from_errno2("realpath",
4459 optarg);
4460 break;
4461 default:
4462 usage_log();
4463 /* NOTREACHED */
4467 argc -= optind;
4468 argv += optind;
4470 if (argc > 1)
4471 usage_log();
4473 error = got_repo_pack_fds_open(&pack_fds);
4474 if (error != NULL)
4475 goto done;
4477 if (repo_path == NULL) {
4478 cwd = getcwd(NULL, 0);
4479 if (cwd == NULL)
4480 return got_error_from_errno("getcwd");
4481 error = got_worktree_open(&worktree, cwd, NULL);
4482 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4483 goto done;
4484 if (worktree)
4485 repo_path =
4486 strdup(got_worktree_get_repo_path(worktree));
4487 else
4488 repo_path = strdup(cwd);
4489 if (repo_path == NULL) {
4490 error = got_error_from_errno("strdup");
4491 goto done;
4495 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4496 if (error != NULL)
4497 goto done;
4499 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4500 repo, worktree);
4501 if (error)
4502 goto done;
4504 init_curses();
4506 error = apply_unveil(got_repo_get_path(repo),
4507 worktree ? got_worktree_get_root_path(worktree) : NULL);
4508 if (error)
4509 goto done;
4511 /* already loaded by tog_log_with_path()? */
4512 if (TAILQ_EMPTY(&tog_refs)) {
4513 error = tog_load_refs(repo, 0);
4514 if (error)
4515 goto done;
4518 if (start_commit == NULL) {
4519 error = got_repo_match_object_id(&start_id, &label,
4520 worktree ? got_worktree_get_head_ref_name(worktree) :
4521 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4522 if (error)
4523 goto done;
4524 head_ref_name = label;
4525 } else {
4526 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4527 repo, worktree);
4528 if (error != NULL)
4529 goto done;
4530 if (keyword_idstr != NULL)
4531 start_commit = keyword_idstr;
4533 error = got_ref_open(&ref, repo, start_commit, 0);
4534 if (error == NULL)
4535 head_ref_name = got_ref_get_name(ref);
4536 else if (error->code != GOT_ERR_NOT_REF)
4537 goto done;
4538 error = got_repo_match_object_id(&start_id, NULL,
4539 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4540 if (error)
4541 goto done;
4544 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4545 if (view == NULL) {
4546 error = got_error_from_errno("view_open");
4547 goto done;
4549 error = open_log_view(view, start_id, repo, head_ref_name,
4550 in_repo_path, log_branches);
4551 if (error)
4552 goto done;
4554 if (worktree) {
4555 error = set_tog_base_commit(repo, worktree);
4556 if (error != NULL)
4557 goto done;
4559 /* Release work tree lock. */
4560 got_worktree_close(worktree);
4561 worktree = NULL;
4564 error = view_loop(view);
4566 done:
4567 free(tog_base_commit.id);
4568 free(keyword_idstr);
4569 free(in_repo_path);
4570 free(repo_path);
4571 free(cwd);
4572 free(start_id);
4573 free(label);
4574 if (ref)
4575 got_ref_close(ref);
4576 if (repo) {
4577 const struct got_error *close_err = got_repo_close(repo);
4578 if (error == NULL)
4579 error = close_err;
4581 if (worktree)
4582 got_worktree_close(worktree);
4583 if (pack_fds) {
4584 const struct got_error *pack_err =
4585 got_repo_pack_fds_close(pack_fds);
4586 if (error == NULL)
4587 error = pack_err;
4589 tog_free_refs();
4590 return error;
4593 __dead static void
4594 usage_diff(void)
4596 endwin();
4597 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4598 "object1 object2\n", getprogname());
4599 exit(1);
4602 static int
4603 match_line(const char *line, regex_t *regex, size_t nmatch,
4604 regmatch_t *regmatch)
4606 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4609 static struct tog_color *
4610 match_color(struct tog_colors *colors, const char *line)
4612 struct tog_color *tc = NULL;
4614 STAILQ_FOREACH(tc, colors, entry) {
4615 if (match_line(line, &tc->regex, 0, NULL))
4616 return tc;
4619 return NULL;
4622 static const struct got_error *
4623 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4624 WINDOW *window, int skipcol, regmatch_t *regmatch)
4626 const struct got_error *err = NULL;
4627 char *exstr = NULL;
4628 wchar_t *wline = NULL;
4629 int rme, rms, n, width, scrollx;
4630 int width0 = 0, width1 = 0, width2 = 0;
4631 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4633 *wtotal = 0;
4635 rms = regmatch->rm_so;
4636 rme = regmatch->rm_eo;
4638 err = expand_tab(&exstr, line);
4639 if (err)
4640 return err;
4642 /* Split the line into 3 segments, according to match offsets. */
4643 seg0 = strndup(exstr, rms);
4644 if (seg0 == NULL) {
4645 err = got_error_from_errno("strndup");
4646 goto done;
4648 seg1 = strndup(exstr + rms, rme - rms);
4649 if (seg1 == NULL) {
4650 err = got_error_from_errno("strndup");
4651 goto done;
4653 seg2 = strdup(exstr + rme);
4654 if (seg2 == NULL) {
4655 err = got_error_from_errno("strndup");
4656 goto done;
4659 /* draw up to matched token if we haven't scrolled past it */
4660 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4661 col_tab_align, 1);
4662 if (err)
4663 goto done;
4664 n = MAX(width0 - skipcol, 0);
4665 if (n) {
4666 free(wline);
4667 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4668 wlimit, col_tab_align, 1);
4669 if (err)
4670 goto done;
4671 waddwstr(window, &wline[scrollx]);
4672 wlimit -= width;
4673 *wtotal += width;
4676 if (wlimit > 0) {
4677 int i = 0, w = 0;
4678 size_t wlen;
4680 free(wline);
4681 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4682 col_tab_align, 1);
4683 if (err)
4684 goto done;
4685 wlen = wcslen(wline);
4686 while (i < wlen) {
4687 width = wcwidth(wline[i]);
4688 if (width == -1) {
4689 /* should not happen, tabs are expanded */
4690 err = got_error(GOT_ERR_RANGE);
4691 goto done;
4693 if (width0 + w + width > skipcol)
4694 break;
4695 w += width;
4696 i++;
4698 /* draw (visible part of) matched token (if scrolled into it) */
4699 if (width1 - w > 0) {
4700 wattron(window, A_STANDOUT);
4701 waddwstr(window, &wline[i]);
4702 wattroff(window, A_STANDOUT);
4703 wlimit -= (width1 - w);
4704 *wtotal += (width1 - w);
4708 if (wlimit > 0) { /* draw rest of line */
4709 free(wline);
4710 if (skipcol > width0 + width1) {
4711 err = format_line(&wline, &width2, &scrollx, seg2,
4712 skipcol - (width0 + width1), wlimit,
4713 col_tab_align, 1);
4714 if (err)
4715 goto done;
4716 waddwstr(window, &wline[scrollx]);
4717 } else {
4718 err = format_line(&wline, &width2, NULL, seg2, 0,
4719 wlimit, col_tab_align, 1);
4720 if (err)
4721 goto done;
4722 waddwstr(window, wline);
4724 *wtotal += width2;
4726 done:
4727 free(wline);
4728 free(exstr);
4729 free(seg0);
4730 free(seg1);
4731 free(seg2);
4732 return err;
4735 static int
4736 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4738 FILE *f = NULL;
4739 int *eof, *first, *selected;
4741 if (view->type == TOG_VIEW_DIFF) {
4742 struct tog_diff_view_state *s = &view->state.diff;
4744 first = &s->first_displayed_line;
4745 selected = first;
4746 eof = &s->eof;
4747 f = s->f;
4748 } else if (view->type == TOG_VIEW_HELP) {
4749 struct tog_help_view_state *s = &view->state.help;
4751 first = &s->first_displayed_line;
4752 selected = first;
4753 eof = &s->eof;
4754 f = s->f;
4755 } else if (view->type == TOG_VIEW_BLAME) {
4756 struct tog_blame_view_state *s = &view->state.blame;
4758 first = &s->first_displayed_line;
4759 selected = &s->selected_line;
4760 eof = &s->eof;
4761 f = s->blame.f;
4762 } else
4763 return 0;
4765 /* Center gline in the middle of the page like vi(1). */
4766 if (*lineno < view->gline - (view->nlines - 3) / 2)
4767 return 0;
4768 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4769 rewind(f);
4770 *eof = 0;
4771 *first = 1;
4772 *lineno = 0;
4773 *nprinted = 0;
4774 return 0;
4777 *selected = view->gline <= (view->nlines - 3) / 2 ?
4778 view->gline : (view->nlines - 3) / 2 + 1;
4779 view->gline = 0;
4781 return 1;
4784 static const struct got_error *
4785 draw_file(struct tog_view *view, const char *header)
4787 struct tog_diff_view_state *s = &view->state.diff;
4788 regmatch_t *regmatch = &view->regmatch;
4789 const struct got_error *err;
4790 int nprinted = 0;
4791 char *line;
4792 size_t linesize = 0;
4793 ssize_t linelen;
4794 wchar_t *wline;
4795 int width;
4796 int max_lines = view->nlines;
4797 int nlines = s->nlines;
4798 off_t line_offset;
4800 s->lineno = s->first_displayed_line - 1;
4801 line_offset = s->lines[s->first_displayed_line - 1].offset;
4802 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4803 return got_error_from_errno("fseek");
4805 werase(view->window);
4807 if (view->gline > s->nlines - 1)
4808 view->gline = s->nlines - 1;
4810 if (header) {
4811 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4812 1 : view->gline - (view->nlines - 3) / 2 :
4813 s->lineno + s->selected_line;
4815 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4816 return got_error_from_errno("asprintf");
4817 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4818 0, 0);
4819 free(line);
4820 if (err)
4821 return err;
4823 if (view_needs_focus_indication(view))
4824 wstandout(view->window);
4825 waddwstr(view->window, wline);
4826 free(wline);
4827 wline = NULL;
4828 while (width++ < view->ncols)
4829 waddch(view->window, ' ');
4830 if (view_needs_focus_indication(view))
4831 wstandend(view->window);
4833 if (max_lines <= 1)
4834 return NULL;
4835 max_lines--;
4838 s->eof = 0;
4839 view->maxx = 0;
4840 line = NULL;
4841 while (max_lines > 0 && nprinted < max_lines) {
4842 enum got_diff_line_type linetype;
4843 attr_t attr = 0;
4845 linelen = getline(&line, &linesize, s->f);
4846 if (linelen == -1) {
4847 if (feof(s->f)) {
4848 s->eof = 1;
4849 break;
4851 free(line);
4852 return got_ferror(s->f, GOT_ERR_IO);
4855 if (++s->lineno < s->first_displayed_line)
4856 continue;
4857 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4858 continue;
4859 if (s->lineno == view->hiline)
4860 attr = A_STANDOUT;
4862 /* Set view->maxx based on full line length. */
4863 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4864 view->x ? 1 : 0);
4865 if (err) {
4866 free(line);
4867 return err;
4869 view->maxx = MAX(view->maxx, width);
4870 free(wline);
4871 wline = NULL;
4873 linetype = s->lines[s->lineno].type;
4874 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4875 linetype < GOT_DIFF_LINE_CONTEXT)
4876 attr |= COLOR_PAIR(linetype);
4877 if (attr)
4878 wattron(view->window, attr);
4879 if (s->first_displayed_line + nprinted == s->matched_line &&
4880 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4881 err = add_matched_line(&width, line, view->ncols, 0,
4882 view->window, view->x, regmatch);
4883 if (err) {
4884 free(line);
4885 return err;
4887 } else {
4888 int skip;
4889 err = format_line(&wline, &width, &skip, line,
4890 view->x, view->ncols, 0, view->x ? 1 : 0);
4891 if (err) {
4892 free(line);
4893 return err;
4895 waddwstr(view->window, &wline[skip]);
4896 free(wline);
4897 wline = NULL;
4899 if (s->lineno == view->hiline) {
4900 /* highlight full gline length */
4901 while (width++ < view->ncols)
4902 waddch(view->window, ' ');
4903 } else {
4904 if (width <= view->ncols - 1)
4905 waddch(view->window, '\n');
4907 if (attr)
4908 wattroff(view->window, attr);
4909 if (++nprinted == 1)
4910 s->first_displayed_line = s->lineno;
4912 free(line);
4913 if (nprinted >= 1)
4914 s->last_displayed_line = s->first_displayed_line +
4915 (nprinted - 1);
4916 else
4917 s->last_displayed_line = s->first_displayed_line;
4919 view_border(view);
4921 if (s->eof) {
4922 while (nprinted < view->nlines) {
4923 waddch(view->window, '\n');
4924 nprinted++;
4927 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4928 view->ncols, 0, 0);
4929 if (err) {
4930 return err;
4933 wstandout(view->window);
4934 waddwstr(view->window, wline);
4935 free(wline);
4936 wline = NULL;
4937 wstandend(view->window);
4940 return NULL;
4943 static char *
4944 get_datestr(time_t *time, char *datebuf)
4946 struct tm mytm, *tm;
4947 char *p, *s;
4949 tm = gmtime_r(time, &mytm);
4950 if (tm == NULL)
4951 return NULL;
4952 s = asctime_r(tm, datebuf);
4953 if (s == NULL)
4954 return NULL;
4955 p = strchr(s, '\n');
4956 if (p)
4957 *p = '\0';
4958 return s;
4961 static const struct got_error *
4962 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4963 off_t off, uint8_t type)
4965 struct got_diff_line *p;
4967 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4968 if (p == NULL)
4969 return got_error_from_errno("reallocarray");
4970 *lines = p;
4971 (*lines)[*nlines].offset = off;
4972 (*lines)[*nlines].type = type;
4973 (*nlines)++;
4975 return NULL;
4978 static const struct got_error *
4979 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4980 struct got_diff_line *s_lines, size_t s_nlines)
4982 struct got_diff_line *p;
4983 char buf[BUFSIZ];
4984 size_t i, r;
4986 if (fseeko(src, 0L, SEEK_SET) == -1)
4987 return got_error_from_errno("fseeko");
4989 for (;;) {
4990 r = fread(buf, 1, sizeof(buf), src);
4991 if (r == 0) {
4992 if (ferror(src))
4993 return got_error_from_errno("fread");
4994 if (feof(src))
4995 break;
4997 if (fwrite(buf, 1, r, dst) != r)
4998 return got_ferror(dst, GOT_ERR_IO);
5001 if (s_nlines == 0 && *d_nlines == 0)
5002 return NULL;
5005 * If commit info was in dst, increment line offsets
5006 * of the appended diff content, but skip s_lines[0]
5007 * because offset zero is already in *d_lines.
5009 if (*d_nlines > 0) {
5010 for (i = 1; i < s_nlines; ++i)
5011 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
5013 if (s_nlines > 0) {
5014 --s_nlines;
5015 ++s_lines;
5019 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
5020 if (p == NULL) {
5021 /* d_lines is freed in close_diff_view() */
5022 return got_error_from_errno("reallocarray");
5025 *d_lines = p;
5027 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
5028 *d_nlines += s_nlines;
5030 return NULL;
5033 static const struct got_error *
5034 write_commit_info(struct got_diff_line **lines, size_t *nlines,
5035 struct got_object_id *commit_id, struct got_reflist_head *refs,
5036 struct got_repository *repo, int ignore_ws, int force_text_diff,
5037 struct got_diffstat_cb_arg *dsa, FILE *outfile)
5039 const struct got_error *err = NULL;
5040 char datebuf[26], *datestr;
5041 struct got_commit_object *commit;
5042 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
5043 time_t committer_time;
5044 const char *author, *committer;
5045 char *refs_str = NULL;
5046 struct got_pathlist_entry *pe;
5047 off_t outoff = 0;
5048 int n;
5050 err = build_refs_str(&refs_str, refs, commit_id, repo);
5051 if (err)
5052 return err;
5054 err = got_object_open_as_commit(&commit, repo, commit_id);
5055 if (err)
5056 return err;
5058 err = got_object_id_str(&id_str, commit_id);
5059 if (err) {
5060 err = got_error_from_errno("got_object_id_str");
5061 goto done;
5064 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
5065 if (err)
5066 goto done;
5068 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
5069 refs_str ? refs_str : "", refs_str ? ")" : "");
5070 if (n < 0) {
5071 err = got_error_from_errno("fprintf");
5072 goto done;
5074 outoff += n;
5075 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
5076 if (err)
5077 goto done;
5079 n = fprintf(outfile, "from: %s\n",
5080 got_object_commit_get_author(commit));
5081 if (n < 0) {
5082 err = got_error_from_errno("fprintf");
5083 goto done;
5085 outoff += n;
5086 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
5087 if (err)
5088 goto done;
5090 author = got_object_commit_get_author(commit);
5091 committer = got_object_commit_get_committer(commit);
5092 if (strcmp(author, committer) != 0) {
5093 n = fprintf(outfile, "via: %s\n", committer);
5094 if (n < 0) {
5095 err = got_error_from_errno("fprintf");
5096 goto done;
5098 outoff += n;
5099 err = add_line_metadata(lines, nlines, outoff,
5100 GOT_DIFF_LINE_AUTHOR);
5101 if (err)
5102 goto done;
5104 committer_time = got_object_commit_get_committer_time(commit);
5105 datestr = get_datestr(&committer_time, datebuf);
5106 if (datestr) {
5107 n = fprintf(outfile, "date: %s UTC\n", datestr);
5108 if (n < 0) {
5109 err = got_error_from_errno("fprintf");
5110 goto done;
5112 outoff += n;
5113 err = add_line_metadata(lines, nlines, outoff,
5114 GOT_DIFF_LINE_DATE);
5115 if (err)
5116 goto done;
5118 if (got_object_commit_get_nparents(commit) > 1) {
5119 const struct got_object_id_queue *parent_ids;
5120 struct got_object_qid *qid;
5121 int pn = 1;
5122 parent_ids = got_object_commit_get_parent_ids(commit);
5123 STAILQ_FOREACH(qid, parent_ids, entry) {
5124 err = got_object_id_str(&id_str, &qid->id);
5125 if (err)
5126 goto done;
5127 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5128 if (n < 0) {
5129 err = got_error_from_errno("fprintf");
5130 goto done;
5132 outoff += n;
5133 err = add_line_metadata(lines, nlines, outoff,
5134 GOT_DIFF_LINE_META);
5135 if (err)
5136 goto done;
5137 free(id_str);
5138 id_str = NULL;
5142 err = got_object_commit_get_logmsg(&logmsg, commit);
5143 if (err)
5144 goto done;
5145 s = logmsg;
5146 while ((line = strsep(&s, "\n")) != NULL) {
5147 n = fprintf(outfile, "%s\n", line);
5148 if (n < 0) {
5149 err = got_error_from_errno("fprintf");
5150 goto done;
5152 outoff += n;
5153 err = add_line_metadata(lines, nlines, outoff,
5154 GOT_DIFF_LINE_LOGMSG);
5155 if (err)
5156 goto done;
5159 TAILQ_FOREACH(pe, dsa->paths, entry) {
5160 struct got_diff_changed_path *cp = pe->data;
5161 int pad = dsa->max_path_len - pe->path_len + 1;
5163 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5164 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5165 dsa->rm_cols + 1, cp->rm);
5166 if (n < 0) {
5167 err = got_error_from_errno("fprintf");
5168 goto done;
5170 outoff += n;
5171 err = add_line_metadata(lines, nlines, outoff,
5172 GOT_DIFF_LINE_CHANGES);
5173 if (err)
5174 goto done;
5177 fputc('\n', outfile);
5178 outoff++;
5179 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5180 if (err)
5181 goto done;
5183 n = fprintf(outfile,
5184 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5185 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5186 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5187 if (n < 0) {
5188 err = got_error_from_errno("fprintf");
5189 goto done;
5191 outoff += n;
5192 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5193 if (err)
5194 goto done;
5196 fputc('\n', outfile);
5197 outoff++;
5198 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5199 done:
5200 free(id_str);
5201 free(logmsg);
5202 free(refs_str);
5203 got_object_commit_close(commit);
5204 if (err) {
5205 free(*lines);
5206 *lines = NULL;
5207 *nlines = 0;
5209 return err;
5212 static const struct got_error *
5213 create_diff(struct tog_diff_view_state *s)
5215 const struct got_error *err = NULL;
5216 FILE *f = NULL, *tmp_diff_file = NULL;
5217 int obj_type;
5218 struct got_diff_line *lines = NULL;
5219 struct got_pathlist_head changed_paths;
5221 TAILQ_INIT(&changed_paths);
5223 free(s->lines);
5224 s->lines = malloc(sizeof(*s->lines));
5225 if (s->lines == NULL)
5226 return got_error_from_errno("malloc");
5227 s->nlines = 0;
5229 f = got_opentemp();
5230 if (f == NULL) {
5231 err = got_error_from_errno("got_opentemp");
5232 goto done;
5234 tmp_diff_file = got_opentemp();
5235 if (tmp_diff_file == NULL) {
5236 err = got_error_from_errno("got_opentemp");
5237 goto done;
5239 if (s->f && fclose(s->f) == EOF) {
5240 err = got_error_from_errno("fclose");
5241 goto done;
5243 s->f = f;
5245 if (s->id1)
5246 err = got_object_get_type(&obj_type, s->repo, s->id1);
5247 else
5248 err = got_object_get_type(&obj_type, s->repo, s->id2);
5249 if (err)
5250 goto done;
5252 switch (obj_type) {
5253 case GOT_OBJ_TYPE_BLOB:
5254 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5255 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5256 s->label1, s->label2, tog_diff_algo, s->diff_context,
5257 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5258 s->f);
5259 break;
5260 case GOT_OBJ_TYPE_TREE:
5261 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5262 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5263 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5264 s->force_text_diff, NULL, s->repo, s->f);
5265 break;
5266 case GOT_OBJ_TYPE_COMMIT: {
5267 const struct got_object_id_queue *parent_ids;
5268 struct got_object_qid *pid;
5269 struct got_commit_object *commit2;
5270 struct got_reflist_head *refs;
5271 size_t nlines = 0;
5272 struct got_diffstat_cb_arg dsa = {
5273 0, 0, 0, 0, 0, 0,
5274 &changed_paths,
5275 s->ignore_whitespace,
5276 s->force_text_diff,
5277 tog_diff_algo
5280 lines = malloc(sizeof(*lines));
5281 if (lines == NULL) {
5282 err = got_error_from_errno("malloc");
5283 goto done;
5286 /* build diff first in tmp file then append to commit info */
5287 err = got_diff_objects_as_commits(&lines, &nlines,
5288 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5289 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5290 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5291 if (err)
5292 break;
5294 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5295 if (err)
5296 goto done;
5297 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5298 /* Show commit info if we're diffing to a parent/root commit. */
5299 if (s->id1 == NULL) {
5300 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5301 refs, s->repo, s->ignore_whitespace,
5302 s->force_text_diff, &dsa, s->f);
5303 if (err)
5304 goto done;
5305 } else {
5306 parent_ids = got_object_commit_get_parent_ids(commit2);
5307 STAILQ_FOREACH(pid, parent_ids, entry) {
5308 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5309 err = write_commit_info(&s->lines,
5310 &s->nlines, s->id2, refs, s->repo,
5311 s->ignore_whitespace,
5312 s->force_text_diff, &dsa, s->f);
5313 if (err)
5314 goto done;
5315 break;
5319 got_object_commit_close(commit2);
5321 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5322 lines, nlines);
5323 break;
5325 default:
5326 err = got_error(GOT_ERR_OBJ_TYPE);
5327 break;
5329 done:
5330 free(lines);
5331 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5332 if (s->f && fflush(s->f) != 0 && err == NULL)
5333 err = got_error_from_errno("fflush");
5334 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5335 err = got_error_from_errno("fclose");
5336 return err;
5339 static void
5340 diff_view_indicate_progress(struct tog_view *view)
5342 mvwaddstr(view->window, 0, 0, "diffing...");
5343 update_panels();
5344 doupdate();
5347 static const struct got_error *
5348 search_start_diff_view(struct tog_view *view)
5350 struct tog_diff_view_state *s = &view->state.diff;
5352 s->matched_line = 0;
5353 return NULL;
5356 static void
5357 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5358 size_t *nlines, int **first, int **last, int **match, int **selected)
5360 struct tog_diff_view_state *s = &view->state.diff;
5362 *f = s->f;
5363 *nlines = s->nlines;
5364 *line_offsets = NULL;
5365 *match = &s->matched_line;
5366 *first = &s->first_displayed_line;
5367 *last = &s->last_displayed_line;
5368 *selected = &s->selected_line;
5371 static const struct got_error *
5372 search_next_view_match(struct tog_view *view)
5374 const struct got_error *err = NULL;
5375 FILE *f;
5376 int lineno;
5377 char *line = NULL;
5378 size_t linesize = 0;
5379 ssize_t linelen;
5380 off_t *line_offsets;
5381 size_t nlines = 0;
5382 int *first, *last, *match, *selected;
5384 if (!view->search_setup)
5385 return got_error_msg(GOT_ERR_NOT_IMPL,
5386 "view search not supported");
5387 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5388 &match, &selected);
5390 if (!view->searching) {
5391 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5392 return NULL;
5395 if (*match) {
5396 if (view->searching == TOG_SEARCH_FORWARD)
5397 lineno = *first + 1;
5398 else
5399 lineno = *first - 1;
5400 } else
5401 lineno = *first - 1 + *selected;
5403 while (1) {
5404 off_t offset;
5406 if (lineno <= 0 || lineno > nlines) {
5407 if (*match == 0) {
5408 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5409 break;
5412 if (view->searching == TOG_SEARCH_FORWARD)
5413 lineno = 1;
5414 else
5415 lineno = nlines;
5418 offset = view->type == TOG_VIEW_DIFF ?
5419 view->state.diff.lines[lineno - 1].offset :
5420 line_offsets[lineno - 1];
5421 if (fseeko(f, offset, SEEK_SET) != 0) {
5422 free(line);
5423 return got_error_from_errno("fseeko");
5425 linelen = getline(&line, &linesize, f);
5426 if (linelen != -1) {
5427 char *exstr;
5428 err = expand_tab(&exstr, line);
5429 if (err)
5430 break;
5431 if (match_line(exstr, &view->regex, 1,
5432 &view->regmatch)) {
5433 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5434 *match = lineno;
5435 free(exstr);
5436 break;
5438 free(exstr);
5440 if (view->searching == TOG_SEARCH_FORWARD)
5441 lineno++;
5442 else
5443 lineno--;
5445 free(line);
5447 if (*match) {
5448 *first = *match;
5449 *selected = 1;
5452 return err;
5455 static const struct got_error *
5456 close_diff_view(struct tog_view *view)
5458 const struct got_error *err = NULL;
5459 struct tog_diff_view_state *s = &view->state.diff;
5461 free(s->id1);
5462 s->id1 = NULL;
5463 free(s->id2);
5464 s->id2 = NULL;
5465 if (s->f && fclose(s->f) == EOF)
5466 err = got_error_from_errno("fclose");
5467 s->f = NULL;
5468 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5469 err = got_error_from_errno("fclose");
5470 s->f1 = NULL;
5471 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5472 err = got_error_from_errno("fclose");
5473 s->f2 = NULL;
5474 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5475 err = got_error_from_errno("close");
5476 s->fd1 = -1;
5477 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5478 err = got_error_from_errno("close");
5479 s->fd2 = -1;
5480 free(s->lines);
5481 s->lines = NULL;
5482 s->nlines = 0;
5483 return err;
5486 static const struct got_error *
5487 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5488 struct got_object_id *id2, const char *label1, const char *label2,
5489 int diff_context, int ignore_whitespace, int force_text_diff,
5490 struct tog_view *parent_view, struct got_repository *repo)
5492 const struct got_error *err;
5493 struct tog_diff_view_state *s = &view->state.diff;
5495 memset(s, 0, sizeof(*s));
5496 s->fd1 = -1;
5497 s->fd2 = -1;
5499 if (id1 != NULL && id2 != NULL) {
5500 int type1, type2;
5502 err = got_object_get_type(&type1, repo, id1);
5503 if (err)
5504 goto done;
5505 err = got_object_get_type(&type2, repo, id2);
5506 if (err)
5507 goto done;
5509 if (type1 != type2) {
5510 err = got_error(GOT_ERR_OBJ_TYPE);
5511 goto done;
5514 s->first_displayed_line = 1;
5515 s->last_displayed_line = view->nlines;
5516 s->selected_line = 1;
5517 s->repo = repo;
5518 s->id1 = id1;
5519 s->id2 = id2;
5520 s->label1 = label1;
5521 s->label2 = label2;
5523 if (id1) {
5524 s->id1 = got_object_id_dup(id1);
5525 if (s->id1 == NULL) {
5526 err = got_error_from_errno("got_object_id_dup");
5527 goto done;
5529 } else
5530 s->id1 = NULL;
5532 s->id2 = got_object_id_dup(id2);
5533 if (s->id2 == NULL) {
5534 err = got_error_from_errno("got_object_id_dup");
5535 goto done;
5538 s->f1 = got_opentemp();
5539 if (s->f1 == NULL) {
5540 err = got_error_from_errno("got_opentemp");
5541 goto done;
5544 s->f2 = got_opentemp();
5545 if (s->f2 == NULL) {
5546 err = got_error_from_errno("got_opentemp");
5547 goto done;
5550 s->fd1 = got_opentempfd();
5551 if (s->fd1 == -1) {
5552 err = got_error_from_errno("got_opentempfd");
5553 goto done;
5556 s->fd2 = got_opentempfd();
5557 if (s->fd2 == -1) {
5558 err = got_error_from_errno("got_opentempfd");
5559 goto done;
5562 s->diff_context = diff_context;
5563 s->ignore_whitespace = ignore_whitespace;
5564 s->force_text_diff = force_text_diff;
5565 s->parent_view = parent_view;
5566 s->repo = repo;
5568 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5569 int rc;
5571 rc = init_pair(GOT_DIFF_LINE_MINUS,
5572 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5573 if (rc != ERR)
5574 rc = init_pair(GOT_DIFF_LINE_PLUS,
5575 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5576 if (rc != ERR)
5577 rc = init_pair(GOT_DIFF_LINE_HUNK,
5578 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5579 if (rc != ERR)
5580 rc = init_pair(GOT_DIFF_LINE_META,
5581 get_color_value("TOG_COLOR_DIFF_META"), -1);
5582 if (rc != ERR)
5583 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5584 get_color_value("TOG_COLOR_DIFF_META"), -1);
5585 if (rc != ERR)
5586 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5587 get_color_value("TOG_COLOR_DIFF_META"), -1);
5588 if (rc != ERR)
5589 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5590 get_color_value("TOG_COLOR_DIFF_META"), -1);
5591 if (rc != ERR)
5592 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5593 get_color_value("TOG_COLOR_AUTHOR"), -1);
5594 if (rc != ERR)
5595 rc = init_pair(GOT_DIFF_LINE_DATE,
5596 get_color_value("TOG_COLOR_DATE"), -1);
5597 if (rc == ERR) {
5598 err = got_error(GOT_ERR_RANGE);
5599 goto done;
5603 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5604 view_is_splitscreen(view))
5605 show_log_view(parent_view); /* draw border */
5606 diff_view_indicate_progress(view);
5608 err = create_diff(s);
5610 view->show = show_diff_view;
5611 view->input = input_diff_view;
5612 view->reset = reset_diff_view;
5613 view->close = close_diff_view;
5614 view->search_start = search_start_diff_view;
5615 view->search_setup = search_setup_diff_view;
5616 view->search_next = search_next_view_match;
5617 done:
5618 if (err) {
5619 if (view->close == NULL)
5620 close_diff_view(view);
5621 view_close(view);
5623 return err;
5626 static const struct got_error *
5627 show_diff_view(struct tog_view *view)
5629 const struct got_error *err;
5630 struct tog_diff_view_state *s = &view->state.diff;
5631 char *id_str1 = NULL, *id_str2, *header;
5632 const char *label1, *label2;
5634 if (s->id1) {
5635 err = got_object_id_str(&id_str1, s->id1);
5636 if (err)
5637 return err;
5638 label1 = s->label1 ? s->label1 : id_str1;
5639 } else
5640 label1 = "/dev/null";
5642 err = got_object_id_str(&id_str2, s->id2);
5643 if (err)
5644 return err;
5645 label2 = s->label2 ? s->label2 : id_str2;
5647 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5648 err = got_error_from_errno("asprintf");
5649 free(id_str1);
5650 free(id_str2);
5651 return err;
5653 free(id_str1);
5654 free(id_str2);
5656 err = draw_file(view, header);
5657 free(header);
5658 return err;
5661 static const struct got_error *
5662 set_selected_commit(struct tog_diff_view_state *s,
5663 struct commit_queue_entry *entry)
5665 const struct got_error *err;
5666 const struct got_object_id_queue *parent_ids;
5667 struct got_commit_object *selected_commit;
5668 struct got_object_qid *pid;
5670 free(s->id2);
5671 s->id2 = got_object_id_dup(entry->id);
5672 if (s->id2 == NULL)
5673 return got_error_from_errno("got_object_id_dup");
5675 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5676 if (err)
5677 return err;
5678 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5679 free(s->id1);
5680 pid = STAILQ_FIRST(parent_ids);
5681 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5682 got_object_commit_close(selected_commit);
5683 return NULL;
5686 static const struct got_error *
5687 reset_diff_view(struct tog_view *view)
5689 struct tog_diff_view_state *s = &view->state.diff;
5691 view->count = 0;
5692 wclear(view->window);
5693 s->first_displayed_line = 1;
5694 s->last_displayed_line = view->nlines;
5695 s->matched_line = 0;
5696 diff_view_indicate_progress(view);
5697 return create_diff(s);
5700 static void
5701 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5703 int start, i;
5705 i = start = s->first_displayed_line - 1;
5707 while (s->lines[i].type != type) {
5708 if (i == 0)
5709 i = s->nlines - 1;
5710 if (--i == start)
5711 return; /* do nothing, requested type not in file */
5714 s->selected_line = 1;
5715 s->first_displayed_line = i;
5718 static void
5719 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5721 int start, i;
5723 i = start = s->first_displayed_line + 1;
5725 while (s->lines[i].type != type) {
5726 if (i == s->nlines - 1)
5727 i = 0;
5728 if (++i == start)
5729 return; /* do nothing, requested type not in file */
5732 s->selected_line = 1;
5733 s->first_displayed_line = i;
5736 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5737 int, int, int);
5738 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5739 int, int);
5741 static const struct got_error *
5742 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5744 const struct got_error *err = NULL;
5745 struct tog_diff_view_state *s = &view->state.diff;
5746 struct tog_log_view_state *ls;
5747 struct commit_queue_entry *old_selected_entry;
5748 char *line = NULL;
5749 size_t linesize = 0;
5750 ssize_t linelen;
5751 int i, nscroll = view->nlines - 1, up = 0;
5753 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5755 switch (ch) {
5756 case '0':
5757 case '$':
5758 case KEY_RIGHT:
5759 case 'l':
5760 case KEY_LEFT:
5761 case 'h':
5762 horizontal_scroll_input(view, ch);
5763 break;
5764 case 'a':
5765 case 'w':
5766 if (ch == 'a') {
5767 s->force_text_diff = !s->force_text_diff;
5768 view->action = s->force_text_diff ?
5769 "force ASCII text enabled" :
5770 "force ASCII text disabled";
5772 else if (ch == 'w') {
5773 s->ignore_whitespace = !s->ignore_whitespace;
5774 view->action = s->ignore_whitespace ?
5775 "ignore whitespace enabled" :
5776 "ignore whitespace disabled";
5778 err = reset_diff_view(view);
5779 break;
5780 case 'g':
5781 case KEY_HOME:
5782 s->first_displayed_line = 1;
5783 view->count = 0;
5784 break;
5785 case 'G':
5786 case KEY_END:
5787 view->count = 0;
5788 if (s->eof)
5789 break;
5791 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5792 s->eof = 1;
5793 break;
5794 case 'k':
5795 case KEY_UP:
5796 case CTRL('p'):
5797 if (s->first_displayed_line > 1)
5798 s->first_displayed_line--;
5799 else
5800 view->count = 0;
5801 break;
5802 case CTRL('u'):
5803 case 'u':
5804 nscroll /= 2;
5805 /* FALL THROUGH */
5806 case KEY_PPAGE:
5807 case CTRL('b'):
5808 case 'b':
5809 if (s->first_displayed_line == 1) {
5810 view->count = 0;
5811 break;
5813 i = 0;
5814 while (i++ < nscroll && s->first_displayed_line > 1)
5815 s->first_displayed_line--;
5816 break;
5817 case 'j':
5818 case KEY_DOWN:
5819 case CTRL('n'):
5820 if (!s->eof)
5821 s->first_displayed_line++;
5822 else
5823 view->count = 0;
5824 break;
5825 case CTRL('d'):
5826 case 'd':
5827 nscroll /= 2;
5828 /* FALL THROUGH */
5829 case KEY_NPAGE:
5830 case CTRL('f'):
5831 case 'f':
5832 case ' ':
5833 if (s->eof) {
5834 view->count = 0;
5835 break;
5837 i = 0;
5838 while (!s->eof && i++ < nscroll) {
5839 linelen = getline(&line, &linesize, s->f);
5840 s->first_displayed_line++;
5841 if (linelen == -1) {
5842 if (feof(s->f)) {
5843 s->eof = 1;
5844 } else
5845 err = got_ferror(s->f, GOT_ERR_IO);
5846 break;
5849 free(line);
5850 break;
5851 case '(':
5852 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5853 break;
5854 case ')':
5855 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5856 break;
5857 case '{':
5858 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5859 break;
5860 case '}':
5861 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5862 break;
5863 case '[':
5864 if (s->diff_context > 0) {
5865 s->diff_context--;
5866 s->matched_line = 0;
5867 diff_view_indicate_progress(view);
5868 err = create_diff(s);
5869 if (s->first_displayed_line + view->nlines - 1 >
5870 s->nlines) {
5871 s->first_displayed_line = 1;
5872 s->last_displayed_line = view->nlines;
5874 } else
5875 view->count = 0;
5876 break;
5877 case ']':
5878 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5879 s->diff_context++;
5880 s->matched_line = 0;
5881 diff_view_indicate_progress(view);
5882 err = create_diff(s);
5883 } else
5884 view->count = 0;
5885 break;
5886 case '<':
5887 case ',':
5888 case 'K':
5889 up = 1;
5890 /* FALL THROUGH */
5891 case '>':
5892 case '.':
5893 case 'J':
5894 if (s->parent_view == NULL) {
5895 view->count = 0;
5896 break;
5898 s->parent_view->count = view->count;
5900 if (s->parent_view->type == TOG_VIEW_LOG) {
5901 ls = &s->parent_view->state.log;
5902 old_selected_entry = ls->selected_entry;
5904 err = input_log_view(NULL, s->parent_view,
5905 up ? KEY_UP : KEY_DOWN);
5906 if (err)
5907 break;
5908 view->count = s->parent_view->count;
5910 if (old_selected_entry == ls->selected_entry)
5911 break;
5913 err = set_selected_commit(s, ls->selected_entry);
5914 if (err)
5915 break;
5916 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5917 struct tog_blame_view_state *bs;
5918 struct got_object_id *id, *prev_id;
5920 bs = &s->parent_view->state.blame;
5921 prev_id = get_annotation_for_line(bs->blame.lines,
5922 bs->blame.nlines, bs->last_diffed_line);
5924 err = input_blame_view(&view, s->parent_view,
5925 up ? KEY_UP : KEY_DOWN);
5926 if (err)
5927 break;
5928 view->count = s->parent_view->count;
5930 if (prev_id == NULL)
5931 break;
5932 id = get_selected_commit_id(bs->blame.lines,
5933 bs->blame.nlines, bs->first_displayed_line,
5934 bs->selected_line);
5935 if (id == NULL)
5936 break;
5938 if (!got_object_id_cmp(prev_id, id))
5939 break;
5941 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5942 if (err)
5943 break;
5945 s->first_displayed_line = 1;
5946 s->last_displayed_line = view->nlines;
5947 s->matched_line = 0;
5948 view->x = 0;
5950 diff_view_indicate_progress(view);
5951 err = create_diff(s);
5952 break;
5953 default:
5954 view->count = 0;
5955 break;
5958 return err;
5961 static const struct got_error *
5962 cmd_diff(int argc, char *argv[])
5964 const struct got_error *error;
5965 struct got_repository *repo = NULL;
5966 struct got_worktree *worktree = NULL;
5967 struct got_object_id *id1 = NULL, *id2 = NULL;
5968 char *repo_path = NULL, *cwd = NULL;
5969 char *id_str1 = NULL, *id_str2 = NULL;
5970 char *keyword_idstr1 = NULL, *keyword_idstr2 = NULL;
5971 char *label1 = NULL, *label2 = NULL;
5972 int diff_context = 3, ignore_whitespace = 0;
5973 int ch, force_text_diff = 0;
5974 const char *errstr;
5975 struct tog_view *view;
5976 int *pack_fds = NULL;
5978 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5979 switch (ch) {
5980 case 'a':
5981 force_text_diff = 1;
5982 break;
5983 case 'C':
5984 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5985 &errstr);
5986 if (errstr != NULL)
5987 errx(1, "number of context lines is %s: %s",
5988 errstr, errstr);
5989 break;
5990 case 'r':
5991 repo_path = realpath(optarg, NULL);
5992 if (repo_path == NULL)
5993 return got_error_from_errno2("realpath",
5994 optarg);
5995 got_path_strip_trailing_slashes(repo_path);
5996 break;
5997 case 'w':
5998 ignore_whitespace = 1;
5999 break;
6000 default:
6001 usage_diff();
6002 /* NOTREACHED */
6006 argc -= optind;
6007 argv += optind;
6009 if (argc == 0) {
6010 usage_diff(); /* TODO show local worktree changes */
6011 } else if (argc == 2) {
6012 id_str1 = argv[0];
6013 id_str2 = argv[1];
6014 } else
6015 usage_diff();
6017 error = got_repo_pack_fds_open(&pack_fds);
6018 if (error)
6019 goto done;
6021 if (repo_path == NULL) {
6022 cwd = getcwd(NULL, 0);
6023 if (cwd == NULL)
6024 return got_error_from_errno("getcwd");
6025 error = got_worktree_open(&worktree, cwd, NULL);
6026 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6027 goto done;
6028 if (worktree)
6029 repo_path =
6030 strdup(got_worktree_get_repo_path(worktree));
6031 else
6032 repo_path = strdup(cwd);
6033 if (repo_path == NULL) {
6034 error = got_error_from_errno("strdup");
6035 goto done;
6039 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6040 if (error)
6041 goto done;
6043 init_curses();
6045 error = apply_unveil(got_repo_get_path(repo), NULL);
6046 if (error)
6047 goto done;
6049 error = tog_load_refs(repo, 0);
6050 if (error)
6051 goto done;
6053 if (id_str1 != NULL) {
6054 error = got_keyword_to_idstr(&keyword_idstr1, id_str1,
6055 repo, worktree);
6056 if (error != NULL)
6057 goto done;
6058 if (keyword_idstr1 != NULL)
6059 id_str1 = keyword_idstr1;
6061 if (id_str2 != NULL) {
6062 error = got_keyword_to_idstr(&keyword_idstr2, id_str2,
6063 repo, worktree);
6064 if (error != NULL)
6065 goto done;
6066 if (keyword_idstr2 != NULL)
6067 id_str2 = keyword_idstr2;
6070 error = got_repo_match_object_id(&id1, &label1, id_str1,
6071 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6072 if (error)
6073 goto done;
6075 error = got_repo_match_object_id(&id2, &label2, id_str2,
6076 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6077 if (error)
6078 goto done;
6080 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
6081 if (view == NULL) {
6082 error = got_error_from_errno("view_open");
6083 goto done;
6085 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
6086 ignore_whitespace, force_text_diff, NULL, repo);
6087 if (error)
6088 goto done;
6090 if (worktree) {
6091 error = set_tog_base_commit(repo, worktree);
6092 if (error != NULL)
6093 goto done;
6096 error = view_loop(view);
6098 done:
6099 free(tog_base_commit.id);
6100 free(keyword_idstr1);
6101 free(keyword_idstr2);
6102 free(label1);
6103 free(label2);
6104 free(repo_path);
6105 free(cwd);
6106 if (repo) {
6107 const struct got_error *close_err = got_repo_close(repo);
6108 if (error == NULL)
6109 error = close_err;
6111 if (worktree)
6112 got_worktree_close(worktree);
6113 if (pack_fds) {
6114 const struct got_error *pack_err =
6115 got_repo_pack_fds_close(pack_fds);
6116 if (error == NULL)
6117 error = pack_err;
6119 tog_free_refs();
6120 return error;
6123 __dead static void
6124 usage_blame(void)
6126 endwin();
6127 fprintf(stderr,
6128 "usage: %s blame [-c commit] [-r repository-path] path\n",
6129 getprogname());
6130 exit(1);
6133 struct tog_blame_line {
6134 int annotated;
6135 struct got_object_id *id;
6138 static const struct got_error *
6139 draw_blame(struct tog_view *view)
6141 struct tog_blame_view_state *s = &view->state.blame;
6142 struct tog_blame *blame = &s->blame;
6143 regmatch_t *regmatch = &view->regmatch;
6144 const struct got_error *err;
6145 int lineno = 0, nprinted = 0;
6146 char *line = NULL;
6147 size_t linesize = 0;
6148 ssize_t linelen;
6149 wchar_t *wline;
6150 int width;
6151 struct tog_blame_line *blame_line;
6152 struct got_object_id *prev_id = NULL;
6153 char *id_str;
6154 struct tog_color *tc;
6156 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6157 if (err)
6158 return err;
6160 rewind(blame->f);
6161 werase(view->window);
6163 if (asprintf(&line, "commit %s", id_str) == -1) {
6164 err = got_error_from_errno("asprintf");
6165 free(id_str);
6166 return err;
6169 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6170 free(line);
6171 line = NULL;
6172 if (err)
6173 return err;
6174 if (view_needs_focus_indication(view))
6175 wstandout(view->window);
6176 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6177 if (tc)
6178 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6179 waddwstr(view->window, wline);
6180 while (width++ < view->ncols)
6181 waddch(view->window, ' ');
6182 if (tc)
6183 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6184 if (view_needs_focus_indication(view))
6185 wstandend(view->window);
6186 free(wline);
6187 wline = NULL;
6189 if (view->gline > blame->nlines)
6190 view->gline = blame->nlines;
6192 if (tog_io.wait_for_ui) {
6193 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6194 int rc;
6196 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6197 if (rc)
6198 return got_error_set_errno(rc, "pthread_cond_wait");
6199 tog_io.wait_for_ui = 0;
6202 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6203 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6204 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6205 free(id_str);
6206 return got_error_from_errno("asprintf");
6208 free(id_str);
6209 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6210 free(line);
6211 line = NULL;
6212 if (err)
6213 return err;
6214 waddwstr(view->window, wline);
6215 free(wline);
6216 wline = NULL;
6217 if (width < view->ncols - 1)
6218 waddch(view->window, '\n');
6220 s->eof = 0;
6221 view->maxx = 0;
6222 while (nprinted < view->nlines - 2) {
6223 linelen = getline(&line, &linesize, blame->f);
6224 if (linelen == -1) {
6225 if (feof(blame->f)) {
6226 s->eof = 1;
6227 break;
6229 free(line);
6230 return got_ferror(blame->f, GOT_ERR_IO);
6232 if (++lineno < s->first_displayed_line)
6233 continue;
6234 if (view->gline && !gotoline(view, &lineno, &nprinted))
6235 continue;
6237 /* Set view->maxx based on full line length. */
6238 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6239 if (err) {
6240 free(line);
6241 return err;
6243 free(wline);
6244 wline = NULL;
6245 view->maxx = MAX(view->maxx, width);
6247 if (nprinted == s->selected_line - 1)
6248 wstandout(view->window);
6250 if (blame->nlines > 0) {
6251 blame_line = &blame->lines[lineno - 1];
6252 if (blame_line->annotated && prev_id &&
6253 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6254 !(nprinted == s->selected_line - 1)) {
6255 waddstr(view->window, " ");
6256 } else if (blame_line->annotated) {
6257 char *id_str;
6258 err = got_object_id_str(&id_str,
6259 blame_line->id);
6260 if (err) {
6261 free(line);
6262 return err;
6264 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6265 if (tc)
6266 wattr_on(view->window,
6267 COLOR_PAIR(tc->colorpair), NULL);
6268 wprintw(view->window, "%.8s", id_str);
6269 if (tc)
6270 wattr_off(view->window,
6271 COLOR_PAIR(tc->colorpair), NULL);
6272 free(id_str);
6273 prev_id = blame_line->id;
6274 } else {
6275 waddstr(view->window, "........");
6276 prev_id = NULL;
6278 } else {
6279 waddstr(view->window, "........");
6280 prev_id = NULL;
6283 if (nprinted == s->selected_line - 1)
6284 wstandend(view->window);
6285 waddstr(view->window, " ");
6287 if (view->ncols <= 9) {
6288 width = 9;
6289 } else if (s->first_displayed_line + nprinted ==
6290 s->matched_line &&
6291 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6292 err = add_matched_line(&width, line, view->ncols - 9, 9,
6293 view->window, view->x, regmatch);
6294 if (err) {
6295 free(line);
6296 return err;
6298 width += 9;
6299 } else {
6300 int skip;
6301 err = format_line(&wline, &width, &skip, line,
6302 view->x, view->ncols - 9, 9, 1);
6303 if (err) {
6304 free(line);
6305 return err;
6307 waddwstr(view->window, &wline[skip]);
6308 width += 9;
6309 free(wline);
6310 wline = NULL;
6313 if (width <= view->ncols - 1)
6314 waddch(view->window, '\n');
6315 if (++nprinted == 1)
6316 s->first_displayed_line = lineno;
6318 free(line);
6319 s->last_displayed_line = lineno;
6321 view_border(view);
6323 return NULL;
6326 static const struct got_error *
6327 blame_cb(void *arg, int nlines, int lineno,
6328 struct got_commit_object *commit, struct got_object_id *id)
6330 const struct got_error *err = NULL;
6331 struct tog_blame_cb_args *a = arg;
6332 struct tog_blame_line *line;
6333 int errcode;
6335 if (nlines != a->nlines ||
6336 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6337 return got_error(GOT_ERR_RANGE);
6339 errcode = pthread_mutex_lock(&tog_mutex);
6340 if (errcode)
6341 return got_error_set_errno(errcode, "pthread_mutex_lock");
6343 if (*a->quit) { /* user has quit the blame view */
6344 err = got_error(GOT_ERR_ITER_COMPLETED);
6345 goto done;
6348 if (lineno == -1)
6349 goto done; /* no change in this commit */
6351 line = &a->lines[lineno - 1];
6352 if (line->annotated)
6353 goto done;
6355 line->id = got_object_id_dup(id);
6356 if (line->id == NULL) {
6357 err = got_error_from_errno("got_object_id_dup");
6358 goto done;
6360 line->annotated = 1;
6361 done:
6362 errcode = pthread_mutex_unlock(&tog_mutex);
6363 if (errcode)
6364 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6365 return err;
6368 static void *
6369 blame_thread(void *arg)
6371 const struct got_error *err, *close_err;
6372 struct tog_blame_thread_args *ta = arg;
6373 struct tog_blame_cb_args *a = ta->cb_args;
6374 int errcode, fd1 = -1, fd2 = -1;
6375 FILE *f1 = NULL, *f2 = NULL;
6377 fd1 = got_opentempfd();
6378 if (fd1 == -1)
6379 return (void *)got_error_from_errno("got_opentempfd");
6381 fd2 = got_opentempfd();
6382 if (fd2 == -1) {
6383 err = got_error_from_errno("got_opentempfd");
6384 goto done;
6387 f1 = got_opentemp();
6388 if (f1 == NULL) {
6389 err = (void *)got_error_from_errno("got_opentemp");
6390 goto done;
6392 f2 = got_opentemp();
6393 if (f2 == NULL) {
6394 err = (void *)got_error_from_errno("got_opentemp");
6395 goto done;
6398 err = block_signals_used_by_main_thread();
6399 if (err)
6400 goto done;
6402 err = got_blame(ta->path, a->commit_id, ta->repo,
6403 tog_diff_algo, blame_cb, ta->cb_args,
6404 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6405 if (err && err->code == GOT_ERR_CANCELLED)
6406 err = NULL;
6408 errcode = pthread_mutex_lock(&tog_mutex);
6409 if (errcode) {
6410 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6411 goto done;
6414 close_err = got_repo_close(ta->repo);
6415 if (err == NULL)
6416 err = close_err;
6417 ta->repo = NULL;
6418 *ta->complete = 1;
6420 if (tog_io.wait_for_ui) {
6421 errcode = pthread_cond_signal(&ta->blame_complete);
6422 if (errcode && err == NULL)
6423 err = got_error_set_errno(errcode,
6424 "pthread_cond_signal");
6427 errcode = pthread_mutex_unlock(&tog_mutex);
6428 if (errcode && err == NULL)
6429 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6431 done:
6432 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6433 err = got_error_from_errno("close");
6434 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6435 err = got_error_from_errno("close");
6436 if (f1 && fclose(f1) == EOF && err == NULL)
6437 err = got_error_from_errno("fclose");
6438 if (f2 && fclose(f2) == EOF && err == NULL)
6439 err = got_error_from_errno("fclose");
6441 return (void *)err;
6444 static struct got_object_id *
6445 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6446 int first_displayed_line, int selected_line)
6448 struct tog_blame_line *line;
6450 if (nlines <= 0)
6451 return NULL;
6453 line = &lines[first_displayed_line - 1 + selected_line - 1];
6454 if (!line->annotated)
6455 return NULL;
6457 return line->id;
6460 static struct got_object_id *
6461 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6462 int lineno)
6464 struct tog_blame_line *line;
6466 if (nlines <= 0 || lineno >= nlines)
6467 return NULL;
6469 line = &lines[lineno - 1];
6470 if (!line->annotated)
6471 return NULL;
6473 return line->id;
6476 static const struct got_error *
6477 stop_blame(struct tog_blame *blame)
6479 const struct got_error *err = NULL;
6480 int i;
6482 if (blame->thread) {
6483 int errcode;
6484 errcode = pthread_mutex_unlock(&tog_mutex);
6485 if (errcode)
6486 return got_error_set_errno(errcode,
6487 "pthread_mutex_unlock");
6488 errcode = pthread_join(blame->thread, (void **)&err);
6489 if (errcode)
6490 return got_error_set_errno(errcode, "pthread_join");
6491 errcode = pthread_mutex_lock(&tog_mutex);
6492 if (errcode)
6493 return got_error_set_errno(errcode,
6494 "pthread_mutex_lock");
6495 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6496 err = NULL;
6497 blame->thread = 0; //NULL;
6499 if (blame->thread_args.repo) {
6500 const struct got_error *close_err;
6501 close_err = got_repo_close(blame->thread_args.repo);
6502 if (err == NULL)
6503 err = close_err;
6504 blame->thread_args.repo = NULL;
6506 if (blame->f) {
6507 if (fclose(blame->f) == EOF && err == NULL)
6508 err = got_error_from_errno("fclose");
6509 blame->f = NULL;
6511 if (blame->lines) {
6512 for (i = 0; i < blame->nlines; i++)
6513 free(blame->lines[i].id);
6514 free(blame->lines);
6515 blame->lines = NULL;
6517 free(blame->cb_args.commit_id);
6518 blame->cb_args.commit_id = NULL;
6519 if (blame->pack_fds) {
6520 const struct got_error *pack_err =
6521 got_repo_pack_fds_close(blame->pack_fds);
6522 if (err == NULL)
6523 err = pack_err;
6524 blame->pack_fds = NULL;
6526 return err;
6529 static const struct got_error *
6530 cancel_blame_view(void *arg)
6532 const struct got_error *err = NULL;
6533 int *done = arg;
6534 int errcode;
6536 errcode = pthread_mutex_lock(&tog_mutex);
6537 if (errcode)
6538 return got_error_set_errno(errcode,
6539 "pthread_mutex_unlock");
6541 if (*done)
6542 err = got_error(GOT_ERR_CANCELLED);
6544 errcode = pthread_mutex_unlock(&tog_mutex);
6545 if (errcode)
6546 return got_error_set_errno(errcode,
6547 "pthread_mutex_lock");
6549 return err;
6552 static const struct got_error *
6553 run_blame(struct tog_view *view)
6555 struct tog_blame_view_state *s = &view->state.blame;
6556 struct tog_blame *blame = &s->blame;
6557 const struct got_error *err = NULL;
6558 struct got_commit_object *commit = NULL;
6559 struct got_blob_object *blob = NULL;
6560 struct got_repository *thread_repo = NULL;
6561 struct got_object_id *obj_id = NULL;
6562 int obj_type, fd = -1;
6563 int *pack_fds = NULL;
6565 err = got_object_open_as_commit(&commit, s->repo,
6566 &s->blamed_commit->id);
6567 if (err)
6568 return err;
6570 fd = got_opentempfd();
6571 if (fd == -1) {
6572 err = got_error_from_errno("got_opentempfd");
6573 goto done;
6576 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6577 if (err)
6578 goto done;
6580 err = got_object_get_type(&obj_type, s->repo, obj_id);
6581 if (err)
6582 goto done;
6584 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6585 err = got_error(GOT_ERR_OBJ_TYPE);
6586 goto done;
6589 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6590 if (err)
6591 goto done;
6592 blame->f = got_opentemp();
6593 if (blame->f == NULL) {
6594 err = got_error_from_errno("got_opentemp");
6595 goto done;
6597 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6598 &blame->line_offsets, blame->f, blob);
6599 if (err)
6600 goto done;
6601 if (blame->nlines == 0) {
6602 s->blame_complete = 1;
6603 goto done;
6606 /* Don't include \n at EOF in the blame line count. */
6607 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6608 blame->nlines--;
6610 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6611 if (blame->lines == NULL) {
6612 err = got_error_from_errno("calloc");
6613 goto done;
6616 err = got_repo_pack_fds_open(&pack_fds);
6617 if (err)
6618 goto done;
6619 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6620 pack_fds);
6621 if (err)
6622 goto done;
6624 blame->pack_fds = pack_fds;
6625 blame->cb_args.view = view;
6626 blame->cb_args.lines = blame->lines;
6627 blame->cb_args.nlines = blame->nlines;
6628 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6629 if (blame->cb_args.commit_id == NULL) {
6630 err = got_error_from_errno("got_object_id_dup");
6631 goto done;
6633 blame->cb_args.quit = &s->done;
6635 blame->thread_args.path = s->path;
6636 blame->thread_args.repo = thread_repo;
6637 blame->thread_args.cb_args = &blame->cb_args;
6638 blame->thread_args.complete = &s->blame_complete;
6639 blame->thread_args.cancel_cb = cancel_blame_view;
6640 blame->thread_args.cancel_arg = &s->done;
6641 s->blame_complete = 0;
6643 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6644 s->first_displayed_line = 1;
6645 s->last_displayed_line = view->nlines;
6646 s->selected_line = 1;
6648 s->matched_line = 0;
6650 done:
6651 if (commit)
6652 got_object_commit_close(commit);
6653 if (fd != -1 && close(fd) == -1 && err == NULL)
6654 err = got_error_from_errno("close");
6655 if (blob)
6656 got_object_blob_close(blob);
6657 free(obj_id);
6658 if (err)
6659 stop_blame(blame);
6660 return err;
6663 static const struct got_error *
6664 open_blame_view(struct tog_view *view, char *path,
6665 struct got_object_id *commit_id, struct got_repository *repo)
6667 const struct got_error *err = NULL;
6668 struct tog_blame_view_state *s = &view->state.blame;
6670 STAILQ_INIT(&s->blamed_commits);
6672 s->path = strdup(path);
6673 if (s->path == NULL)
6674 return got_error_from_errno("strdup");
6676 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6677 if (err) {
6678 free(s->path);
6679 return err;
6682 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6683 s->first_displayed_line = 1;
6684 s->last_displayed_line = view->nlines;
6685 s->selected_line = 1;
6686 s->blame_complete = 0;
6687 s->repo = repo;
6688 s->commit_id = commit_id;
6689 memset(&s->blame, 0, sizeof(s->blame));
6691 STAILQ_INIT(&s->colors);
6692 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6693 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6694 get_color_value("TOG_COLOR_COMMIT"));
6695 if (err)
6696 return err;
6699 view->show = show_blame_view;
6700 view->input = input_blame_view;
6701 view->reset = reset_blame_view;
6702 view->close = close_blame_view;
6703 view->search_start = search_start_blame_view;
6704 view->search_setup = search_setup_blame_view;
6705 view->search_next = search_next_view_match;
6707 if (using_mock_io) {
6708 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6709 int rc;
6711 rc = pthread_cond_init(&bta->blame_complete, NULL);
6712 if (rc)
6713 return got_error_set_errno(rc, "pthread_cond_init");
6716 return run_blame(view);
6719 static const struct got_error *
6720 close_blame_view(struct tog_view *view)
6722 const struct got_error *err = NULL;
6723 struct tog_blame_view_state *s = &view->state.blame;
6725 if (s->blame.thread)
6726 err = stop_blame(&s->blame);
6728 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6729 struct got_object_qid *blamed_commit;
6730 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6731 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6732 got_object_qid_free(blamed_commit);
6735 if (using_mock_io) {
6736 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6737 int rc;
6739 rc = pthread_cond_destroy(&bta->blame_complete);
6740 if (rc && err == NULL)
6741 err = got_error_set_errno(rc, "pthread_cond_destroy");
6744 free(s->path);
6745 free_colors(&s->colors);
6746 return err;
6749 static const struct got_error *
6750 search_start_blame_view(struct tog_view *view)
6752 struct tog_blame_view_state *s = &view->state.blame;
6754 s->matched_line = 0;
6755 return NULL;
6758 static void
6759 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6760 size_t *nlines, int **first, int **last, int **match, int **selected)
6762 struct tog_blame_view_state *s = &view->state.blame;
6764 *f = s->blame.f;
6765 *nlines = s->blame.nlines;
6766 *line_offsets = s->blame.line_offsets;
6767 *match = &s->matched_line;
6768 *first = &s->first_displayed_line;
6769 *last = &s->last_displayed_line;
6770 *selected = &s->selected_line;
6773 static const struct got_error *
6774 show_blame_view(struct tog_view *view)
6776 const struct got_error *err = NULL;
6777 struct tog_blame_view_state *s = &view->state.blame;
6778 int errcode;
6780 if (s->blame.thread == 0 && !s->blame_complete) {
6781 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6782 &s->blame.thread_args);
6783 if (errcode)
6784 return got_error_set_errno(errcode, "pthread_create");
6786 if (!using_mock_io)
6787 halfdelay(1); /* fast refresh while annotating */
6790 if (s->blame_complete && !using_mock_io)
6791 halfdelay(10); /* disable fast refresh */
6793 err = draw_blame(view);
6795 view_border(view);
6796 return err;
6799 static const struct got_error *
6800 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6801 struct got_repository *repo, struct got_object_id *id)
6803 struct tog_view *log_view;
6804 const struct got_error *err = NULL;
6806 *new_view = NULL;
6808 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6809 if (log_view == NULL)
6810 return got_error_from_errno("view_open");
6812 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6813 if (err)
6814 view_close(log_view);
6815 else
6816 *new_view = log_view;
6818 return err;
6821 static const struct got_error *
6822 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6824 const struct got_error *err = NULL, *thread_err = NULL;
6825 struct tog_view *diff_view;
6826 struct tog_blame_view_state *s = &view->state.blame;
6827 int eos, nscroll, begin_y = 0, begin_x = 0;
6829 eos = nscroll = view->nlines - 2;
6830 if (view_is_hsplit_top(view))
6831 --eos; /* border */
6833 switch (ch) {
6834 case '0':
6835 case '$':
6836 case KEY_RIGHT:
6837 case 'l':
6838 case KEY_LEFT:
6839 case 'h':
6840 horizontal_scroll_input(view, ch);
6841 break;
6842 case 'q':
6843 s->done = 1;
6844 break;
6845 case 'g':
6846 case KEY_HOME:
6847 s->selected_line = 1;
6848 s->first_displayed_line = 1;
6849 view->count = 0;
6850 break;
6851 case 'G':
6852 case KEY_END:
6853 if (s->blame.nlines < eos) {
6854 s->selected_line = s->blame.nlines;
6855 s->first_displayed_line = 1;
6856 } else {
6857 s->selected_line = eos;
6858 s->first_displayed_line = s->blame.nlines - (eos - 1);
6860 view->count = 0;
6861 break;
6862 case 'k':
6863 case KEY_UP:
6864 case CTRL('p'):
6865 if (s->selected_line > 1)
6866 s->selected_line--;
6867 else if (s->selected_line == 1 &&
6868 s->first_displayed_line > 1)
6869 s->first_displayed_line--;
6870 else
6871 view->count = 0;
6872 break;
6873 case CTRL('u'):
6874 case 'u':
6875 nscroll /= 2;
6876 /* FALL THROUGH */
6877 case KEY_PPAGE:
6878 case CTRL('b'):
6879 case 'b':
6880 if (s->first_displayed_line == 1) {
6881 if (view->count > 1)
6882 nscroll += nscroll;
6883 s->selected_line = MAX(1, s->selected_line - nscroll);
6884 view->count = 0;
6885 break;
6887 if (s->first_displayed_line > nscroll)
6888 s->first_displayed_line -= nscroll;
6889 else
6890 s->first_displayed_line = 1;
6891 break;
6892 case 'j':
6893 case KEY_DOWN:
6894 case CTRL('n'):
6895 if (s->selected_line < eos && s->first_displayed_line +
6896 s->selected_line <= s->blame.nlines)
6897 s->selected_line++;
6898 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6899 s->first_displayed_line++;
6900 else
6901 view->count = 0;
6902 break;
6903 case 'c':
6904 case 'p': {
6905 struct got_object_id *id = NULL;
6907 view->count = 0;
6908 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6909 s->first_displayed_line, s->selected_line);
6910 if (id == NULL)
6911 break;
6912 if (ch == 'p') {
6913 struct got_commit_object *commit, *pcommit;
6914 struct got_object_qid *pid;
6915 struct got_object_id *blob_id = NULL;
6916 int obj_type;
6917 err = got_object_open_as_commit(&commit,
6918 s->repo, id);
6919 if (err)
6920 break;
6921 pid = STAILQ_FIRST(
6922 got_object_commit_get_parent_ids(commit));
6923 if (pid == NULL) {
6924 got_object_commit_close(commit);
6925 break;
6927 /* Check if path history ends here. */
6928 err = got_object_open_as_commit(&pcommit,
6929 s->repo, &pid->id);
6930 if (err)
6931 break;
6932 err = got_object_id_by_path(&blob_id, s->repo,
6933 pcommit, s->path);
6934 got_object_commit_close(pcommit);
6935 if (err) {
6936 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6937 err = NULL;
6938 got_object_commit_close(commit);
6939 break;
6941 err = got_object_get_type(&obj_type, s->repo,
6942 blob_id);
6943 free(blob_id);
6944 /* Can't blame non-blob type objects. */
6945 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6946 got_object_commit_close(commit);
6947 break;
6949 err = got_object_qid_alloc(&s->blamed_commit,
6950 &pid->id);
6951 got_object_commit_close(commit);
6952 } else {
6953 if (got_object_id_cmp(id,
6954 &s->blamed_commit->id) == 0)
6955 break;
6956 err = got_object_qid_alloc(&s->blamed_commit,
6957 id);
6959 if (err)
6960 break;
6961 s->done = 1;
6962 thread_err = stop_blame(&s->blame);
6963 s->done = 0;
6964 if (thread_err)
6965 break;
6966 STAILQ_INSERT_HEAD(&s->blamed_commits,
6967 s->blamed_commit, entry);
6968 err = run_blame(view);
6969 if (err)
6970 break;
6971 break;
6973 case 'C': {
6974 struct got_object_qid *first;
6976 view->count = 0;
6977 first = STAILQ_FIRST(&s->blamed_commits);
6978 if (!got_object_id_cmp(&first->id, s->commit_id))
6979 break;
6980 s->done = 1;
6981 thread_err = stop_blame(&s->blame);
6982 s->done = 0;
6983 if (thread_err)
6984 break;
6985 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6986 got_object_qid_free(s->blamed_commit);
6987 s->blamed_commit =
6988 STAILQ_FIRST(&s->blamed_commits);
6989 err = run_blame(view);
6990 if (err)
6991 break;
6992 break;
6994 case 'L':
6995 view->count = 0;
6996 s->id_to_log = get_selected_commit_id(s->blame.lines,
6997 s->blame.nlines, s->first_displayed_line, s->selected_line);
6998 if (s->id_to_log)
6999 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7000 break;
7001 case KEY_ENTER:
7002 case '\r': {
7003 struct got_object_id *id = NULL;
7004 struct got_object_qid *pid;
7005 struct got_commit_object *commit = NULL;
7007 view->count = 0;
7008 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
7009 s->first_displayed_line, s->selected_line);
7010 if (id == NULL)
7011 break;
7012 err = got_object_open_as_commit(&commit, s->repo, id);
7013 if (err)
7014 break;
7015 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7016 if (*new_view) {
7017 /* traversed from diff view, release diff resources */
7018 err = close_diff_view(*new_view);
7019 if (err)
7020 break;
7021 diff_view = *new_view;
7022 } else {
7023 if (view_is_parent_view(view))
7024 view_get_split(view, &begin_y, &begin_x);
7026 diff_view = view_open(0, 0, begin_y, begin_x,
7027 TOG_VIEW_DIFF);
7028 if (diff_view == NULL) {
7029 got_object_commit_close(commit);
7030 err = got_error_from_errno("view_open");
7031 break;
7034 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
7035 id, NULL, NULL, 3, 0, 0, view, s->repo);
7036 got_object_commit_close(commit);
7037 if (err)
7038 break;
7039 s->last_diffed_line = s->first_displayed_line - 1 +
7040 s->selected_line;
7041 if (*new_view)
7042 break; /* still open from active diff view */
7043 if (view_is_parent_view(view) &&
7044 view->mode == TOG_VIEW_SPLIT_HRZN) {
7045 err = view_init_hsplit(view, begin_y);
7046 if (err)
7047 break;
7050 view->focussed = 0;
7051 diff_view->focussed = 1;
7052 diff_view->mode = view->mode;
7053 diff_view->nlines = view->lines - begin_y;
7054 if (view_is_parent_view(view)) {
7055 view_transfer_size(diff_view, view);
7056 err = view_close_child(view);
7057 if (err)
7058 break;
7059 err = view_set_child(view, diff_view);
7060 if (err)
7061 break;
7062 view->focus_child = 1;
7063 } else
7064 *new_view = diff_view;
7065 if (err)
7066 break;
7067 break;
7069 case CTRL('d'):
7070 case 'd':
7071 nscroll /= 2;
7072 /* FALL THROUGH */
7073 case KEY_NPAGE:
7074 case CTRL('f'):
7075 case 'f':
7076 case ' ':
7077 if (s->last_displayed_line >= s->blame.nlines &&
7078 s->selected_line >= MIN(s->blame.nlines,
7079 view->nlines - 2)) {
7080 view->count = 0;
7081 break;
7083 if (s->last_displayed_line >= s->blame.nlines &&
7084 s->selected_line < view->nlines - 2) {
7085 s->selected_line +=
7086 MIN(nscroll, s->last_displayed_line -
7087 s->first_displayed_line - s->selected_line + 1);
7089 if (s->last_displayed_line + nscroll <= s->blame.nlines)
7090 s->first_displayed_line += nscroll;
7091 else
7092 s->first_displayed_line =
7093 s->blame.nlines - (view->nlines - 3);
7094 break;
7095 case KEY_RESIZE:
7096 if (s->selected_line > view->nlines - 2) {
7097 s->selected_line = MIN(s->blame.nlines,
7098 view->nlines - 2);
7100 break;
7101 default:
7102 view->count = 0;
7103 break;
7105 return thread_err ? thread_err : err;
7108 static const struct got_error *
7109 reset_blame_view(struct tog_view *view)
7111 const struct got_error *err;
7112 struct tog_blame_view_state *s = &view->state.blame;
7114 view->count = 0;
7115 s->done = 1;
7116 err = stop_blame(&s->blame);
7117 s->done = 0;
7118 if (err)
7119 return err;
7120 return run_blame(view);
7123 static const struct got_error *
7124 cmd_blame(int argc, char *argv[])
7126 const struct got_error *error;
7127 struct got_repository *repo = NULL;
7128 struct got_worktree *worktree = NULL;
7129 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7130 char *link_target = NULL;
7131 struct got_object_id *commit_id = NULL;
7132 struct got_commit_object *commit = NULL;
7133 char *keyword_idstr = NULL, *commit_id_str = NULL;
7134 int ch;
7135 struct tog_view *view = NULL;
7136 int *pack_fds = NULL;
7138 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7139 switch (ch) {
7140 case 'c':
7141 commit_id_str = optarg;
7142 break;
7143 case 'r':
7144 repo_path = realpath(optarg, NULL);
7145 if (repo_path == NULL)
7146 return got_error_from_errno2("realpath",
7147 optarg);
7148 break;
7149 default:
7150 usage_blame();
7151 /* NOTREACHED */
7155 argc -= optind;
7156 argv += optind;
7158 if (argc != 1)
7159 usage_blame();
7161 error = got_repo_pack_fds_open(&pack_fds);
7162 if (error != NULL)
7163 goto done;
7165 if (repo_path == NULL) {
7166 cwd = getcwd(NULL, 0);
7167 if (cwd == NULL)
7168 return got_error_from_errno("getcwd");
7169 error = got_worktree_open(&worktree, cwd, NULL);
7170 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7171 goto done;
7172 if (worktree)
7173 repo_path =
7174 strdup(got_worktree_get_repo_path(worktree));
7175 else
7176 repo_path = strdup(cwd);
7177 if (repo_path == NULL) {
7178 error = got_error_from_errno("strdup");
7179 goto done;
7183 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7184 if (error != NULL)
7185 goto done;
7187 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7188 worktree);
7189 if (error)
7190 goto done;
7192 init_curses();
7194 error = apply_unveil(got_repo_get_path(repo), NULL);
7195 if (error)
7196 goto done;
7198 error = tog_load_refs(repo, 0);
7199 if (error)
7200 goto done;
7202 if (commit_id_str == NULL) {
7203 struct got_reference *head_ref;
7204 error = got_ref_open(&head_ref, repo, worktree ?
7205 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7206 if (error != NULL)
7207 goto done;
7208 error = got_ref_resolve(&commit_id, repo, head_ref);
7209 got_ref_close(head_ref);
7210 } else {
7211 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
7212 repo, worktree);
7213 if (error != NULL)
7214 goto done;
7215 if (keyword_idstr != NULL)
7216 commit_id_str = keyword_idstr;
7218 error = got_repo_match_object_id(&commit_id, NULL,
7219 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7221 if (error != NULL)
7222 goto done;
7224 error = got_object_open_as_commit(&commit, repo, commit_id);
7225 if (error)
7226 goto done;
7228 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7229 commit, repo);
7230 if (error)
7231 goto done;
7233 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7234 if (view == NULL) {
7235 error = got_error_from_errno("view_open");
7236 goto done;
7238 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7239 commit_id, repo);
7240 if (error != NULL) {
7241 if (view->close == NULL)
7242 close_blame_view(view);
7243 view_close(view);
7244 goto done;
7247 if (worktree) {
7248 error = set_tog_base_commit(repo, worktree);
7249 if (error != NULL)
7250 goto done;
7252 /* Release work tree lock. */
7253 got_worktree_close(worktree);
7254 worktree = NULL;
7257 error = view_loop(view);
7259 done:
7260 free(tog_base_commit.id);
7261 free(repo_path);
7262 free(in_repo_path);
7263 free(link_target);
7264 free(cwd);
7265 free(commit_id);
7266 free(keyword_idstr);
7267 if (commit)
7268 got_object_commit_close(commit);
7269 if (worktree)
7270 got_worktree_close(worktree);
7271 if (repo) {
7272 const struct got_error *close_err = got_repo_close(repo);
7273 if (error == NULL)
7274 error = close_err;
7276 if (pack_fds) {
7277 const struct got_error *pack_err =
7278 got_repo_pack_fds_close(pack_fds);
7279 if (error == NULL)
7280 error = pack_err;
7282 tog_free_refs();
7283 return error;
7286 static const struct got_error *
7287 draw_tree_entries(struct tog_view *view, const char *parent_path)
7289 struct tog_tree_view_state *s = &view->state.tree;
7290 const struct got_error *err = NULL;
7291 struct got_tree_entry *te;
7292 wchar_t *wline;
7293 char *index = NULL;
7294 struct tog_color *tc;
7295 int width, n, nentries, scrollx, i = 1;
7296 int limit = view->nlines;
7298 s->ndisplayed = 0;
7299 if (view_is_hsplit_top(view))
7300 --limit; /* border */
7302 werase(view->window);
7304 if (limit == 0)
7305 return NULL;
7307 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7308 0, 0);
7309 if (err)
7310 return err;
7311 if (view_needs_focus_indication(view))
7312 wstandout(view->window);
7313 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7314 if (tc)
7315 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7316 waddwstr(view->window, wline);
7317 free(wline);
7318 wline = NULL;
7319 while (width++ < view->ncols)
7320 waddch(view->window, ' ');
7321 if (tc)
7322 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7323 if (view_needs_focus_indication(view))
7324 wstandend(view->window);
7325 if (--limit <= 0)
7326 return NULL;
7328 i += s->selected;
7329 if (s->first_displayed_entry) {
7330 i += got_tree_entry_get_index(s->first_displayed_entry);
7331 if (s->tree != s->root)
7332 ++i; /* account for ".." entry */
7334 nentries = got_object_tree_get_nentries(s->tree);
7335 if (asprintf(&index, "[%d/%d] %s",
7336 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7337 return got_error_from_errno("asprintf");
7338 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7339 free(index);
7340 if (err)
7341 return err;
7342 waddwstr(view->window, wline);
7343 free(wline);
7344 wline = NULL;
7345 if (width < view->ncols - 1)
7346 waddch(view->window, '\n');
7347 if (--limit <= 0)
7348 return NULL;
7349 waddch(view->window, '\n');
7350 if (--limit <= 0)
7351 return NULL;
7353 if (s->first_displayed_entry == NULL) {
7354 te = got_object_tree_get_first_entry(s->tree);
7355 if (s->selected == 0) {
7356 if (view->focussed)
7357 wstandout(view->window);
7358 s->selected_entry = NULL;
7360 waddstr(view->window, " ..\n"); /* parent directory */
7361 if (s->selected == 0 && view->focussed)
7362 wstandend(view->window);
7363 s->ndisplayed++;
7364 if (--limit <= 0)
7365 return NULL;
7366 n = 1;
7367 } else {
7368 n = 0;
7369 te = s->first_displayed_entry;
7372 view->maxx = 0;
7373 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7374 char *line = NULL, *id_str = NULL, *link_target = NULL;
7375 const char *modestr = "";
7376 mode_t mode;
7378 te = got_object_tree_get_entry(s->tree, i);
7379 mode = got_tree_entry_get_mode(te);
7381 if (s->show_ids) {
7382 err = got_object_id_str(&id_str,
7383 got_tree_entry_get_id(te));
7384 if (err)
7385 return got_error_from_errno(
7386 "got_object_id_str");
7388 if (got_object_tree_entry_is_submodule(te))
7389 modestr = "$";
7390 else if (S_ISLNK(mode)) {
7391 int i;
7393 err = got_tree_entry_get_symlink_target(&link_target,
7394 te, s->repo);
7395 if (err) {
7396 free(id_str);
7397 return err;
7399 for (i = 0; link_target[i] != '\0'; i++) {
7400 if (!isprint((unsigned char)link_target[i]))
7401 link_target[i] = '?';
7403 modestr = "@";
7405 else if (S_ISDIR(mode))
7406 modestr = "/";
7407 else if (mode & S_IXUSR)
7408 modestr = "*";
7409 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7410 got_tree_entry_get_name(te), modestr,
7411 link_target ? " -> ": "",
7412 link_target ? link_target : "") == -1) {
7413 free(id_str);
7414 free(link_target);
7415 return got_error_from_errno("asprintf");
7417 free(id_str);
7418 free(link_target);
7420 /* use full line width to determine view->maxx */
7421 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7422 if (err) {
7423 free(line);
7424 break;
7426 view->maxx = MAX(view->maxx, width);
7427 free(wline);
7428 wline = NULL;
7430 err = format_line(&wline, &width, &scrollx, line, view->x,
7431 view->ncols, 0, 0);
7432 if (err) {
7433 free(line);
7434 break;
7436 if (n == s->selected) {
7437 if (view->focussed)
7438 wstandout(view->window);
7439 s->selected_entry = te;
7441 tc = match_color(&s->colors, line);
7442 if (tc)
7443 wattr_on(view->window,
7444 COLOR_PAIR(tc->colorpair), NULL);
7445 waddwstr(view->window, &wline[scrollx]);
7446 if (tc)
7447 wattr_off(view->window,
7448 COLOR_PAIR(tc->colorpair), NULL);
7449 if (width < view->ncols)
7450 waddch(view->window, '\n');
7451 if (n == s->selected && view->focussed)
7452 wstandend(view->window);
7453 free(line);
7454 free(wline);
7455 wline = NULL;
7456 n++;
7457 s->ndisplayed++;
7458 s->last_displayed_entry = te;
7459 if (--limit <= 0)
7460 break;
7463 return err;
7466 static void
7467 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7469 struct got_tree_entry *te;
7470 int isroot = s->tree == s->root;
7471 int i = 0;
7473 if (s->first_displayed_entry == NULL)
7474 return;
7476 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7477 while (i++ < maxscroll) {
7478 if (te == NULL) {
7479 if (!isroot)
7480 s->first_displayed_entry = NULL;
7481 break;
7483 s->first_displayed_entry = te;
7484 te = got_tree_entry_get_prev(s->tree, te);
7488 static const struct got_error *
7489 tree_scroll_down(struct tog_view *view, int maxscroll)
7491 struct tog_tree_view_state *s = &view->state.tree;
7492 struct got_tree_entry *next, *last;
7493 int n = 0;
7495 if (s->first_displayed_entry)
7496 next = got_tree_entry_get_next(s->tree,
7497 s->first_displayed_entry);
7498 else
7499 next = got_object_tree_get_first_entry(s->tree);
7501 last = s->last_displayed_entry;
7502 while (next && n++ < maxscroll) {
7503 if (last) {
7504 s->last_displayed_entry = last;
7505 last = got_tree_entry_get_next(s->tree, last);
7507 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7508 s->first_displayed_entry = next;
7509 next = got_tree_entry_get_next(s->tree, next);
7513 return NULL;
7516 static const struct got_error *
7517 tree_entry_path(char **path, struct tog_parent_trees *parents,
7518 struct got_tree_entry *te)
7520 const struct got_error *err = NULL;
7521 struct tog_parent_tree *pt;
7522 size_t len = 2; /* for leading slash and NUL */
7524 TAILQ_FOREACH(pt, parents, entry)
7525 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7526 + 1 /* slash */;
7527 if (te)
7528 len += strlen(got_tree_entry_get_name(te));
7530 *path = calloc(1, len);
7531 if (path == NULL)
7532 return got_error_from_errno("calloc");
7534 (*path)[0] = '/';
7535 pt = TAILQ_LAST(parents, tog_parent_trees);
7536 while (pt) {
7537 const char *name = got_tree_entry_get_name(pt->selected_entry);
7538 if (strlcat(*path, name, len) >= len) {
7539 err = got_error(GOT_ERR_NO_SPACE);
7540 goto done;
7542 if (strlcat(*path, "/", len) >= len) {
7543 err = got_error(GOT_ERR_NO_SPACE);
7544 goto done;
7546 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7548 if (te) {
7549 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7550 err = got_error(GOT_ERR_NO_SPACE);
7551 goto done;
7554 done:
7555 if (err) {
7556 free(*path);
7557 *path = NULL;
7559 return err;
7562 static const struct got_error *
7563 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7564 struct got_tree_entry *te, struct tog_parent_trees *parents,
7565 struct got_object_id *commit_id, struct got_repository *repo)
7567 const struct got_error *err = NULL;
7568 char *path;
7569 struct tog_view *blame_view;
7571 *new_view = NULL;
7573 err = tree_entry_path(&path, parents, te);
7574 if (err)
7575 return err;
7577 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7578 if (blame_view == NULL) {
7579 err = got_error_from_errno("view_open");
7580 goto done;
7583 err = open_blame_view(blame_view, path, commit_id, repo);
7584 if (err) {
7585 if (err->code == GOT_ERR_CANCELLED)
7586 err = NULL;
7587 view_close(blame_view);
7588 } else
7589 *new_view = blame_view;
7590 done:
7591 free(path);
7592 return err;
7595 static const struct got_error *
7596 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7597 struct tog_tree_view_state *s)
7599 struct tog_view *log_view;
7600 const struct got_error *err = NULL;
7601 char *path;
7603 *new_view = NULL;
7605 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7606 if (log_view == NULL)
7607 return got_error_from_errno("view_open");
7609 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7610 if (err)
7611 return err;
7613 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7614 path, 0);
7615 if (err)
7616 view_close(log_view);
7617 else
7618 *new_view = log_view;
7619 free(path);
7620 return err;
7623 static const struct got_error *
7624 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7625 const char *head_ref_name, struct got_repository *repo)
7627 const struct got_error *err = NULL;
7628 char *commit_id_str = NULL;
7629 struct tog_tree_view_state *s = &view->state.tree;
7630 struct got_commit_object *commit = NULL;
7632 TAILQ_INIT(&s->parents);
7633 STAILQ_INIT(&s->colors);
7635 s->commit_id = got_object_id_dup(commit_id);
7636 if (s->commit_id == NULL) {
7637 err = got_error_from_errno("got_object_id_dup");
7638 goto done;
7641 err = got_object_open_as_commit(&commit, repo, commit_id);
7642 if (err)
7643 goto done;
7646 * The root is opened here and will be closed when the view is closed.
7647 * Any visited subtrees and their path-wise parents are opened and
7648 * closed on demand.
7650 err = got_object_open_as_tree(&s->root, repo,
7651 got_object_commit_get_tree_id(commit));
7652 if (err)
7653 goto done;
7654 s->tree = s->root;
7656 err = got_object_id_str(&commit_id_str, commit_id);
7657 if (err != NULL)
7658 goto done;
7660 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7661 err = got_error_from_errno("asprintf");
7662 goto done;
7665 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7666 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7667 if (head_ref_name) {
7668 s->head_ref_name = strdup(head_ref_name);
7669 if (s->head_ref_name == NULL) {
7670 err = got_error_from_errno("strdup");
7671 goto done;
7674 s->repo = repo;
7676 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7677 err = add_color(&s->colors, "\\$$",
7678 TOG_COLOR_TREE_SUBMODULE,
7679 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7680 if (err)
7681 goto done;
7682 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7683 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7684 if (err)
7685 goto done;
7686 err = add_color(&s->colors, "/$",
7687 TOG_COLOR_TREE_DIRECTORY,
7688 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7689 if (err)
7690 goto done;
7692 err = add_color(&s->colors, "\\*$",
7693 TOG_COLOR_TREE_EXECUTABLE,
7694 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7695 if (err)
7696 goto done;
7698 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7699 get_color_value("TOG_COLOR_COMMIT"));
7700 if (err)
7701 goto done;
7704 view->show = show_tree_view;
7705 view->input = input_tree_view;
7706 view->close = close_tree_view;
7707 view->search_start = search_start_tree_view;
7708 view->search_next = search_next_tree_view;
7709 done:
7710 free(commit_id_str);
7711 if (commit)
7712 got_object_commit_close(commit);
7713 if (err) {
7714 if (view->close == NULL)
7715 close_tree_view(view);
7716 view_close(view);
7718 return err;
7721 static const struct got_error *
7722 close_tree_view(struct tog_view *view)
7724 struct tog_tree_view_state *s = &view->state.tree;
7726 free_colors(&s->colors);
7727 free(s->tree_label);
7728 s->tree_label = NULL;
7729 free(s->commit_id);
7730 s->commit_id = NULL;
7731 free(s->head_ref_name);
7732 s->head_ref_name = NULL;
7733 while (!TAILQ_EMPTY(&s->parents)) {
7734 struct tog_parent_tree *parent;
7735 parent = TAILQ_FIRST(&s->parents);
7736 TAILQ_REMOVE(&s->parents, parent, entry);
7737 if (parent->tree != s->root)
7738 got_object_tree_close(parent->tree);
7739 free(parent);
7742 if (s->tree != NULL && s->tree != s->root)
7743 got_object_tree_close(s->tree);
7744 if (s->root)
7745 got_object_tree_close(s->root);
7746 return NULL;
7749 static const struct got_error *
7750 search_start_tree_view(struct tog_view *view)
7752 struct tog_tree_view_state *s = &view->state.tree;
7754 s->matched_entry = NULL;
7755 return NULL;
7758 static int
7759 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7761 regmatch_t regmatch;
7763 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7764 0) == 0;
7767 static const struct got_error *
7768 search_next_tree_view(struct tog_view *view)
7770 struct tog_tree_view_state *s = &view->state.tree;
7771 struct got_tree_entry *te = NULL;
7773 if (!view->searching) {
7774 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7775 return NULL;
7778 if (s->matched_entry) {
7779 if (view->searching == TOG_SEARCH_FORWARD) {
7780 if (s->selected_entry)
7781 te = got_tree_entry_get_next(s->tree,
7782 s->selected_entry);
7783 else
7784 te = got_object_tree_get_first_entry(s->tree);
7785 } else {
7786 if (s->selected_entry == NULL)
7787 te = got_object_tree_get_last_entry(s->tree);
7788 else
7789 te = got_tree_entry_get_prev(s->tree,
7790 s->selected_entry);
7792 } else {
7793 if (s->selected_entry)
7794 te = s->selected_entry;
7795 else if (view->searching == TOG_SEARCH_FORWARD)
7796 te = got_object_tree_get_first_entry(s->tree);
7797 else
7798 te = got_object_tree_get_last_entry(s->tree);
7801 while (1) {
7802 if (te == NULL) {
7803 if (s->matched_entry == NULL) {
7804 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7805 return NULL;
7807 if (view->searching == TOG_SEARCH_FORWARD)
7808 te = got_object_tree_get_first_entry(s->tree);
7809 else
7810 te = got_object_tree_get_last_entry(s->tree);
7813 if (match_tree_entry(te, &view->regex)) {
7814 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7815 s->matched_entry = te;
7816 break;
7819 if (view->searching == TOG_SEARCH_FORWARD)
7820 te = got_tree_entry_get_next(s->tree, te);
7821 else
7822 te = got_tree_entry_get_prev(s->tree, te);
7825 if (s->matched_entry) {
7826 s->first_displayed_entry = s->matched_entry;
7827 s->selected = 0;
7830 return NULL;
7833 static const struct got_error *
7834 show_tree_view(struct tog_view *view)
7836 const struct got_error *err = NULL;
7837 struct tog_tree_view_state *s = &view->state.tree;
7838 char *parent_path;
7840 err = tree_entry_path(&parent_path, &s->parents, NULL);
7841 if (err)
7842 return err;
7844 err = draw_tree_entries(view, parent_path);
7845 free(parent_path);
7847 view_border(view);
7848 return err;
7851 static const struct got_error *
7852 tree_goto_line(struct tog_view *view, int nlines)
7854 const struct got_error *err = NULL;
7855 struct tog_tree_view_state *s = &view->state.tree;
7856 struct got_tree_entry **fte, **lte, **ste;
7857 int g, last, first = 1, i = 1;
7858 int root = s->tree == s->root;
7859 int off = root ? 1 : 2;
7861 g = view->gline;
7862 view->gline = 0;
7864 if (g == 0)
7865 g = 1;
7866 else if (g > got_object_tree_get_nentries(s->tree))
7867 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7869 fte = &s->first_displayed_entry;
7870 lte = &s->last_displayed_entry;
7871 ste = &s->selected_entry;
7873 if (*fte != NULL) {
7874 first = got_tree_entry_get_index(*fte);
7875 first += off; /* account for ".." */
7877 last = got_tree_entry_get_index(*lte);
7878 last += off;
7880 if (g >= first && g <= last && g - first < nlines) {
7881 s->selected = g - first;
7882 return NULL; /* gline is on the current page */
7885 if (*ste != NULL) {
7886 i = got_tree_entry_get_index(*ste);
7887 i += off;
7890 if (i < g) {
7891 err = tree_scroll_down(view, g - i);
7892 if (err)
7893 return err;
7894 if (got_tree_entry_get_index(*lte) >=
7895 got_object_tree_get_nentries(s->tree) - 1 &&
7896 first + s->selected < g &&
7897 s->selected < s->ndisplayed - 1) {
7898 first = got_tree_entry_get_index(*fte);
7899 first += off;
7900 s->selected = g - first;
7902 } else if (i > g)
7903 tree_scroll_up(s, i - g);
7905 if (g < nlines &&
7906 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7907 s->selected = g - 1;
7909 return NULL;
7912 static const struct got_error *
7913 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7915 const struct got_error *err = NULL;
7916 struct tog_tree_view_state *s = &view->state.tree;
7917 struct got_tree_entry *te;
7918 int n, nscroll = view->nlines - 3;
7920 if (view->gline)
7921 return tree_goto_line(view, nscroll);
7923 switch (ch) {
7924 case '0':
7925 case '$':
7926 case KEY_RIGHT:
7927 case 'l':
7928 case KEY_LEFT:
7929 case 'h':
7930 horizontal_scroll_input(view, ch);
7931 break;
7932 case 'i':
7933 s->show_ids = !s->show_ids;
7934 view->count = 0;
7935 break;
7936 case 'L':
7937 view->count = 0;
7938 if (!s->selected_entry)
7939 break;
7940 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7941 break;
7942 case 'R':
7943 view->count = 0;
7944 err = view_request_new(new_view, view, TOG_VIEW_REF);
7945 break;
7946 case 'g':
7947 case '=':
7948 case KEY_HOME:
7949 s->selected = 0;
7950 view->count = 0;
7951 if (s->tree == s->root)
7952 s->first_displayed_entry =
7953 got_object_tree_get_first_entry(s->tree);
7954 else
7955 s->first_displayed_entry = NULL;
7956 break;
7957 case 'G':
7958 case '*':
7959 case KEY_END: {
7960 int eos = view->nlines - 3;
7962 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7963 --eos; /* border */
7964 s->selected = 0;
7965 view->count = 0;
7966 te = got_object_tree_get_last_entry(s->tree);
7967 for (n = 0; n < eos; n++) {
7968 if (te == NULL) {
7969 if (s->tree != s->root) {
7970 s->first_displayed_entry = NULL;
7971 n++;
7973 break;
7975 s->first_displayed_entry = te;
7976 te = got_tree_entry_get_prev(s->tree, te);
7978 if (n > 0)
7979 s->selected = n - 1;
7980 break;
7982 case 'k':
7983 case KEY_UP:
7984 case CTRL('p'):
7985 if (s->selected > 0) {
7986 s->selected--;
7987 break;
7989 tree_scroll_up(s, 1);
7990 if (s->selected_entry == NULL ||
7991 (s->tree == s->root && s->selected_entry ==
7992 got_object_tree_get_first_entry(s->tree)))
7993 view->count = 0;
7994 break;
7995 case CTRL('u'):
7996 case 'u':
7997 nscroll /= 2;
7998 /* FALL THROUGH */
7999 case KEY_PPAGE:
8000 case CTRL('b'):
8001 case 'b':
8002 if (s->tree == s->root) {
8003 if (got_object_tree_get_first_entry(s->tree) ==
8004 s->first_displayed_entry)
8005 s->selected -= MIN(s->selected, nscroll);
8006 } else {
8007 if (s->first_displayed_entry == NULL)
8008 s->selected -= MIN(s->selected, nscroll);
8010 tree_scroll_up(s, MAX(0, nscroll));
8011 if (s->selected_entry == NULL ||
8012 (s->tree == s->root && s->selected_entry ==
8013 got_object_tree_get_first_entry(s->tree)))
8014 view->count = 0;
8015 break;
8016 case 'j':
8017 case KEY_DOWN:
8018 case CTRL('n'):
8019 if (s->selected < s->ndisplayed - 1) {
8020 s->selected++;
8021 break;
8023 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8024 == NULL) {
8025 /* can't scroll any further */
8026 view->count = 0;
8027 break;
8029 tree_scroll_down(view, 1);
8030 break;
8031 case CTRL('d'):
8032 case 'd':
8033 nscroll /= 2;
8034 /* FALL THROUGH */
8035 case KEY_NPAGE:
8036 case CTRL('f'):
8037 case 'f':
8038 case ' ':
8039 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8040 == NULL) {
8041 /* can't scroll any further; move cursor down */
8042 if (s->selected < s->ndisplayed - 1)
8043 s->selected += MIN(nscroll,
8044 s->ndisplayed - s->selected - 1);
8045 else
8046 view->count = 0;
8047 break;
8049 tree_scroll_down(view, nscroll);
8050 break;
8051 case KEY_ENTER:
8052 case '\r':
8053 case KEY_BACKSPACE:
8054 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
8055 struct tog_parent_tree *parent;
8056 /* user selected '..' */
8057 if (s->tree == s->root) {
8058 view->count = 0;
8059 break;
8061 parent = TAILQ_FIRST(&s->parents);
8062 TAILQ_REMOVE(&s->parents, parent,
8063 entry);
8064 got_object_tree_close(s->tree);
8065 s->tree = parent->tree;
8066 s->first_displayed_entry =
8067 parent->first_displayed_entry;
8068 s->selected_entry =
8069 parent->selected_entry;
8070 s->selected = parent->selected;
8071 if (s->selected > view->nlines - 3) {
8072 err = offset_selection_down(view);
8073 if (err)
8074 break;
8076 free(parent);
8077 } else if (S_ISDIR(got_tree_entry_get_mode(
8078 s->selected_entry))) {
8079 struct got_tree_object *subtree;
8080 view->count = 0;
8081 err = got_object_open_as_tree(&subtree, s->repo,
8082 got_tree_entry_get_id(s->selected_entry));
8083 if (err)
8084 break;
8085 err = tree_view_visit_subtree(s, subtree);
8086 if (err) {
8087 got_object_tree_close(subtree);
8088 break;
8090 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
8091 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
8092 break;
8093 case KEY_RESIZE:
8094 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
8095 s->selected = view->nlines - 4;
8096 view->count = 0;
8097 break;
8098 default:
8099 view->count = 0;
8100 break;
8103 return err;
8106 __dead static void
8107 usage_tree(void)
8109 endwin();
8110 fprintf(stderr,
8111 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
8112 getprogname());
8113 exit(1);
8116 static const struct got_error *
8117 cmd_tree(int argc, char *argv[])
8119 const struct got_error *error;
8120 struct got_repository *repo = NULL;
8121 struct got_worktree *worktree = NULL;
8122 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8123 struct got_object_id *commit_id = NULL;
8124 struct got_commit_object *commit = NULL;
8125 const char *commit_id_arg = NULL;
8126 char *keyword_idstr = NULL, *label = NULL;
8127 struct got_reference *ref = NULL;
8128 const char *head_ref_name = NULL;
8129 int ch;
8130 struct tog_view *view;
8131 int *pack_fds = NULL;
8133 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
8134 switch (ch) {
8135 case 'c':
8136 commit_id_arg = optarg;
8137 break;
8138 case 'r':
8139 repo_path = realpath(optarg, NULL);
8140 if (repo_path == NULL)
8141 return got_error_from_errno2("realpath",
8142 optarg);
8143 break;
8144 default:
8145 usage_tree();
8146 /* NOTREACHED */
8150 argc -= optind;
8151 argv += optind;
8153 if (argc > 1)
8154 usage_tree();
8156 error = got_repo_pack_fds_open(&pack_fds);
8157 if (error != NULL)
8158 goto done;
8160 if (repo_path == NULL) {
8161 cwd = getcwd(NULL, 0);
8162 if (cwd == NULL)
8163 return got_error_from_errno("getcwd");
8164 error = got_worktree_open(&worktree, cwd, NULL);
8165 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8166 goto done;
8167 if (worktree)
8168 repo_path =
8169 strdup(got_worktree_get_repo_path(worktree));
8170 else
8171 repo_path = strdup(cwd);
8172 if (repo_path == NULL) {
8173 error = got_error_from_errno("strdup");
8174 goto done;
8178 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8179 if (error != NULL)
8180 goto done;
8182 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8183 repo, worktree);
8184 if (error)
8185 goto done;
8187 init_curses();
8189 error = apply_unveil(got_repo_get_path(repo), NULL);
8190 if (error)
8191 goto done;
8193 error = tog_load_refs(repo, 0);
8194 if (error)
8195 goto done;
8197 if (commit_id_arg == NULL) {
8198 error = got_repo_match_object_id(&commit_id, &label,
8199 worktree ? got_worktree_get_head_ref_name(worktree) :
8200 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8201 if (error)
8202 goto done;
8203 head_ref_name = label;
8204 } else {
8205 error = got_keyword_to_idstr(&keyword_idstr, commit_id_arg,
8206 repo, worktree);
8207 if (error != NULL)
8208 goto done;
8209 if (keyword_idstr != NULL)
8210 commit_id_arg = keyword_idstr;
8212 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8213 if (error == NULL)
8214 head_ref_name = got_ref_get_name(ref);
8215 else if (error->code != GOT_ERR_NOT_REF)
8216 goto done;
8217 error = got_repo_match_object_id(&commit_id, NULL,
8218 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8219 if (error)
8220 goto done;
8223 error = got_object_open_as_commit(&commit, repo, commit_id);
8224 if (error)
8225 goto done;
8227 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8228 if (view == NULL) {
8229 error = got_error_from_errno("view_open");
8230 goto done;
8232 error = open_tree_view(view, commit_id, head_ref_name, repo);
8233 if (error)
8234 goto done;
8235 if (!got_path_is_root_dir(in_repo_path)) {
8236 error = tree_view_walk_path(&view->state.tree, commit,
8237 in_repo_path);
8238 if (error)
8239 goto done;
8242 if (worktree) {
8243 error = set_tog_base_commit(repo, worktree);
8244 if (error != NULL)
8245 goto done;
8247 /* Release work tree lock. */
8248 got_worktree_close(worktree);
8249 worktree = NULL;
8252 error = view_loop(view);
8254 done:
8255 free(tog_base_commit.id);
8256 free(keyword_idstr);
8257 free(repo_path);
8258 free(cwd);
8259 free(commit_id);
8260 free(label);
8261 if (ref)
8262 got_ref_close(ref);
8263 if (worktree != NULL)
8264 got_worktree_close(worktree);
8265 if (repo) {
8266 const struct got_error *close_err = got_repo_close(repo);
8267 if (error == NULL)
8268 error = close_err;
8270 if (pack_fds) {
8271 const struct got_error *pack_err =
8272 got_repo_pack_fds_close(pack_fds);
8273 if (error == NULL)
8274 error = pack_err;
8276 tog_free_refs();
8277 return error;
8280 static const struct got_error *
8281 ref_view_load_refs(struct tog_ref_view_state *s)
8283 struct got_reflist_entry *sre;
8284 struct tog_reflist_entry *re;
8286 s->nrefs = 0;
8287 TAILQ_FOREACH(sre, &tog_refs, entry) {
8288 if (strncmp(got_ref_get_name(sre->ref),
8289 "refs/got/", 9) == 0 &&
8290 strncmp(got_ref_get_name(sre->ref),
8291 "refs/got/backup/", 16) != 0)
8292 continue;
8294 re = malloc(sizeof(*re));
8295 if (re == NULL)
8296 return got_error_from_errno("malloc");
8298 re->ref = got_ref_dup(sre->ref);
8299 if (re->ref == NULL)
8300 return got_error_from_errno("got_ref_dup");
8301 re->idx = s->nrefs++;
8302 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8305 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8306 return NULL;
8309 static void
8310 ref_view_free_refs(struct tog_ref_view_state *s)
8312 struct tog_reflist_entry *re;
8314 while (!TAILQ_EMPTY(&s->refs)) {
8315 re = TAILQ_FIRST(&s->refs);
8316 TAILQ_REMOVE(&s->refs, re, entry);
8317 got_ref_close(re->ref);
8318 free(re);
8322 static const struct got_error *
8323 open_ref_view(struct tog_view *view, struct got_repository *repo)
8325 const struct got_error *err = NULL;
8326 struct tog_ref_view_state *s = &view->state.ref;
8328 s->selected_entry = 0;
8329 s->repo = repo;
8331 TAILQ_INIT(&s->refs);
8332 STAILQ_INIT(&s->colors);
8334 err = ref_view_load_refs(s);
8335 if (err)
8336 goto done;
8338 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8339 err = add_color(&s->colors, "^refs/heads/",
8340 TOG_COLOR_REFS_HEADS,
8341 get_color_value("TOG_COLOR_REFS_HEADS"));
8342 if (err)
8343 goto done;
8345 err = add_color(&s->colors, "^refs/tags/",
8346 TOG_COLOR_REFS_TAGS,
8347 get_color_value("TOG_COLOR_REFS_TAGS"));
8348 if (err)
8349 goto done;
8351 err = add_color(&s->colors, "^refs/remotes/",
8352 TOG_COLOR_REFS_REMOTES,
8353 get_color_value("TOG_COLOR_REFS_REMOTES"));
8354 if (err)
8355 goto done;
8357 err = add_color(&s->colors, "^refs/got/backup/",
8358 TOG_COLOR_REFS_BACKUP,
8359 get_color_value("TOG_COLOR_REFS_BACKUP"));
8360 if (err)
8361 goto done;
8364 view->show = show_ref_view;
8365 view->input = input_ref_view;
8366 view->close = close_ref_view;
8367 view->search_start = search_start_ref_view;
8368 view->search_next = search_next_ref_view;
8369 done:
8370 if (err) {
8371 if (view->close == NULL)
8372 close_ref_view(view);
8373 view_close(view);
8375 return err;
8378 static const struct got_error *
8379 close_ref_view(struct tog_view *view)
8381 struct tog_ref_view_state *s = &view->state.ref;
8383 ref_view_free_refs(s);
8384 free_colors(&s->colors);
8386 return NULL;
8389 static const struct got_error *
8390 resolve_reflist_entry(struct got_object_id **commit_id,
8391 struct tog_reflist_entry *re, struct got_repository *repo)
8393 const struct got_error *err = NULL;
8394 struct got_object_id *obj_id;
8395 struct got_tag_object *tag = NULL;
8396 int obj_type;
8398 *commit_id = NULL;
8400 err = got_ref_resolve(&obj_id, repo, re->ref);
8401 if (err)
8402 return err;
8404 err = got_object_get_type(&obj_type, repo, obj_id);
8405 if (err)
8406 goto done;
8408 switch (obj_type) {
8409 case GOT_OBJ_TYPE_COMMIT:
8410 *commit_id = obj_id;
8411 break;
8412 case GOT_OBJ_TYPE_TAG:
8413 err = got_object_open_as_tag(&tag, repo, obj_id);
8414 if (err)
8415 goto done;
8416 free(obj_id);
8417 err = got_object_get_type(&obj_type, repo,
8418 got_object_tag_get_object_id(tag));
8419 if (err)
8420 goto done;
8421 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8422 err = got_error(GOT_ERR_OBJ_TYPE);
8423 goto done;
8425 *commit_id = got_object_id_dup(
8426 got_object_tag_get_object_id(tag));
8427 if (*commit_id == NULL) {
8428 err = got_error_from_errno("got_object_id_dup");
8429 goto done;
8431 break;
8432 default:
8433 err = got_error(GOT_ERR_OBJ_TYPE);
8434 break;
8437 done:
8438 if (tag)
8439 got_object_tag_close(tag);
8440 if (err) {
8441 free(*commit_id);
8442 *commit_id = NULL;
8444 return err;
8447 static const struct got_error *
8448 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8449 struct tog_reflist_entry *re, struct got_repository *repo)
8451 struct tog_view *log_view;
8452 const struct got_error *err = NULL;
8453 struct got_object_id *commit_id = NULL;
8455 *new_view = NULL;
8457 err = resolve_reflist_entry(&commit_id, re, repo);
8458 if (err) {
8459 if (err->code != GOT_ERR_OBJ_TYPE)
8460 return err;
8461 else
8462 return NULL;
8465 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8466 if (log_view == NULL) {
8467 err = got_error_from_errno("view_open");
8468 goto done;
8471 err = open_log_view(log_view, commit_id, repo,
8472 got_ref_get_name(re->ref), "", 0);
8473 done:
8474 if (err)
8475 view_close(log_view);
8476 else
8477 *new_view = log_view;
8478 free(commit_id);
8479 return err;
8482 static void
8483 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8485 struct tog_reflist_entry *re;
8486 int i = 0;
8488 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8489 return;
8491 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8492 while (i++ < maxscroll) {
8493 if (re == NULL)
8494 break;
8495 s->first_displayed_entry = re;
8496 re = TAILQ_PREV(re, tog_reflist_head, entry);
8500 static const struct got_error *
8501 ref_scroll_down(struct tog_view *view, int maxscroll)
8503 struct tog_ref_view_state *s = &view->state.ref;
8504 struct tog_reflist_entry *next, *last;
8505 int n = 0;
8507 if (s->first_displayed_entry)
8508 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8509 else
8510 next = TAILQ_FIRST(&s->refs);
8512 last = s->last_displayed_entry;
8513 while (next && n++ < maxscroll) {
8514 if (last) {
8515 s->last_displayed_entry = last;
8516 last = TAILQ_NEXT(last, entry);
8518 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8519 s->first_displayed_entry = next;
8520 next = TAILQ_NEXT(next, entry);
8524 return NULL;
8527 static const struct got_error *
8528 search_start_ref_view(struct tog_view *view)
8530 struct tog_ref_view_state *s = &view->state.ref;
8532 s->matched_entry = NULL;
8533 return NULL;
8536 static int
8537 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8539 regmatch_t regmatch;
8541 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8542 0) == 0;
8545 static const struct got_error *
8546 search_next_ref_view(struct tog_view *view)
8548 struct tog_ref_view_state *s = &view->state.ref;
8549 struct tog_reflist_entry *re = NULL;
8551 if (!view->searching) {
8552 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8553 return NULL;
8556 if (s->matched_entry) {
8557 if (view->searching == TOG_SEARCH_FORWARD) {
8558 if (s->selected_entry)
8559 re = TAILQ_NEXT(s->selected_entry, entry);
8560 else
8561 re = TAILQ_PREV(s->selected_entry,
8562 tog_reflist_head, entry);
8563 } else {
8564 if (s->selected_entry == NULL)
8565 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8566 else
8567 re = TAILQ_PREV(s->selected_entry,
8568 tog_reflist_head, entry);
8570 } else {
8571 if (s->selected_entry)
8572 re = s->selected_entry;
8573 else if (view->searching == TOG_SEARCH_FORWARD)
8574 re = TAILQ_FIRST(&s->refs);
8575 else
8576 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8579 while (1) {
8580 if (re == NULL) {
8581 if (s->matched_entry == NULL) {
8582 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8583 return NULL;
8585 if (view->searching == TOG_SEARCH_FORWARD)
8586 re = TAILQ_FIRST(&s->refs);
8587 else
8588 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8591 if (match_reflist_entry(re, &view->regex)) {
8592 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8593 s->matched_entry = re;
8594 break;
8597 if (view->searching == TOG_SEARCH_FORWARD)
8598 re = TAILQ_NEXT(re, entry);
8599 else
8600 re = TAILQ_PREV(re, tog_reflist_head, entry);
8603 if (s->matched_entry) {
8604 s->first_displayed_entry = s->matched_entry;
8605 s->selected = 0;
8608 return NULL;
8611 static const struct got_error *
8612 show_ref_view(struct tog_view *view)
8614 const struct got_error *err = NULL;
8615 struct tog_ref_view_state *s = &view->state.ref;
8616 struct tog_reflist_entry *re;
8617 char *line = NULL;
8618 wchar_t *wline;
8619 struct tog_color *tc;
8620 int width, n, scrollx;
8621 int limit = view->nlines;
8623 werase(view->window);
8625 s->ndisplayed = 0;
8626 if (view_is_hsplit_top(view))
8627 --limit; /* border */
8629 if (limit == 0)
8630 return NULL;
8632 re = s->first_displayed_entry;
8634 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8635 s->nrefs) == -1)
8636 return got_error_from_errno("asprintf");
8638 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8639 if (err) {
8640 free(line);
8641 return err;
8643 if (view_needs_focus_indication(view))
8644 wstandout(view->window);
8645 waddwstr(view->window, wline);
8646 while (width++ < view->ncols)
8647 waddch(view->window, ' ');
8648 if (view_needs_focus_indication(view))
8649 wstandend(view->window);
8650 free(wline);
8651 wline = NULL;
8652 free(line);
8653 line = NULL;
8654 if (--limit <= 0)
8655 return NULL;
8657 n = 0;
8658 view->maxx = 0;
8659 while (re && limit > 0) {
8660 char *line = NULL;
8661 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8663 if (s->show_date) {
8664 struct got_commit_object *ci;
8665 struct got_tag_object *tag;
8666 struct got_object_id *id;
8667 struct tm tm;
8668 time_t t;
8670 err = got_ref_resolve(&id, s->repo, re->ref);
8671 if (err)
8672 return err;
8673 err = got_object_open_as_tag(&tag, s->repo, id);
8674 if (err) {
8675 if (err->code != GOT_ERR_OBJ_TYPE) {
8676 free(id);
8677 return err;
8679 err = got_object_open_as_commit(&ci, s->repo,
8680 id);
8681 if (err) {
8682 free(id);
8683 return err;
8685 t = got_object_commit_get_committer_time(ci);
8686 got_object_commit_close(ci);
8687 } else {
8688 t = got_object_tag_get_tagger_time(tag);
8689 got_object_tag_close(tag);
8691 free(id);
8692 if (gmtime_r(&t, &tm) == NULL)
8693 return got_error_from_errno("gmtime_r");
8694 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8695 return got_error(GOT_ERR_NO_SPACE);
8697 if (got_ref_is_symbolic(re->ref)) {
8698 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8699 ymd : "", got_ref_get_name(re->ref),
8700 got_ref_get_symref_target(re->ref)) == -1)
8701 return got_error_from_errno("asprintf");
8702 } else if (s->show_ids) {
8703 struct got_object_id *id;
8704 char *id_str;
8705 err = got_ref_resolve(&id, s->repo, re->ref);
8706 if (err)
8707 return err;
8708 err = got_object_id_str(&id_str, id);
8709 if (err) {
8710 free(id);
8711 return err;
8713 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8714 got_ref_get_name(re->ref), id_str) == -1) {
8715 err = got_error_from_errno("asprintf");
8716 free(id);
8717 free(id_str);
8718 return err;
8720 free(id);
8721 free(id_str);
8722 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8723 got_ref_get_name(re->ref)) == -1)
8724 return got_error_from_errno("asprintf");
8726 /* use full line width to determine view->maxx */
8727 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8728 if (err) {
8729 free(line);
8730 return err;
8732 view->maxx = MAX(view->maxx, width);
8733 free(wline);
8734 wline = NULL;
8736 err = format_line(&wline, &width, &scrollx, line, view->x,
8737 view->ncols, 0, 0);
8738 if (err) {
8739 free(line);
8740 return err;
8742 if (n == s->selected) {
8743 if (view->focussed)
8744 wstandout(view->window);
8745 s->selected_entry = re;
8747 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8748 if (tc)
8749 wattr_on(view->window,
8750 COLOR_PAIR(tc->colorpair), NULL);
8751 waddwstr(view->window, &wline[scrollx]);
8752 if (tc)
8753 wattr_off(view->window,
8754 COLOR_PAIR(tc->colorpair), NULL);
8755 if (width < view->ncols)
8756 waddch(view->window, '\n');
8757 if (n == s->selected && view->focussed)
8758 wstandend(view->window);
8759 free(line);
8760 free(wline);
8761 wline = NULL;
8762 n++;
8763 s->ndisplayed++;
8764 s->last_displayed_entry = re;
8766 limit--;
8767 re = TAILQ_NEXT(re, entry);
8770 view_border(view);
8771 return err;
8774 static const struct got_error *
8775 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8776 struct tog_reflist_entry *re, struct got_repository *repo)
8778 const struct got_error *err = NULL;
8779 struct got_object_id *commit_id = NULL;
8780 struct tog_view *tree_view;
8782 *new_view = NULL;
8784 err = resolve_reflist_entry(&commit_id, re, repo);
8785 if (err) {
8786 if (err->code != GOT_ERR_OBJ_TYPE)
8787 return err;
8788 else
8789 return NULL;
8793 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8794 if (tree_view == NULL) {
8795 err = got_error_from_errno("view_open");
8796 goto done;
8799 err = open_tree_view(tree_view, commit_id,
8800 got_ref_get_name(re->ref), repo);
8801 if (err)
8802 goto done;
8804 *new_view = tree_view;
8805 done:
8806 free(commit_id);
8807 return err;
8810 static const struct got_error *
8811 ref_goto_line(struct tog_view *view, int nlines)
8813 const struct got_error *err = NULL;
8814 struct tog_ref_view_state *s = &view->state.ref;
8815 int g, idx = s->selected_entry->idx;
8817 g = view->gline;
8818 view->gline = 0;
8820 if (g == 0)
8821 g = 1;
8822 else if (g > s->nrefs)
8823 g = s->nrefs;
8825 if (g >= s->first_displayed_entry->idx + 1 &&
8826 g <= s->last_displayed_entry->idx + 1 &&
8827 g - s->first_displayed_entry->idx - 1 < nlines) {
8828 s->selected = g - s->first_displayed_entry->idx - 1;
8829 return NULL;
8832 if (idx + 1 < g) {
8833 err = ref_scroll_down(view, g - idx - 1);
8834 if (err)
8835 return err;
8836 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8837 s->first_displayed_entry->idx + s->selected < g &&
8838 s->selected < s->ndisplayed - 1)
8839 s->selected = g - s->first_displayed_entry->idx - 1;
8840 } else if (idx + 1 > g)
8841 ref_scroll_up(s, idx - g + 1);
8843 if (g < nlines && s->first_displayed_entry->idx == 0)
8844 s->selected = g - 1;
8846 return NULL;
8850 static const struct got_error *
8851 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8853 const struct got_error *err = NULL;
8854 struct tog_ref_view_state *s = &view->state.ref;
8855 struct tog_reflist_entry *re;
8856 int n, nscroll = view->nlines - 1;
8858 if (view->gline)
8859 return ref_goto_line(view, nscroll);
8861 switch (ch) {
8862 case '0':
8863 case '$':
8864 case KEY_RIGHT:
8865 case 'l':
8866 case KEY_LEFT:
8867 case 'h':
8868 horizontal_scroll_input(view, ch);
8869 break;
8870 case 'i':
8871 s->show_ids = !s->show_ids;
8872 view->count = 0;
8873 break;
8874 case 'm':
8875 s->show_date = !s->show_date;
8876 view->count = 0;
8877 break;
8878 case 'o':
8879 s->sort_by_date = !s->sort_by_date;
8880 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8881 view->count = 0;
8882 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8883 got_ref_cmp_by_commit_timestamp_descending :
8884 tog_ref_cmp_by_name, s->repo);
8885 if (err)
8886 break;
8887 got_reflist_object_id_map_free(tog_refs_idmap);
8888 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8889 &tog_refs, s->repo);
8890 if (err)
8891 break;
8892 ref_view_free_refs(s);
8893 err = ref_view_load_refs(s);
8894 break;
8895 case KEY_ENTER:
8896 case '\r':
8897 view->count = 0;
8898 if (!s->selected_entry)
8899 break;
8900 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8901 break;
8902 case 'T':
8903 view->count = 0;
8904 if (!s->selected_entry)
8905 break;
8906 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8907 break;
8908 case 'g':
8909 case '=':
8910 case KEY_HOME:
8911 s->selected = 0;
8912 view->count = 0;
8913 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8914 break;
8915 case 'G':
8916 case '*':
8917 case KEY_END: {
8918 int eos = view->nlines - 1;
8920 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8921 --eos; /* border */
8922 s->selected = 0;
8923 view->count = 0;
8924 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8925 for (n = 0; n < eos; n++) {
8926 if (re == NULL)
8927 break;
8928 s->first_displayed_entry = re;
8929 re = TAILQ_PREV(re, tog_reflist_head, entry);
8931 if (n > 0)
8932 s->selected = n - 1;
8933 break;
8935 case 'k':
8936 case KEY_UP:
8937 case CTRL('p'):
8938 if (s->selected > 0) {
8939 s->selected--;
8940 break;
8942 ref_scroll_up(s, 1);
8943 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8944 view->count = 0;
8945 break;
8946 case CTRL('u'):
8947 case 'u':
8948 nscroll /= 2;
8949 /* FALL THROUGH */
8950 case KEY_PPAGE:
8951 case CTRL('b'):
8952 case 'b':
8953 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8954 s->selected -= MIN(nscroll, s->selected);
8955 ref_scroll_up(s, MAX(0, nscroll));
8956 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8957 view->count = 0;
8958 break;
8959 case 'j':
8960 case KEY_DOWN:
8961 case CTRL('n'):
8962 if (s->selected < s->ndisplayed - 1) {
8963 s->selected++;
8964 break;
8966 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8967 /* can't scroll any further */
8968 view->count = 0;
8969 break;
8971 ref_scroll_down(view, 1);
8972 break;
8973 case CTRL('d'):
8974 case 'd':
8975 nscroll /= 2;
8976 /* FALL THROUGH */
8977 case KEY_NPAGE:
8978 case CTRL('f'):
8979 case 'f':
8980 case ' ':
8981 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8982 /* can't scroll any further; move cursor down */
8983 if (s->selected < s->ndisplayed - 1)
8984 s->selected += MIN(nscroll,
8985 s->ndisplayed - s->selected - 1);
8986 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8987 s->selected += s->ndisplayed - s->selected - 1;
8988 view->count = 0;
8989 break;
8991 ref_scroll_down(view, nscroll);
8992 break;
8993 case CTRL('l'):
8994 view->count = 0;
8995 tog_free_refs();
8996 err = tog_load_refs(s->repo, s->sort_by_date);
8997 if (err)
8998 break;
8999 ref_view_free_refs(s);
9000 err = ref_view_load_refs(s);
9001 break;
9002 case KEY_RESIZE:
9003 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
9004 s->selected = view->nlines - 2;
9005 break;
9006 default:
9007 view->count = 0;
9008 break;
9011 return err;
9014 __dead static void
9015 usage_ref(void)
9017 endwin();
9018 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
9019 getprogname());
9020 exit(1);
9023 static const struct got_error *
9024 cmd_ref(int argc, char *argv[])
9026 const struct got_error *error;
9027 struct got_repository *repo = NULL;
9028 struct got_worktree *worktree = NULL;
9029 char *cwd = NULL, *repo_path = NULL;
9030 int ch;
9031 struct tog_view *view;
9032 int *pack_fds = NULL;
9034 while ((ch = getopt(argc, argv, "r:")) != -1) {
9035 switch (ch) {
9036 case 'r':
9037 repo_path = realpath(optarg, NULL);
9038 if (repo_path == NULL)
9039 return got_error_from_errno2("realpath",
9040 optarg);
9041 break;
9042 default:
9043 usage_ref();
9044 /* NOTREACHED */
9048 argc -= optind;
9049 argv += optind;
9051 if (argc > 1)
9052 usage_ref();
9054 error = got_repo_pack_fds_open(&pack_fds);
9055 if (error != NULL)
9056 goto done;
9058 if (repo_path == NULL) {
9059 cwd = getcwd(NULL, 0);
9060 if (cwd == NULL)
9061 return got_error_from_errno("getcwd");
9062 error = got_worktree_open(&worktree, cwd, NULL);
9063 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9064 goto done;
9065 if (worktree)
9066 repo_path =
9067 strdup(got_worktree_get_repo_path(worktree));
9068 else
9069 repo_path = strdup(cwd);
9070 if (repo_path == NULL) {
9071 error = got_error_from_errno("strdup");
9072 goto done;
9076 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9077 if (error != NULL)
9078 goto done;
9080 init_curses();
9082 error = apply_unveil(got_repo_get_path(repo), NULL);
9083 if (error)
9084 goto done;
9086 error = tog_load_refs(repo, 0);
9087 if (error)
9088 goto done;
9090 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
9091 if (view == NULL) {
9092 error = got_error_from_errno("view_open");
9093 goto done;
9096 error = open_ref_view(view, repo);
9097 if (error)
9098 goto done;
9100 if (worktree) {
9101 error = set_tog_base_commit(repo, worktree);
9102 if (error != NULL)
9103 goto done;
9105 /* Release work tree lock. */
9106 got_worktree_close(worktree);
9107 worktree = NULL;
9110 error = view_loop(view);
9112 done:
9113 free(tog_base_commit.id);
9114 free(repo_path);
9115 free(cwd);
9116 if (worktree != NULL)
9117 got_worktree_close(worktree);
9118 if (repo) {
9119 const struct got_error *close_err = got_repo_close(repo);
9120 if (close_err)
9121 error = close_err;
9123 if (pack_fds) {
9124 const struct got_error *pack_err =
9125 got_repo_pack_fds_close(pack_fds);
9126 if (error == NULL)
9127 error = pack_err;
9129 tog_free_refs();
9130 return error;
9133 static const struct got_error*
9134 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
9135 const char *str)
9137 size_t len;
9139 if (win == NULL)
9140 win = stdscr;
9142 len = strlen(str);
9143 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
9145 if (focus)
9146 wstandout(win);
9147 if (mvwprintw(win, y, x, "%s", str) == ERR)
9148 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
9149 if (focus)
9150 wstandend(win);
9152 return NULL;
9155 static const struct got_error *
9156 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
9158 off_t *p;
9160 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
9161 if (p == NULL) {
9162 free(*line_offsets);
9163 *line_offsets = NULL;
9164 return got_error_from_errno("reallocarray");
9167 *line_offsets = p;
9168 (*line_offsets)[*nlines] = off;
9169 ++(*nlines);
9170 return NULL;
9173 static const struct got_error *
9174 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
9176 *ret = 0;
9178 for (;n > 0; --n, ++km) {
9179 char *t0, *t, *k;
9180 size_t len = 1;
9182 if (km->keys == NULL)
9183 continue;
9185 t = t0 = strdup(km->keys);
9186 if (t0 == NULL)
9187 return got_error_from_errno("strdup");
9189 len += strlen(t);
9190 while ((k = strsep(&t, " ")) != NULL)
9191 len += strlen(k) > 1 ? 2 : 0;
9192 free(t0);
9193 *ret = MAX(*ret, len);
9196 return NULL;
9200 * Write keymap section headers, keys, and key info in km to f.
9201 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9202 * wrap control and symbolic keys in guillemets, else use <>.
9204 static const struct got_error *
9205 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9207 int n, len = width;
9209 if (km->keys) {
9210 static const char *u8_glyph[] = {
9211 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9212 "\xe2\x80\xba" /* U+203A (utf8 >) */
9214 char *t0, *t, *k;
9215 int cs, s, first = 1;
9217 cs = got_locale_is_utf8();
9219 t = t0 = strdup(km->keys);
9220 if (t0 == NULL)
9221 return got_error_from_errno("strdup");
9223 len = strlen(km->keys);
9224 while ((k = strsep(&t, " ")) != NULL) {
9225 s = strlen(k) > 1; /* control or symbolic key */
9226 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9227 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9228 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9229 if (n < 0) {
9230 free(t0);
9231 return got_error_from_errno("fprintf");
9233 first = 0;
9234 len += s ? 2 : 0;
9235 *off += n;
9237 free(t0);
9239 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9240 if (n < 0)
9241 return got_error_from_errno("fprintf");
9242 *off += n;
9244 return NULL;
9247 static const struct got_error *
9248 format_help(struct tog_help_view_state *s)
9250 const struct got_error *err = NULL;
9251 off_t off = 0;
9252 int i, max, n, show = s->all;
9253 static const struct tog_key_map km[] = {
9254 #define KEYMAP_(info, type) { NULL, (info), type }
9255 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9256 GENERATE_HELP
9257 #undef KEYMAP_
9258 #undef KEY_
9261 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9262 if (err)
9263 return err;
9265 n = nitems(km);
9266 err = max_key_str(&max, km, n);
9267 if (err)
9268 return err;
9270 for (i = 0; i < n; ++i) {
9271 if (km[i].keys == NULL) {
9272 show = s->all;
9273 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9274 km[i].type == s->type || s->all)
9275 show = 1;
9277 if (show) {
9278 err = format_help_line(&off, s->f, &km[i], max);
9279 if (err)
9280 return err;
9281 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9282 if (err)
9283 return err;
9286 fputc('\n', s->f);
9287 ++off;
9288 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9289 return err;
9292 static const struct got_error *
9293 create_help(struct tog_help_view_state *s)
9295 FILE *f;
9296 const struct got_error *err;
9298 free(s->line_offsets);
9299 s->line_offsets = NULL;
9300 s->nlines = 0;
9302 f = got_opentemp();
9303 if (f == NULL)
9304 return got_error_from_errno("got_opentemp");
9305 s->f = f;
9307 err = format_help(s);
9308 if (err)
9309 return err;
9311 if (s->f && fflush(s->f) != 0)
9312 return got_error_from_errno("fflush");
9314 return NULL;
9317 static const struct got_error *
9318 search_start_help_view(struct tog_view *view)
9320 view->state.help.matched_line = 0;
9321 return NULL;
9324 static void
9325 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9326 size_t *nlines, int **first, int **last, int **match, int **selected)
9328 struct tog_help_view_state *s = &view->state.help;
9330 *f = s->f;
9331 *nlines = s->nlines;
9332 *line_offsets = s->line_offsets;
9333 *match = &s->matched_line;
9334 *first = &s->first_displayed_line;
9335 *last = &s->last_displayed_line;
9336 *selected = &s->selected_line;
9339 static const struct got_error *
9340 show_help_view(struct tog_view *view)
9342 struct tog_help_view_state *s = &view->state.help;
9343 const struct got_error *err;
9344 regmatch_t *regmatch = &view->regmatch;
9345 wchar_t *wline;
9346 char *line;
9347 ssize_t linelen;
9348 size_t linesz = 0;
9349 int width, nprinted = 0, rc = 0;
9350 int eos = view->nlines;
9352 if (view_is_hsplit_top(view))
9353 --eos; /* account for border */
9355 s->lineno = 0;
9356 rewind(s->f);
9357 werase(view->window);
9359 if (view->gline > s->nlines - 1)
9360 view->gline = s->nlines - 1;
9362 err = win_draw_center(view->window, 0, 0, view->ncols,
9363 view_needs_focus_indication(view),
9364 "tog help (press q to return to tog)");
9365 if (err)
9366 return err;
9367 if (eos <= 1)
9368 return NULL;
9369 waddstr(view->window, "\n\n");
9370 eos -= 2;
9372 s->eof = 0;
9373 view->maxx = 0;
9374 line = NULL;
9375 while (eos > 0 && nprinted < eos) {
9376 attr_t attr = 0;
9378 linelen = getline(&line, &linesz, s->f);
9379 if (linelen == -1) {
9380 if (!feof(s->f)) {
9381 free(line);
9382 return got_ferror(s->f, GOT_ERR_IO);
9384 s->eof = 1;
9385 break;
9387 if (++s->lineno < s->first_displayed_line)
9388 continue;
9389 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9390 continue;
9391 if (s->lineno == view->hiline)
9392 attr = A_STANDOUT;
9394 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9395 view->x ? 1 : 0);
9396 if (err) {
9397 free(line);
9398 return err;
9400 view->maxx = MAX(view->maxx, width);
9401 free(wline);
9402 wline = NULL;
9404 if (attr)
9405 wattron(view->window, attr);
9406 if (s->first_displayed_line + nprinted == s->matched_line &&
9407 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9408 err = add_matched_line(&width, line, view->ncols - 1, 0,
9409 view->window, view->x, regmatch);
9410 if (err) {
9411 free(line);
9412 return err;
9414 } else {
9415 int skip;
9417 err = format_line(&wline, &width, &skip, line,
9418 view->x, view->ncols, 0, view->x ? 1 : 0);
9419 if (err) {
9420 free(line);
9421 return err;
9423 waddwstr(view->window, &wline[skip]);
9424 free(wline);
9425 wline = NULL;
9427 if (s->lineno == view->hiline) {
9428 while (width++ < view->ncols)
9429 waddch(view->window, ' ');
9430 } else {
9431 if (width < view->ncols)
9432 waddch(view->window, '\n');
9434 if (attr)
9435 wattroff(view->window, attr);
9436 if (++nprinted == 1)
9437 s->first_displayed_line = s->lineno;
9439 free(line);
9440 if (nprinted > 0)
9441 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9442 else
9443 s->last_displayed_line = s->first_displayed_line;
9445 view_border(view);
9447 if (s->eof) {
9448 rc = waddnstr(view->window,
9449 "See the tog(1) manual page for full documentation",
9450 view->ncols - 1);
9451 if (rc == ERR)
9452 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9453 } else {
9454 wmove(view->window, view->nlines - 1, 0);
9455 wclrtoeol(view->window);
9456 wstandout(view->window);
9457 rc = waddnstr(view->window, "scroll down for more...",
9458 view->ncols - 1);
9459 if (rc == ERR)
9460 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9461 if (getcurx(view->window) < view->ncols - 6) {
9462 rc = wprintw(view->window, "[%.0f%%]",
9463 100.00 * s->last_displayed_line / s->nlines);
9464 if (rc == ERR)
9465 return got_error_msg(GOT_ERR_IO, "wprintw");
9467 wstandend(view->window);
9470 return NULL;
9473 static const struct got_error *
9474 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9476 struct tog_help_view_state *s = &view->state.help;
9477 const struct got_error *err = NULL;
9478 char *line = NULL;
9479 ssize_t linelen;
9480 size_t linesz = 0;
9481 int eos, nscroll;
9483 eos = nscroll = view->nlines;
9484 if (view_is_hsplit_top(view))
9485 --eos; /* border */
9487 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9489 switch (ch) {
9490 case '0':
9491 case '$':
9492 case KEY_RIGHT:
9493 case 'l':
9494 case KEY_LEFT:
9495 case 'h':
9496 horizontal_scroll_input(view, ch);
9497 break;
9498 case 'g':
9499 case KEY_HOME:
9500 s->first_displayed_line = 1;
9501 view->count = 0;
9502 break;
9503 case 'G':
9504 case KEY_END:
9505 view->count = 0;
9506 if (s->eof)
9507 break;
9508 s->first_displayed_line = (s->nlines - eos) + 3;
9509 s->eof = 1;
9510 break;
9511 case 'k':
9512 case KEY_UP:
9513 if (s->first_displayed_line > 1)
9514 --s->first_displayed_line;
9515 else
9516 view->count = 0;
9517 break;
9518 case CTRL('u'):
9519 case 'u':
9520 nscroll /= 2;
9521 /* FALL THROUGH */
9522 case KEY_PPAGE:
9523 case CTRL('b'):
9524 case 'b':
9525 if (s->first_displayed_line == 1) {
9526 view->count = 0;
9527 break;
9529 while (--nscroll > 0 && s->first_displayed_line > 1)
9530 s->first_displayed_line--;
9531 break;
9532 case 'j':
9533 case KEY_DOWN:
9534 case CTRL('n'):
9535 if (!s->eof)
9536 ++s->first_displayed_line;
9537 else
9538 view->count = 0;
9539 break;
9540 case CTRL('d'):
9541 case 'd':
9542 nscroll /= 2;
9543 /* FALL THROUGH */
9544 case KEY_NPAGE:
9545 case CTRL('f'):
9546 case 'f':
9547 case ' ':
9548 if (s->eof) {
9549 view->count = 0;
9550 break;
9552 while (!s->eof && --nscroll > 0) {
9553 linelen = getline(&line, &linesz, s->f);
9554 s->first_displayed_line++;
9555 if (linelen == -1) {
9556 if (feof(s->f))
9557 s->eof = 1;
9558 else
9559 err = got_ferror(s->f, GOT_ERR_IO);
9560 break;
9563 free(line);
9564 break;
9565 default:
9566 view->count = 0;
9567 break;
9570 return err;
9573 static const struct got_error *
9574 close_help_view(struct tog_view *view)
9576 struct tog_help_view_state *s = &view->state.help;
9578 free(s->line_offsets);
9579 s->line_offsets = NULL;
9580 if (fclose(s->f) == EOF)
9581 return got_error_from_errno("fclose");
9583 return NULL;
9586 static const struct got_error *
9587 reset_help_view(struct tog_view *view)
9589 struct tog_help_view_state *s = &view->state.help;
9592 if (s->f && fclose(s->f) == EOF)
9593 return got_error_from_errno("fclose");
9595 wclear(view->window);
9596 view->count = 0;
9597 view->x = 0;
9598 s->all = !s->all;
9599 s->first_displayed_line = 1;
9600 s->last_displayed_line = view->nlines;
9601 s->matched_line = 0;
9603 return create_help(s);
9606 static const struct got_error *
9607 open_help_view(struct tog_view *view, struct tog_view *parent)
9609 const struct got_error *err = NULL;
9610 struct tog_help_view_state *s = &view->state.help;
9612 s->type = (enum tog_keymap_type)parent->type;
9613 s->first_displayed_line = 1;
9614 s->last_displayed_line = view->nlines;
9615 s->selected_line = 1;
9617 view->show = show_help_view;
9618 view->input = input_help_view;
9619 view->reset = reset_help_view;
9620 view->close = close_help_view;
9621 view->search_start = search_start_help_view;
9622 view->search_setup = search_setup_help_view;
9623 view->search_next = search_next_view_match;
9625 err = create_help(s);
9626 return err;
9629 static const struct got_error *
9630 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9631 enum tog_view_type request, int y, int x)
9633 const struct got_error *err = NULL;
9635 *new_view = NULL;
9637 switch (request) {
9638 case TOG_VIEW_DIFF:
9639 if (view->type == TOG_VIEW_LOG) {
9640 struct tog_log_view_state *s = &view->state.log;
9642 err = open_diff_view_for_commit(new_view, y, x,
9643 s->selected_entry->commit, s->selected_entry->id,
9644 view, s->repo);
9645 } else
9646 return got_error_msg(GOT_ERR_NOT_IMPL,
9647 "parent/child view pair not supported");
9648 break;
9649 case TOG_VIEW_BLAME:
9650 if (view->type == TOG_VIEW_TREE) {
9651 struct tog_tree_view_state *s = &view->state.tree;
9653 err = blame_tree_entry(new_view, y, x,
9654 s->selected_entry, &s->parents, s->commit_id,
9655 s->repo);
9656 } else
9657 return got_error_msg(GOT_ERR_NOT_IMPL,
9658 "parent/child view pair not supported");
9659 break;
9660 case TOG_VIEW_LOG:
9661 if (view->type == TOG_VIEW_BLAME)
9662 err = log_annotated_line(new_view, y, x,
9663 view->state.blame.repo, view->state.blame.id_to_log);
9664 else if (view->type == TOG_VIEW_TREE)
9665 err = log_selected_tree_entry(new_view, y, x,
9666 &view->state.tree);
9667 else if (view->type == TOG_VIEW_REF)
9668 err = log_ref_entry(new_view, y, x,
9669 view->state.ref.selected_entry,
9670 view->state.ref.repo);
9671 else
9672 return got_error_msg(GOT_ERR_NOT_IMPL,
9673 "parent/child view pair not supported");
9674 break;
9675 case TOG_VIEW_TREE:
9676 if (view->type == TOG_VIEW_LOG)
9677 err = browse_commit_tree(new_view, y, x,
9678 view->state.log.selected_entry,
9679 view->state.log.in_repo_path,
9680 view->state.log.head_ref_name,
9681 view->state.log.repo);
9682 else if (view->type == TOG_VIEW_REF)
9683 err = browse_ref_tree(new_view, y, x,
9684 view->state.ref.selected_entry,
9685 view->state.ref.repo);
9686 else
9687 return got_error_msg(GOT_ERR_NOT_IMPL,
9688 "parent/child view pair not supported");
9689 break;
9690 case TOG_VIEW_REF:
9691 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9692 if (*new_view == NULL)
9693 return got_error_from_errno("view_open");
9694 if (view->type == TOG_VIEW_LOG)
9695 err = open_ref_view(*new_view, view->state.log.repo);
9696 else if (view->type == TOG_VIEW_TREE)
9697 err = open_ref_view(*new_view, view->state.tree.repo);
9698 else
9699 err = got_error_msg(GOT_ERR_NOT_IMPL,
9700 "parent/child view pair not supported");
9701 if (err)
9702 view_close(*new_view);
9703 break;
9704 case TOG_VIEW_HELP:
9705 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9706 if (*new_view == NULL)
9707 return got_error_from_errno("view_open");
9708 err = open_help_view(*new_view, view);
9709 if (err)
9710 view_close(*new_view);
9711 break;
9712 default:
9713 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9716 return err;
9720 * If view was scrolled down to move the selected line into view when opening a
9721 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9723 static void
9724 offset_selection_up(struct tog_view *view)
9726 switch (view->type) {
9727 case TOG_VIEW_BLAME: {
9728 struct tog_blame_view_state *s = &view->state.blame;
9729 if (s->first_displayed_line == 1) {
9730 s->selected_line = MAX(s->selected_line - view->offset,
9731 1);
9732 break;
9734 if (s->first_displayed_line > view->offset)
9735 s->first_displayed_line -= view->offset;
9736 else
9737 s->first_displayed_line = 1;
9738 s->selected_line += view->offset;
9739 break;
9741 case TOG_VIEW_LOG:
9742 log_scroll_up(&view->state.log, view->offset);
9743 view->state.log.selected += view->offset;
9744 break;
9745 case TOG_VIEW_REF:
9746 ref_scroll_up(&view->state.ref, view->offset);
9747 view->state.ref.selected += view->offset;
9748 break;
9749 case TOG_VIEW_TREE:
9750 tree_scroll_up(&view->state.tree, view->offset);
9751 view->state.tree.selected += view->offset;
9752 break;
9753 default:
9754 break;
9757 view->offset = 0;
9761 * If the selected line is in the section of screen covered by the bottom split,
9762 * scroll down offset lines to move it into view and index its new position.
9764 static const struct got_error *
9765 offset_selection_down(struct tog_view *view)
9767 const struct got_error *err = NULL;
9768 const struct got_error *(*scrolld)(struct tog_view *, int);
9769 int *selected = NULL;
9770 int header, offset;
9772 switch (view->type) {
9773 case TOG_VIEW_BLAME: {
9774 struct tog_blame_view_state *s = &view->state.blame;
9775 header = 3;
9776 scrolld = NULL;
9777 if (s->selected_line > view->nlines - header) {
9778 offset = abs(view->nlines - s->selected_line - header);
9779 s->first_displayed_line += offset;
9780 s->selected_line -= offset;
9781 view->offset = offset;
9783 break;
9785 case TOG_VIEW_LOG: {
9786 struct tog_log_view_state *s = &view->state.log;
9787 scrolld = &log_scroll_down;
9788 header = view_is_parent_view(view) ? 3 : 2;
9789 selected = &s->selected;
9790 break;
9792 case TOG_VIEW_REF: {
9793 struct tog_ref_view_state *s = &view->state.ref;
9794 scrolld = &ref_scroll_down;
9795 header = 3;
9796 selected = &s->selected;
9797 break;
9799 case TOG_VIEW_TREE: {
9800 struct tog_tree_view_state *s = &view->state.tree;
9801 scrolld = &tree_scroll_down;
9802 header = 5;
9803 selected = &s->selected;
9804 break;
9806 default:
9807 selected = NULL;
9808 scrolld = NULL;
9809 header = 0;
9810 break;
9813 if (selected && *selected > view->nlines - header) {
9814 offset = abs(view->nlines - *selected - header);
9815 view->offset = offset;
9816 if (scrolld && offset) {
9817 err = scrolld(view, offset);
9818 *selected -= offset;
9822 return err;
9825 static void
9826 list_commands(FILE *fp)
9828 size_t i;
9830 fprintf(fp, "commands:");
9831 for (i = 0; i < nitems(tog_commands); i++) {
9832 const struct tog_cmd *cmd = &tog_commands[i];
9833 fprintf(fp, " %s", cmd->name);
9835 fputc('\n', fp);
9838 __dead static void
9839 usage(int hflag, int status)
9841 FILE *fp = (status == 0) ? stdout : stderr;
9843 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9844 getprogname());
9845 if (hflag) {
9846 fprintf(fp, "lazy usage: %s path\n", getprogname());
9847 list_commands(fp);
9849 exit(status);
9852 static char **
9853 make_argv(int argc, ...)
9855 va_list ap;
9856 char **argv;
9857 int i;
9859 va_start(ap, argc);
9861 argv = calloc(argc, sizeof(char *));
9862 if (argv == NULL)
9863 err(1, "calloc");
9864 for (i = 0; i < argc; i++) {
9865 argv[i] = strdup(va_arg(ap, char *));
9866 if (argv[i] == NULL)
9867 err(1, "strdup");
9870 va_end(ap);
9871 return argv;
9875 * Try to convert 'tog path' into a 'tog log path' command.
9876 * The user could simply have mistyped the command rather than knowingly
9877 * provided a path. So check whether argv[0] can in fact be resolved
9878 * to a path in the HEAD commit and print a special error if not.
9879 * This hack is for mpi@ <3
9881 static const struct got_error *
9882 tog_log_with_path(int argc, char *argv[])
9884 const struct got_error *error = NULL, *close_err;
9885 const struct tog_cmd *cmd = NULL;
9886 struct got_repository *repo = NULL;
9887 struct got_worktree *worktree = NULL;
9888 struct got_object_id *commit_id = NULL, *id = NULL;
9889 struct got_commit_object *commit = NULL;
9890 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9891 char *commit_id_str = NULL, **cmd_argv = NULL;
9892 int *pack_fds = NULL;
9894 cwd = getcwd(NULL, 0);
9895 if (cwd == NULL)
9896 return got_error_from_errno("getcwd");
9898 error = got_repo_pack_fds_open(&pack_fds);
9899 if (error != NULL)
9900 goto done;
9902 error = got_worktree_open(&worktree, cwd, NULL);
9903 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9904 goto done;
9906 if (worktree)
9907 repo_path = strdup(got_worktree_get_repo_path(worktree));
9908 else
9909 repo_path = strdup(cwd);
9910 if (repo_path == NULL) {
9911 error = got_error_from_errno("strdup");
9912 goto done;
9915 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9916 if (error != NULL)
9917 goto done;
9919 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9920 repo, worktree);
9921 if (error)
9922 goto done;
9924 error = tog_load_refs(repo, 0);
9925 if (error)
9926 goto done;
9927 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9928 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9929 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9930 if (error)
9931 goto done;
9933 if (worktree) {
9934 got_worktree_close(worktree);
9935 worktree = NULL;
9938 error = got_object_open_as_commit(&commit, repo, commit_id);
9939 if (error)
9940 goto done;
9942 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9943 if (error) {
9944 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9945 goto done;
9946 fprintf(stderr, "%s: '%s' is no known command or path\n",
9947 getprogname(), argv[0]);
9948 usage(1, 1);
9949 /* not reached */
9952 error = got_object_id_str(&commit_id_str, commit_id);
9953 if (error)
9954 goto done;
9956 cmd = &tog_commands[0]; /* log */
9957 argc = 4;
9958 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9959 error = cmd->cmd_main(argc, cmd_argv);
9960 done:
9961 if (repo) {
9962 close_err = got_repo_close(repo);
9963 if (error == NULL)
9964 error = close_err;
9966 if (commit)
9967 got_object_commit_close(commit);
9968 if (worktree)
9969 got_worktree_close(worktree);
9970 if (pack_fds) {
9971 const struct got_error *pack_err =
9972 got_repo_pack_fds_close(pack_fds);
9973 if (error == NULL)
9974 error = pack_err;
9976 free(id);
9977 free(commit_id_str);
9978 free(commit_id);
9979 free(cwd);
9980 free(repo_path);
9981 free(in_repo_path);
9982 if (cmd_argv) {
9983 int i;
9984 for (i = 0; i < argc; i++)
9985 free(cmd_argv[i]);
9986 free(cmd_argv);
9988 tog_free_refs();
9989 return error;
9992 int
9993 main(int argc, char *argv[])
9995 const struct got_error *io_err, *error = NULL;
9996 const struct tog_cmd *cmd = NULL;
9997 int ch, hflag = 0, Vflag = 0;
9998 char **cmd_argv = NULL;
9999 static const struct option longopts[] = {
10000 { "version", no_argument, NULL, 'V' },
10001 { NULL, 0, NULL, 0}
10003 char *diff_algo_str = NULL;
10004 const char *test_script_path;
10006 setlocale(LC_CTYPE, "");
10009 * Test mode init must happen before pledge() because "tty" will
10010 * not allow TTY-related ioctls to occur via regular files.
10012 test_script_path = getenv("TOG_TEST_SCRIPT");
10013 if (test_script_path != NULL) {
10014 error = init_mock_term(test_script_path);
10015 if (error) {
10016 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10017 return 1;
10019 } else if (!isatty(STDIN_FILENO))
10020 errx(1, "standard input is not a tty");
10022 #if !defined(PROFILE)
10023 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
10024 NULL) == -1)
10025 err(1, "pledge");
10026 #endif
10028 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
10029 switch (ch) {
10030 case 'h':
10031 hflag = 1;
10032 break;
10033 case 'V':
10034 Vflag = 1;
10035 break;
10036 default:
10037 usage(hflag, 1);
10038 /* NOTREACHED */
10042 argc -= optind;
10043 argv += optind;
10044 optind = 1;
10045 optreset = 1;
10047 if (Vflag) {
10048 got_version_print_str();
10049 return 0;
10052 if (argc == 0) {
10053 if (hflag)
10054 usage(hflag, 0);
10055 /* Build an argument vector which runs a default command. */
10056 cmd = &tog_commands[0];
10057 argc = 1;
10058 cmd_argv = make_argv(argc, cmd->name);
10059 } else {
10060 size_t i;
10062 /* Did the user specify a command? */
10063 for (i = 0; i < nitems(tog_commands); i++) {
10064 if (strncmp(tog_commands[i].name, argv[0],
10065 strlen(argv[0])) == 0) {
10066 cmd = &tog_commands[i];
10067 break;
10072 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
10073 if (diff_algo_str) {
10074 if (strcasecmp(diff_algo_str, "patience") == 0)
10075 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
10076 if (strcasecmp(diff_algo_str, "myers") == 0)
10077 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
10080 if (cmd == NULL) {
10081 if (argc != 1)
10082 usage(0, 1);
10083 /* No command specified; try log with a path */
10084 error = tog_log_with_path(argc, argv);
10085 } else {
10086 if (hflag)
10087 cmd->cmd_usage();
10088 else
10089 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
10092 if (using_mock_io) {
10093 io_err = tog_io_close();
10094 if (error == NULL)
10095 error = io_err;
10097 endwin();
10098 if (cmd_argv) {
10099 int i;
10100 for (i = 0; i < argc; i++)
10101 free(cmd_argv[i]);
10102 free(cmd_argv);
10105 if (error && error->code != GOT_ERR_CANCELLED &&
10106 error->code != GOT_ERR_EOF &&
10107 error->code != GOT_ERR_PRIVSEP_EXIT &&
10108 error->code != GOT_ERR_PRIVSEP_PIPE &&
10109 !(error->code == GOT_ERR_ERRNO && errno == EINTR)) {
10110 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10111 return 1;
10113 return 0;