Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
24 #include <curses.h>
25 #include <panel.h>
26 #include <locale.h>
27 #include <sha1.h>
28 #include <sha2.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #include <string.h>
35 #include <err.h>
36 #include <unistd.h>
37 #include <limits.h>
38 #include <wchar.h>
39 #include <time.h>
40 #include <pthread.h>
41 #include <libgen.h>
42 #include <regex.h>
43 #include <sched.h>
45 #include "got_version.h"
46 #include "got_error.h"
47 #include "got_object.h"
48 #include "got_reference.h"
49 #include "got_repository.h"
50 #include "got_diff.h"
51 #include "got_opentemp.h"
52 #include "got_utf8.h"
53 #include "got_cancel.h"
54 #include "got_commit_graph.h"
55 #include "got_blame.h"
56 #include "got_privsep.h"
57 #include "got_path.h"
58 #include "got_worktree.h"
59 #include "got_keyword.h"
61 #ifndef MIN
62 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
63 #endif
65 #ifndef MAX
66 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
67 #endif
69 #define CTRL(x) ((x) & 0x1f)
71 #ifndef nitems
72 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
73 #endif
75 struct tog_cmd {
76 const char *name;
77 const struct got_error *(*cmd_main)(int, char *[]);
78 void (*cmd_usage)(void);
79 };
81 __dead static void usage(int, int);
82 __dead static void usage_log(void);
83 __dead static void usage_diff(void);
84 __dead static void usage_blame(void);
85 __dead static void usage_tree(void);
86 __dead static void usage_ref(void);
88 static const struct got_error* cmd_log(int, char *[]);
89 static const struct got_error* cmd_diff(int, char *[]);
90 static const struct got_error* cmd_blame(int, char *[]);
91 static const struct got_error* cmd_tree(int, char *[]);
92 static const struct got_error* cmd_ref(int, char *[]);
94 static const struct tog_cmd tog_commands[] = {
95 { "log", cmd_log, usage_log },
96 { "diff", cmd_diff, usage_diff },
97 { "blame", cmd_blame, usage_blame },
98 { "tree", cmd_tree, usage_tree },
99 { "ref", cmd_ref, usage_ref },
100 };
102 enum tog_view_type {
103 TOG_VIEW_DIFF,
104 TOG_VIEW_LOG,
105 TOG_VIEW_BLAME,
106 TOG_VIEW_TREE,
107 TOG_VIEW_REF,
108 TOG_VIEW_HELP
109 };
111 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
112 enum tog_keymap_type {
113 TOG_KEYMAP_KEYS = -2,
114 TOG_KEYMAP_GLOBAL,
115 TOG_KEYMAP_DIFF,
116 TOG_KEYMAP_LOG,
117 TOG_KEYMAP_BLAME,
118 TOG_KEYMAP_TREE,
119 TOG_KEYMAP_REF,
120 TOG_KEYMAP_HELP
121 };
123 enum tog_view_mode {
124 TOG_VIEW_SPLIT_NONE,
125 TOG_VIEW_SPLIT_VERT,
126 TOG_VIEW_SPLIT_HRZN
127 };
129 #define HSPLIT_SCALE 0.3f /* default horizontal split scale */
131 #define TOG_EOF_STRING "(END)"
133 struct commit_queue_entry {
134 TAILQ_ENTRY(commit_queue_entry) entry;
135 struct got_object_id *id;
136 struct got_commit_object *commit;
137 int idx;
138 };
139 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
140 struct commit_queue {
141 int ncommits;
142 struct commit_queue_head head;
143 };
145 struct tog_color {
146 STAILQ_ENTRY(tog_color) entry;
147 regex_t regex;
148 short colorpair;
149 };
150 STAILQ_HEAD(tog_colors, tog_color);
152 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
153 static struct got_reflist_object_id_map *tog_refs_idmap;
154 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
156 static const struct got_error *
157 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
158 struct got_reference* re2)
160 const char *name1 = got_ref_get_name(re1);
161 const char *name2 = got_ref_get_name(re2);
162 int isbackup1, isbackup2;
164 /* Sort backup refs towards the bottom of the list. */
165 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
166 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
167 if (!isbackup1 && isbackup2) {
168 *cmp = -1;
169 return NULL;
170 } else if (isbackup1 && !isbackup2) {
171 *cmp = 1;
172 return NULL;
175 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
176 return NULL;
179 static const struct got_error *
180 tog_load_refs(struct got_repository *repo, int sort_by_date)
182 const struct got_error *err;
184 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
185 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
186 repo);
187 if (err)
188 return err;
190 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
191 repo);
194 static void
195 tog_free_refs(void)
197 if (tog_refs_idmap) {
198 got_reflist_object_id_map_free(tog_refs_idmap);
199 tog_refs_idmap = NULL;
201 got_ref_list_free(&tog_refs);
204 static const struct got_error *
205 add_color(struct tog_colors *colors, const char *pattern,
206 int idx, short color)
208 const struct got_error *err = NULL;
209 struct tog_color *tc;
210 int regerr = 0;
212 if (idx < 1 || idx > COLOR_PAIRS - 1)
213 return NULL;
215 init_pair(idx, color, -1);
217 tc = calloc(1, sizeof(*tc));
218 if (tc == NULL)
219 return got_error_from_errno("calloc");
220 regerr = regcomp(&tc->regex, pattern,
221 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
222 if (regerr) {
223 static char regerr_msg[512];
224 static char err_msg[512];
225 regerror(regerr, &tc->regex, regerr_msg,
226 sizeof(regerr_msg));
227 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
228 regerr_msg);
229 err = got_error_msg(GOT_ERR_REGEX, err_msg);
230 free(tc);
231 return err;
233 tc->colorpair = idx;
234 STAILQ_INSERT_HEAD(colors, tc, entry);
235 return NULL;
238 static void
239 free_colors(struct tog_colors *colors)
241 struct tog_color *tc;
243 while (!STAILQ_EMPTY(colors)) {
244 tc = STAILQ_FIRST(colors);
245 STAILQ_REMOVE_HEAD(colors, entry);
246 regfree(&tc->regex);
247 free(tc);
251 static struct tog_color *
252 get_color(struct tog_colors *colors, int colorpair)
254 struct tog_color *tc = NULL;
256 STAILQ_FOREACH(tc, colors, entry) {
257 if (tc->colorpair == colorpair)
258 return tc;
261 return NULL;
264 static int
265 default_color_value(const char *envvar)
267 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
268 return COLOR_MAGENTA;
269 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
270 return COLOR_CYAN;
271 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
272 return COLOR_YELLOW;
273 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
274 return COLOR_GREEN;
275 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
276 return COLOR_MAGENTA;
277 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
278 return COLOR_MAGENTA;
279 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
280 return COLOR_CYAN;
281 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
282 return COLOR_GREEN;
283 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
284 return COLOR_GREEN;
285 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
286 return COLOR_CYAN;
287 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
288 return COLOR_YELLOW;
289 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
290 return COLOR_GREEN;
291 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
292 return COLOR_MAGENTA;
293 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
294 return COLOR_YELLOW;
295 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
296 return COLOR_CYAN;
298 return -1;
301 static int
302 get_color_value(const char *envvar)
304 const char *val = getenv(envvar);
306 if (val == NULL)
307 return default_color_value(envvar);
309 if (strcasecmp(val, "black") == 0)
310 return COLOR_BLACK;
311 if (strcasecmp(val, "red") == 0)
312 return COLOR_RED;
313 if (strcasecmp(val, "green") == 0)
314 return COLOR_GREEN;
315 if (strcasecmp(val, "yellow") == 0)
316 return COLOR_YELLOW;
317 if (strcasecmp(val, "blue") == 0)
318 return COLOR_BLUE;
319 if (strcasecmp(val, "magenta") == 0)
320 return COLOR_MAGENTA;
321 if (strcasecmp(val, "cyan") == 0)
322 return COLOR_CYAN;
323 if (strcasecmp(val, "white") == 0)
324 return COLOR_WHITE;
325 if (strcasecmp(val, "default") == 0)
326 return -1;
328 return default_color_value(envvar);
331 struct tog_diff_view_state {
332 struct got_object_id *id1, *id2;
333 const char *label1, *label2;
334 FILE *f, *f1, *f2;
335 int fd1, fd2;
336 int lineno;
337 int first_displayed_line;
338 int last_displayed_line;
339 int eof;
340 int diff_context;
341 int ignore_whitespace;
342 int force_text_diff;
343 struct got_repository *repo;
344 struct got_diff_line *lines;
345 size_t nlines;
346 int matched_line;
347 int selected_line;
349 /* passed from log or blame view; may be NULL */
350 struct tog_view *parent_view;
351 };
353 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
354 static volatile sig_atomic_t tog_thread_error;
356 struct tog_log_thread_args {
357 pthread_cond_t need_commits;
358 pthread_cond_t commit_loaded;
359 int commits_needed;
360 int load_all;
361 struct got_commit_graph *graph;
362 struct commit_queue *real_commits;
363 const char *in_repo_path;
364 struct got_object_id *start_id;
365 struct got_repository *repo;
366 int *pack_fds;
367 int log_complete;
368 sig_atomic_t *quit;
369 struct commit_queue_entry **first_displayed_entry;
370 struct commit_queue_entry **selected_entry;
371 int *searching;
372 int *search_next_done;
373 regex_t *regex;
374 int *limiting;
375 int limit_match;
376 regex_t *limit_regex;
377 struct commit_queue *limit_commits;
378 };
380 struct tog_log_view_state {
381 struct commit_queue *commits;
382 struct commit_queue_entry *first_displayed_entry;
383 struct commit_queue_entry *last_displayed_entry;
384 struct commit_queue_entry *selected_entry;
385 struct commit_queue real_commits;
386 int selected;
387 char *in_repo_path;
388 char *head_ref_name;
389 int log_branches;
390 struct got_repository *repo;
391 struct got_object_id *start_id;
392 sig_atomic_t quit;
393 pthread_t thread;
394 struct tog_log_thread_args thread_args;
395 struct commit_queue_entry *matched_entry;
396 struct commit_queue_entry *search_entry;
397 struct tog_colors colors;
398 int use_committer;
399 int limit_view;
400 regex_t limit_regex;
401 struct commit_queue limit_commits;
402 };
404 #define TOG_COLOR_DIFF_MINUS 1
405 #define TOG_COLOR_DIFF_PLUS 2
406 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
407 #define TOG_COLOR_DIFF_META 4
408 #define TOG_COLOR_TREE_SUBMODULE 5
409 #define TOG_COLOR_TREE_SYMLINK 6
410 #define TOG_COLOR_TREE_DIRECTORY 7
411 #define TOG_COLOR_TREE_EXECUTABLE 8
412 #define TOG_COLOR_COMMIT 9
413 #define TOG_COLOR_AUTHOR 10
414 #define TOG_COLOR_DATE 11
415 #define TOG_COLOR_REFS_HEADS 12
416 #define TOG_COLOR_REFS_TAGS 13
417 #define TOG_COLOR_REFS_REMOTES 14
418 #define TOG_COLOR_REFS_BACKUP 15
420 struct tog_blame_cb_args {
421 struct tog_blame_line *lines; /* one per line */
422 int nlines;
424 struct tog_view *view;
425 struct got_object_id *commit_id;
426 int *quit;
427 };
429 struct tog_blame_thread_args {
430 const char *path;
431 struct got_repository *repo;
432 struct tog_blame_cb_args *cb_args;
433 int *complete;
434 got_cancel_cb cancel_cb;
435 void *cancel_arg;
436 pthread_cond_t blame_complete;
437 };
439 struct tog_blame {
440 FILE *f;
441 off_t filesize;
442 struct tog_blame_line *lines;
443 int nlines;
444 off_t *line_offsets;
445 pthread_t thread;
446 struct tog_blame_thread_args thread_args;
447 struct tog_blame_cb_args cb_args;
448 const char *path;
449 int *pack_fds;
450 };
452 struct tog_blame_view_state {
453 int first_displayed_line;
454 int last_displayed_line;
455 int selected_line;
456 int last_diffed_line;
457 int blame_complete;
458 int eof;
459 int done;
460 struct got_object_id_queue blamed_commits;
461 struct got_object_qid *blamed_commit;
462 char *path;
463 struct got_repository *repo;
464 struct got_object_id *commit_id;
465 struct got_object_id *id_to_log;
466 struct tog_blame blame;
467 int matched_line;
468 struct tog_colors colors;
469 };
471 struct tog_parent_tree {
472 TAILQ_ENTRY(tog_parent_tree) entry;
473 struct got_tree_object *tree;
474 struct got_tree_entry *first_displayed_entry;
475 struct got_tree_entry *selected_entry;
476 int selected;
477 };
479 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
481 struct tog_tree_view_state {
482 char *tree_label;
483 struct got_object_id *commit_id;/* commit which this tree belongs to */
484 struct got_tree_object *root; /* the commit's root tree entry */
485 struct got_tree_object *tree; /* currently displayed (sub-)tree */
486 struct got_tree_entry *first_displayed_entry;
487 struct got_tree_entry *last_displayed_entry;
488 struct got_tree_entry *selected_entry;
489 int ndisplayed, selected, show_ids;
490 struct tog_parent_trees parents; /* parent trees of current sub-tree */
491 char *head_ref_name;
492 struct got_repository *repo;
493 struct got_tree_entry *matched_entry;
494 struct tog_colors colors;
495 };
497 struct tog_reflist_entry {
498 TAILQ_ENTRY(tog_reflist_entry) entry;
499 struct got_reference *ref;
500 int idx;
501 };
503 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
505 struct tog_ref_view_state {
506 struct tog_reflist_head refs;
507 struct tog_reflist_entry *first_displayed_entry;
508 struct tog_reflist_entry *last_displayed_entry;
509 struct tog_reflist_entry *selected_entry;
510 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
511 struct got_repository *repo;
512 struct tog_reflist_entry *matched_entry;
513 struct tog_colors colors;
514 };
516 struct tog_help_view_state {
517 FILE *f;
518 off_t *line_offsets;
519 size_t nlines;
520 int lineno;
521 int first_displayed_line;
522 int last_displayed_line;
523 int eof;
524 int matched_line;
525 int selected_line;
526 int all;
527 enum tog_keymap_type type;
528 };
530 #define GENERATE_HELP \
531 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
532 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
533 KEY_("k C-p Up", "Move cursor or page up one line"), \
534 KEY_("j C-n Down", "Move cursor or page down one line"), \
535 KEY_("C-b b PgUp", "Scroll the view up one page"), \
536 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
537 KEY_("C-u u", "Scroll the view up one half page"), \
538 KEY_("C-d d", "Scroll the view down one half page"), \
539 KEY_("g", "Go to line N (default: first line)"), \
540 KEY_("Home =", "Go to the first line"), \
541 KEY_("G", "Go to line N (default: last line)"), \
542 KEY_("End *", "Go to the last line"), \
543 KEY_("l Right", "Scroll the view right"), \
544 KEY_("h Left", "Scroll the view left"), \
545 KEY_("$", "Scroll view to the rightmost position"), \
546 KEY_("0", "Scroll view to the leftmost position"), \
547 KEY_("-", "Decrease size of the focussed split"), \
548 KEY_("+", "Increase size of the focussed split"), \
549 KEY_("Tab", "Switch focus between views"), \
550 KEY_("F", "Toggle fullscreen mode"), \
551 KEY_("S", "Switch split-screen layout"), \
552 KEY_("/", "Open prompt to enter search term"), \
553 KEY_("n", "Find next line/token matching the current search term"), \
554 KEY_("N", "Find previous line/token matching the current search term"),\
555 KEY_("q", "Quit the focussed view; Quit help screen"), \
556 KEY_("Q", "Quit tog"), \
558 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
559 KEY_("< ,", "Move cursor up one commit"), \
560 KEY_("> .", "Move cursor down one commit"), \
561 KEY_("Enter", "Open diff view of the selected commit"), \
562 KEY_("B", "Reload the log view and toggle display of merged commits"), \
563 KEY_("R", "Open ref view of all repository references"), \
564 KEY_("T", "Display tree view of the repository from the selected" \
565 " commit"), \
566 KEY_("@", "Toggle between displaying author and committer name"), \
567 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
568 KEY_("C-g Backspace", "Cancel current search or log operation"), \
569 KEY_("C-l", "Reload the log view with new commits in the repository"), \
571 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
572 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
573 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
574 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
575 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
576 " data"), \
577 KEY_("(", "Go to the previous file in the diff"), \
578 KEY_(")", "Go to the next file in the diff"), \
579 KEY_("{", "Go to the previous hunk in the diff"), \
580 KEY_("}", "Go to the next hunk in the diff"), \
581 KEY_("[", "Decrease the number of context lines"), \
582 KEY_("]", "Increase the number of context lines"), \
583 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
585 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
586 KEY_("Enter", "Display diff view of the selected line's commit"), \
587 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
588 KEY_("L", "Open log view for the currently selected annotated line"), \
589 KEY_("C", "Reload view with the previously blamed commit"), \
590 KEY_("c", "Reload view with the version of the file found in the" \
591 " selected line's commit"), \
592 KEY_("p", "Reload view with the version of the file found in the" \
593 " selected line's parent commit"), \
595 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
596 KEY_("Enter", "Enter selected directory or open blame view of the" \
597 " selected file"), \
598 KEY_("L", "Open log view for the selected entry"), \
599 KEY_("R", "Open ref view of all repository references"), \
600 KEY_("i", "Show object IDs for all tree entries"), \
601 KEY_("Backspace", "Return to the parent directory"), \
603 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
604 KEY_("Enter", "Display log view of the selected reference"), \
605 KEY_("T", "Display tree view of the selected reference"), \
606 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
607 KEY_("m", "Toggle display of last modified date for each reference"), \
608 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
609 KEY_("C-l", "Reload view with all repository references")
611 struct tog_key_map {
612 const char *keys;
613 const char *info;
614 enum tog_keymap_type type;
615 };
617 /* curses io for tog regress */
618 struct tog_io {
619 FILE *cin;
620 FILE *cout;
621 FILE *f;
622 FILE *sdump;
623 int wait_for_ui;
624 } tog_io;
625 static int using_mock_io;
627 #define TOG_KEY_SCRDUMP SHRT_MIN
629 /*
630 * We implement two types of views: parent views and child views.
632 * The 'Tab' key switches focus between a parent view and its child view.
633 * Child views are shown side-by-side to their parent view, provided
634 * there is enough screen estate.
636 * When a new view is opened from within a parent view, this new view
637 * becomes a child view of the parent view, replacing any existing child.
639 * When a new view is opened from within a child view, this new view
640 * becomes a parent view which will obscure the views below until the
641 * user quits the new parent view by typing 'q'.
643 * This list of views contains parent views only.
644 * Child views are only pointed to by their parent view.
645 */
646 TAILQ_HEAD(tog_view_list_head, tog_view);
648 struct tog_view {
649 TAILQ_ENTRY(tog_view) entry;
650 WINDOW *window;
651 PANEL *panel;
652 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
653 int resized_y, resized_x; /* begin_y/x based on user resizing */
654 int maxx, x; /* max column and current start column */
655 int lines, cols; /* copies of LINES and COLS */
656 int nscrolled, offset; /* lines scrolled and hsplit line offset */
657 int gline, hiline; /* navigate to and highlight this nG line */
658 int ch, count; /* current keymap and count prefix */
659 int resized; /* set when in a resize event */
660 int focussed; /* Only set on one parent or child view at a time. */
661 int dying;
662 struct tog_view *parent;
663 struct tog_view *child;
665 /*
666 * This flag is initially set on parent views when a new child view
667 * is created. It gets toggled when the 'Tab' key switches focus
668 * between parent and child.
669 * The flag indicates whether focus should be passed on to our child
670 * view if this parent view gets picked for focus after another parent
671 * view was closed. This prevents child views from losing focus in such
672 * situations.
673 */
674 int focus_child;
676 enum tog_view_mode mode;
677 /* type-specific state */
678 enum tog_view_type type;
679 union {
680 struct tog_diff_view_state diff;
681 struct tog_log_view_state log;
682 struct tog_blame_view_state blame;
683 struct tog_tree_view_state tree;
684 struct tog_ref_view_state ref;
685 struct tog_help_view_state help;
686 } state;
688 const struct got_error *(*show)(struct tog_view *);
689 const struct got_error *(*input)(struct tog_view **,
690 struct tog_view *, int);
691 const struct got_error *(*reset)(struct tog_view *);
692 const struct got_error *(*resize)(struct tog_view *, int);
693 const struct got_error *(*close)(struct tog_view *);
695 const struct got_error *(*search_start)(struct tog_view *);
696 const struct got_error *(*search_next)(struct tog_view *);
697 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
698 int **, int **, int **, int **);
699 int search_started;
700 int searching;
701 #define TOG_SEARCH_FORWARD 1
702 #define TOG_SEARCH_BACKWARD 2
703 int search_next_done;
704 #define TOG_SEARCH_HAVE_MORE 1
705 #define TOG_SEARCH_NO_MORE 2
706 #define TOG_SEARCH_HAVE_NONE 3
707 regex_t regex;
708 regmatch_t regmatch;
709 const char *action;
710 };
712 static const struct got_error *open_diff_view(struct tog_view *,
713 struct got_object_id *, struct got_object_id *,
714 const char *, const char *, int, int, int, struct tog_view *,
715 struct got_repository *);
716 static const struct got_error *show_diff_view(struct tog_view *);
717 static const struct got_error *input_diff_view(struct tog_view **,
718 struct tog_view *, int);
719 static const struct got_error *reset_diff_view(struct tog_view *);
720 static const struct got_error* close_diff_view(struct tog_view *);
721 static const struct got_error *search_start_diff_view(struct tog_view *);
722 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
723 size_t *, int **, int **, int **, int **);
724 static const struct got_error *search_next_view_match(struct tog_view *);
726 static const struct got_error *open_log_view(struct tog_view *,
727 struct got_object_id *, struct got_repository *,
728 const char *, const char *, int);
729 static const struct got_error * show_log_view(struct tog_view *);
730 static const struct got_error *input_log_view(struct tog_view **,
731 struct tog_view *, int);
732 static const struct got_error *resize_log_view(struct tog_view *, int);
733 static const struct got_error *close_log_view(struct tog_view *);
734 static const struct got_error *search_start_log_view(struct tog_view *);
735 static const struct got_error *search_next_log_view(struct tog_view *);
737 static const struct got_error *open_blame_view(struct tog_view *, char *,
738 struct got_object_id *, struct got_repository *);
739 static const struct got_error *show_blame_view(struct tog_view *);
740 static const struct got_error *input_blame_view(struct tog_view **,
741 struct tog_view *, int);
742 static const struct got_error *reset_blame_view(struct tog_view *);
743 static const struct got_error *close_blame_view(struct tog_view *);
744 static const struct got_error *search_start_blame_view(struct tog_view *);
745 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
746 size_t *, int **, int **, int **, int **);
748 static const struct got_error *open_tree_view(struct tog_view *,
749 struct got_object_id *, const char *, struct got_repository *);
750 static const struct got_error *show_tree_view(struct tog_view *);
751 static const struct got_error *input_tree_view(struct tog_view **,
752 struct tog_view *, int);
753 static const struct got_error *close_tree_view(struct tog_view *);
754 static const struct got_error *search_start_tree_view(struct tog_view *);
755 static const struct got_error *search_next_tree_view(struct tog_view *);
757 static const struct got_error *open_ref_view(struct tog_view *,
758 struct got_repository *);
759 static const struct got_error *show_ref_view(struct tog_view *);
760 static const struct got_error *input_ref_view(struct tog_view **,
761 struct tog_view *, int);
762 static const struct got_error *close_ref_view(struct tog_view *);
763 static const struct got_error *search_start_ref_view(struct tog_view *);
764 static const struct got_error *search_next_ref_view(struct tog_view *);
766 static const struct got_error *open_help_view(struct tog_view *,
767 struct tog_view *);
768 static const struct got_error *show_help_view(struct tog_view *);
769 static const struct got_error *input_help_view(struct tog_view **,
770 struct tog_view *, int);
771 static const struct got_error *reset_help_view(struct tog_view *);
772 static const struct got_error* close_help_view(struct tog_view *);
773 static const struct got_error *search_start_help_view(struct tog_view *);
774 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
775 size_t *, int **, int **, int **, int **);
777 static volatile sig_atomic_t tog_sigwinch_received;
778 static volatile sig_atomic_t tog_sigpipe_received;
779 static volatile sig_atomic_t tog_sigcont_received;
780 static volatile sig_atomic_t tog_sigint_received;
781 static volatile sig_atomic_t tog_sigterm_received;
783 static void
784 tog_sigwinch(int signo)
786 tog_sigwinch_received = 1;
789 static void
790 tog_sigpipe(int signo)
792 tog_sigpipe_received = 1;
795 static void
796 tog_sigcont(int signo)
798 tog_sigcont_received = 1;
801 static void
802 tog_sigint(int signo)
804 tog_sigint_received = 1;
807 static void
808 tog_sigterm(int signo)
810 tog_sigterm_received = 1;
813 static int
814 tog_fatal_signal_received(void)
816 return (tog_sigpipe_received ||
817 tog_sigint_received || tog_sigterm_received);
820 static const struct got_error *
821 view_close(struct tog_view *view)
823 const struct got_error *err = NULL, *child_err = NULL;
825 if (view->child) {
826 child_err = view_close(view->child);
827 view->child = NULL;
829 if (view->close)
830 err = view->close(view);
831 if (view->panel)
832 del_panel(view->panel);
833 if (view->window)
834 delwin(view->window);
835 free(view);
836 return err ? err : child_err;
839 static struct tog_view *
840 view_open(int nlines, int ncols, int begin_y, int begin_x,
841 enum tog_view_type type)
843 struct tog_view *view = calloc(1, sizeof(*view));
845 if (view == NULL)
846 return NULL;
848 view->type = type;
849 view->lines = LINES;
850 view->cols = COLS;
851 view->nlines = nlines ? nlines : LINES - begin_y;
852 view->ncols = ncols ? ncols : COLS - begin_x;
853 view->begin_y = begin_y;
854 view->begin_x = begin_x;
855 view->window = newwin(nlines, ncols, begin_y, begin_x);
856 if (view->window == NULL) {
857 view_close(view);
858 return NULL;
860 view->panel = new_panel(view->window);
861 if (view->panel == NULL ||
862 set_panel_userptr(view->panel, view) != OK) {
863 view_close(view);
864 return NULL;
867 keypad(view->window, TRUE);
868 return view;
871 static int
872 view_split_begin_x(int begin_x)
874 if (begin_x > 0 || COLS < 120)
875 return 0;
876 return (COLS - MAX(COLS / 2, 80));
879 /* XXX Stub till we decide what to do. */
880 static int
881 view_split_begin_y(int lines)
883 return lines * HSPLIT_SCALE;
886 static const struct got_error *view_resize(struct tog_view *);
888 static const struct got_error *
889 view_splitscreen(struct tog_view *view)
891 const struct got_error *err = NULL;
893 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
894 if (view->resized_y && view->resized_y < view->lines)
895 view->begin_y = view->resized_y;
896 else
897 view->begin_y = view_split_begin_y(view->nlines);
898 view->begin_x = 0;
899 } else if (!view->resized) {
900 if (view->resized_x && view->resized_x < view->cols - 1 &&
901 view->cols > 119)
902 view->begin_x = view->resized_x;
903 else
904 view->begin_x = view_split_begin_x(0);
905 view->begin_y = 0;
907 view->nlines = LINES - view->begin_y;
908 view->ncols = COLS - view->begin_x;
909 view->lines = LINES;
910 view->cols = COLS;
911 err = view_resize(view);
912 if (err)
913 return err;
915 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
916 view->parent->nlines = view->begin_y;
918 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
919 return got_error_from_errno("mvwin");
921 return NULL;
924 static const struct got_error *
925 view_fullscreen(struct tog_view *view)
927 const struct got_error *err = NULL;
929 view->begin_x = 0;
930 view->begin_y = view->resized ? view->begin_y : 0;
931 view->nlines = view->resized ? view->nlines : LINES;
932 view->ncols = COLS;
933 view->lines = LINES;
934 view->cols = COLS;
935 err = view_resize(view);
936 if (err)
937 return err;
939 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
940 return got_error_from_errno("mvwin");
942 return NULL;
945 static int
946 view_is_parent_view(struct tog_view *view)
948 return view->parent == NULL;
951 static int
952 view_is_splitscreen(struct tog_view *view)
954 return view->begin_x > 0 || view->begin_y > 0;
957 static int
958 view_is_fullscreen(struct tog_view *view)
960 return view->nlines == LINES && view->ncols == COLS;
963 static int
964 view_is_hsplit_top(struct tog_view *view)
966 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
967 view_is_splitscreen(view->child);
970 static void
971 view_border(struct tog_view *view)
973 PANEL *panel;
974 const struct tog_view *view_above;
976 if (view->parent)
977 return view_border(view->parent);
979 panel = panel_above(view->panel);
980 if (panel == NULL)
981 return;
983 view_above = panel_userptr(panel);
984 if (view->mode == TOG_VIEW_SPLIT_HRZN)
985 mvwhline(view->window, view_above->begin_y - 1,
986 view->begin_x, ACS_HLINE, view->ncols);
987 else
988 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
989 ACS_VLINE, view->nlines);
992 static const struct got_error *view_init_hsplit(struct tog_view *, int);
993 static const struct got_error *request_log_commits(struct tog_view *);
994 static const struct got_error *offset_selection_down(struct tog_view *);
995 static void offset_selection_up(struct tog_view *);
996 static void view_get_split(struct tog_view *, int *, int *);
998 static const struct got_error *
999 view_resize(struct tog_view *view)
1001 const struct got_error *err = NULL;
1002 int dif, nlines, ncols;
1004 dif = LINES - view->lines; /* line difference */
1006 if (view->lines > LINES)
1007 nlines = view->nlines - (view->lines - LINES);
1008 else
1009 nlines = view->nlines + (LINES - view->lines);
1010 if (view->cols > COLS)
1011 ncols = view->ncols - (view->cols - COLS);
1012 else
1013 ncols = view->ncols + (COLS - view->cols);
1015 if (view->child) {
1016 int hs = view->child->begin_y;
1018 if (!view_is_fullscreen(view))
1019 view->child->begin_x = view_split_begin_x(view->begin_x);
1020 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1021 view->child->begin_x == 0) {
1022 ncols = COLS;
1024 view_fullscreen(view->child);
1025 if (view->child->focussed)
1026 show_panel(view->child->panel);
1027 else
1028 show_panel(view->panel);
1029 } else {
1030 ncols = view->child->begin_x;
1032 view_splitscreen(view->child);
1033 show_panel(view->child->panel);
1036 * XXX This is ugly and needs to be moved into the above
1037 * logic but "works" for now and my attempts at moving it
1038 * break either 'tab' or 'F' key maps in horizontal splits.
1040 if (hs) {
1041 err = view_splitscreen(view->child);
1042 if (err)
1043 return err;
1044 if (dif < 0) { /* top split decreased */
1045 err = offset_selection_down(view);
1046 if (err)
1047 return err;
1049 view_border(view);
1050 update_panels();
1051 doupdate();
1052 show_panel(view->child->panel);
1053 nlines = view->nlines;
1055 } else if (view->parent == NULL)
1056 ncols = COLS;
1058 if (view->resize && dif > 0) {
1059 err = view->resize(view, dif);
1060 if (err)
1061 return err;
1064 if (wresize(view->window, nlines, ncols) == ERR)
1065 return got_error_from_errno("wresize");
1066 if (replace_panel(view->panel, view->window) == ERR)
1067 return got_error_from_errno("replace_panel");
1068 wclear(view->window);
1070 view->nlines = nlines;
1071 view->ncols = ncols;
1072 view->lines = LINES;
1073 view->cols = COLS;
1075 return NULL;
1078 static const struct got_error *
1079 resize_log_view(struct tog_view *view, int increase)
1081 struct tog_log_view_state *s = &view->state.log;
1082 const struct got_error *err = NULL;
1083 int n = 0;
1085 if (s->selected_entry)
1086 n = s->selected_entry->idx + view->lines - s->selected;
1089 * Request commits to account for the increased
1090 * height so we have enough to populate the view.
1092 if (s->commits->ncommits < n) {
1093 view->nscrolled = n - s->commits->ncommits + increase + 1;
1094 err = request_log_commits(view);
1097 return err;
1100 static void
1101 view_adjust_offset(struct tog_view *view, int n)
1103 if (n == 0)
1104 return;
1106 if (view->parent && view->parent->offset) {
1107 if (view->parent->offset + n >= 0)
1108 view->parent->offset += n;
1109 else
1110 view->parent->offset = 0;
1111 } else if (view->offset) {
1112 if (view->offset - n >= 0)
1113 view->offset -= n;
1114 else
1115 view->offset = 0;
1119 static const struct got_error *
1120 view_resize_split(struct tog_view *view, int resize)
1122 const struct got_error *err = NULL;
1123 struct tog_view *v = NULL;
1125 if (view->parent)
1126 v = view->parent;
1127 else
1128 v = view;
1130 if (!v->child || !view_is_splitscreen(v->child))
1131 return NULL;
1133 v->resized = v->child->resized = resize; /* lock for resize event */
1135 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1136 if (v->child->resized_y)
1137 v->child->begin_y = v->child->resized_y;
1138 if (view->parent)
1139 v->child->begin_y -= resize;
1140 else
1141 v->child->begin_y += resize;
1142 if (v->child->begin_y < 3) {
1143 view->count = 0;
1144 v->child->begin_y = 3;
1145 } else if (v->child->begin_y > LINES - 1) {
1146 view->count = 0;
1147 v->child->begin_y = LINES - 1;
1149 v->ncols = COLS;
1150 v->child->ncols = COLS;
1151 view_adjust_offset(view, resize);
1152 err = view_init_hsplit(v, v->child->begin_y);
1153 if (err)
1154 return err;
1155 v->child->resized_y = v->child->begin_y;
1156 } else {
1157 if (v->child->resized_x)
1158 v->child->begin_x = v->child->resized_x;
1159 if (view->parent)
1160 v->child->begin_x -= resize;
1161 else
1162 v->child->begin_x += resize;
1163 if (v->child->begin_x < 11) {
1164 view->count = 0;
1165 v->child->begin_x = 11;
1166 } else if (v->child->begin_x > COLS - 1) {
1167 view->count = 0;
1168 v->child->begin_x = COLS - 1;
1170 v->child->resized_x = v->child->begin_x;
1173 v->child->mode = v->mode;
1174 v->child->nlines = v->lines - v->child->begin_y;
1175 v->child->ncols = v->cols - v->child->begin_x;
1176 v->focus_child = 1;
1178 err = view_fullscreen(v);
1179 if (err)
1180 return err;
1181 err = view_splitscreen(v->child);
1182 if (err)
1183 return err;
1185 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1186 err = offset_selection_down(v->child);
1187 if (err)
1188 return err;
1191 if (v->resize)
1192 err = v->resize(v, 0);
1193 else if (v->child->resize)
1194 err = v->child->resize(v->child, 0);
1196 v->resized = v->child->resized = 0;
1198 return err;
1201 static void
1202 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1204 struct tog_view *v = src->child ? src->child : src;
1206 dst->resized_x = v->resized_x;
1207 dst->resized_y = v->resized_y;
1210 static const struct got_error *
1211 view_close_child(struct tog_view *view)
1213 const struct got_error *err = NULL;
1215 if (view->child == NULL)
1216 return NULL;
1218 err = view_close(view->child);
1219 view->child = NULL;
1220 return err;
1223 static const struct got_error *
1224 view_set_child(struct tog_view *view, struct tog_view *child)
1226 const struct got_error *err = NULL;
1228 view->child = child;
1229 child->parent = view;
1231 err = view_resize(view);
1232 if (err)
1233 return err;
1235 if (view->child->resized_x || view->child->resized_y)
1236 err = view_resize_split(view, 0);
1238 return err;
1241 static const struct got_error *view_dispatch_request(struct tog_view **,
1242 struct tog_view *, enum tog_view_type, int, int);
1244 static const struct got_error *
1245 view_request_new(struct tog_view **requested, struct tog_view *view,
1246 enum tog_view_type request)
1248 struct tog_view *new_view = NULL;
1249 const struct got_error *err;
1250 int y = 0, x = 0;
1252 *requested = NULL;
1254 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1255 view_get_split(view, &y, &x);
1257 err = view_dispatch_request(&new_view, view, request, y, x);
1258 if (err)
1259 return err;
1261 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1262 request != TOG_VIEW_HELP) {
1263 err = view_init_hsplit(view, y);
1264 if (err)
1265 return err;
1268 view->focussed = 0;
1269 new_view->focussed = 1;
1270 new_view->mode = view->mode;
1271 new_view->nlines = request == TOG_VIEW_HELP ?
1272 view->lines : view->lines - y;
1274 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1275 view_transfer_size(new_view, view);
1276 err = view_close_child(view);
1277 if (err)
1278 return err;
1279 err = view_set_child(view, new_view);
1280 if (err)
1281 return err;
1282 view->focus_child = 1;
1283 } else
1284 *requested = new_view;
1286 return NULL;
1289 static void
1290 tog_resizeterm(void)
1292 int cols, lines;
1293 struct winsize size;
1295 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1296 cols = 80; /* Default */
1297 lines = 24;
1298 } else {
1299 cols = size.ws_col;
1300 lines = size.ws_row;
1302 resize_term(lines, cols);
1305 static const struct got_error *
1306 view_search_start(struct tog_view *view, int fast_refresh)
1308 const struct got_error *err = NULL;
1309 struct tog_view *v = view;
1310 char pattern[1024];
1311 int ret;
1313 if (view->search_started) {
1314 regfree(&view->regex);
1315 view->searching = 0;
1316 memset(&view->regmatch, 0, sizeof(view->regmatch));
1318 view->search_started = 0;
1320 if (view->nlines < 1)
1321 return NULL;
1323 if (view_is_hsplit_top(view))
1324 v = view->child;
1325 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1326 v = view->parent;
1328 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1329 wclrtoeol(v->window);
1331 nodelay(v->window, FALSE); /* block for search term input */
1332 nocbreak();
1333 echo();
1334 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1335 wrefresh(v->window);
1336 cbreak();
1337 noecho();
1338 nodelay(v->window, TRUE);
1339 if (!fast_refresh && !using_mock_io)
1340 halfdelay(10);
1341 if (ret == ERR)
1342 return NULL;
1344 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1345 err = view->search_start(view);
1346 if (err) {
1347 regfree(&view->regex);
1348 return err;
1350 view->search_started = 1;
1351 view->searching = TOG_SEARCH_FORWARD;
1352 view->search_next_done = 0;
1353 view->search_next(view);
1356 return NULL;
1359 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1360 static const struct got_error *
1361 switch_split(struct tog_view *view)
1363 const struct got_error *err = NULL;
1364 struct tog_view *v = NULL;
1366 if (view->parent)
1367 v = view->parent;
1368 else
1369 v = view;
1371 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1372 v->mode = TOG_VIEW_SPLIT_VERT;
1373 else
1374 v->mode = TOG_VIEW_SPLIT_HRZN;
1376 if (!v->child)
1377 return NULL;
1378 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1379 v->mode = TOG_VIEW_SPLIT_NONE;
1381 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1382 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1383 v->child->begin_y = v->child->resized_y;
1384 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1385 v->child->begin_x = v->child->resized_x;
1388 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1389 v->ncols = COLS;
1390 v->child->ncols = COLS;
1391 v->child->nscrolled = LINES - v->child->nlines;
1393 err = view_init_hsplit(v, v->child->begin_y);
1394 if (err)
1395 return err;
1397 v->child->mode = v->mode;
1398 v->child->nlines = v->lines - v->child->begin_y;
1399 v->focus_child = 1;
1401 err = view_fullscreen(v);
1402 if (err)
1403 return err;
1404 err = view_splitscreen(v->child);
1405 if (err)
1406 return err;
1408 if (v->mode == TOG_VIEW_SPLIT_NONE)
1409 v->mode = TOG_VIEW_SPLIT_VERT;
1410 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1411 err = offset_selection_down(v);
1412 if (err)
1413 return err;
1414 err = offset_selection_down(v->child);
1415 if (err)
1416 return err;
1417 } else {
1418 offset_selection_up(v);
1419 offset_selection_up(v->child);
1421 if (v->resize)
1422 err = v->resize(v, 0);
1423 else if (v->child->resize)
1424 err = v->child->resize(v->child, 0);
1426 return err;
1430 * Strip trailing whitespace from str starting at byte *n;
1431 * if *n < 0, use strlen(str). Return new str length in *n.
1433 static void
1434 strip_trailing_ws(char *str, int *n)
1436 size_t x = *n;
1438 if (str == NULL || *str == '\0')
1439 return;
1441 if (x < 0)
1442 x = strlen(str);
1444 while (x-- > 0 && isspace((unsigned char)str[x]))
1445 str[x] = '\0';
1447 *n = x + 1;
1451 * Extract visible substring of line y from the curses screen
1452 * and strip trailing whitespace. If vline is set, overwrite
1453 * line[vline] with '|' because the ACS_VLINE character is
1454 * written out as 'x'. Write the line to file f.
1456 static const struct got_error *
1457 view_write_line(FILE *f, int y, int vline)
1459 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1460 int r, w;
1462 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1463 if (r == ERR)
1464 return got_error_fmt(GOT_ERR_RANGE,
1465 "failed to extract line %d", y);
1468 * In some views, lines are padded with blanks to COLS width.
1469 * Strip them so we can diff without the -b flag when testing.
1471 strip_trailing_ws(line, &r);
1473 if (vline > 0)
1474 line[vline] = '|';
1476 w = fprintf(f, "%s\n", line);
1477 if (w != r + 1) /* \n */
1478 return got_ferror(f, GOT_ERR_IO);
1480 return NULL;
1484 * Capture the visible curses screen by writing each line to the
1485 * file at the path set via the TOG_SCR_DUMP environment variable.
1487 static const struct got_error *
1488 screendump(struct tog_view *view)
1490 const struct got_error *err;
1491 int i;
1493 err = got_opentemp_truncate(tog_io.sdump);
1494 if (err)
1495 return err;
1497 if ((view->child && view->child->begin_x) ||
1498 (view->parent && view->begin_x)) {
1499 int ncols = view->child ? view->ncols : view->parent->ncols;
1501 /* vertical splitscreen */
1502 for (i = 0; i < view->nlines; ++i) {
1503 err = view_write_line(tog_io.sdump, i, ncols - 1);
1504 if (err)
1505 goto done;
1507 } else {
1508 int hline = 0;
1510 /* fullscreen or horizontal splitscreen */
1511 if ((view->child && view->child->begin_y) ||
1512 (view->parent && view->begin_y)) /* hsplit */
1513 hline = view->child ?
1514 view->child->begin_y : view->begin_y;
1516 for (i = 0; i < view->lines; i++) {
1517 if (hline && i == hline - 1) {
1518 int c;
1520 /* ACS_HLINE writes out as 'q', overwrite it */
1521 for (c = 0; c < view->cols; ++c)
1522 fputc('-', tog_io.sdump);
1523 fputc('\n', tog_io.sdump);
1524 continue;
1527 err = view_write_line(tog_io.sdump, i, 0);
1528 if (err)
1529 goto done;
1533 done:
1534 return err;
1538 * Compute view->count from numeric input. Assign total to view->count and
1539 * return first non-numeric key entered.
1541 static int
1542 get_compound_key(struct tog_view *view, int c)
1544 struct tog_view *v = view;
1545 int x, n = 0;
1547 if (view_is_hsplit_top(view))
1548 v = view->child;
1549 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1550 v = view->parent;
1552 view->count = 0;
1553 cbreak(); /* block for input */
1554 nodelay(view->window, FALSE);
1555 wmove(v->window, v->nlines - 1, 0);
1556 wclrtoeol(v->window);
1557 waddch(v->window, ':');
1559 do {
1560 x = getcurx(v->window);
1561 if (x != ERR && x < view->ncols) {
1562 waddch(v->window, c);
1563 wrefresh(v->window);
1567 * Don't overflow. Max valid request should be the greatest
1568 * between the longest and total lines; cap at 10 million.
1570 if (n >= 9999999)
1571 n = 9999999;
1572 else
1573 n = n * 10 + (c - '0');
1574 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1576 if (c == 'G' || c == 'g') { /* nG key map */
1577 view->gline = view->hiline = n;
1578 n = 0;
1579 c = 0;
1582 /* Massage excessive or inapplicable values at the input handler. */
1583 view->count = n;
1585 return c;
1588 static void
1589 action_report(struct tog_view *view)
1591 struct tog_view *v = view;
1593 if (view_is_hsplit_top(view))
1594 v = view->child;
1595 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1596 v = view->parent;
1598 wmove(v->window, v->nlines - 1, 0);
1599 wclrtoeol(v->window);
1600 wprintw(v->window, ":%s", view->action);
1601 wrefresh(v->window);
1604 * Clear action status report. Only clear in blame view
1605 * once annotating is complete, otherwise it's too fast.
1607 if (view->type == TOG_VIEW_BLAME) {
1608 if (view->state.blame.blame_complete)
1609 view->action = NULL;
1610 } else
1611 view->action = NULL;
1615 * Read the next line from the test script and assign
1616 * key instruction to *ch. If at EOF, set the *done flag.
1618 static const struct got_error *
1619 tog_read_script_key(FILE *script, struct tog_view *view, int *ch, int *done)
1621 const struct got_error *err = NULL;
1622 char *line = NULL;
1623 size_t linesz = 0;
1625 if (view->count && --view->count) {
1626 *ch = view->ch;
1627 return NULL;
1628 } else
1629 *ch = -1;
1631 if (getline(&line, &linesz, script) == -1) {
1632 if (feof(script)) {
1633 *done = 1;
1634 goto done;
1635 } else {
1636 err = got_ferror(script, GOT_ERR_IO);
1637 goto done;
1641 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1642 tog_io.wait_for_ui = 1;
1643 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1644 *ch = KEY_ENTER;
1645 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1646 *ch = KEY_RIGHT;
1647 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1648 *ch = KEY_LEFT;
1649 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1650 *ch = KEY_DOWN;
1651 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1652 *ch = KEY_UP;
1653 else if (strncasecmp(line, "TAB", 3) == 0)
1654 *ch = '\t';
1655 else if (strncasecmp(line, "SCREENDUMP", 10) == 0)
1656 *ch = TOG_KEY_SCRDUMP;
1657 else if (isdigit((unsigned char)*line)) {
1658 char *t = line;
1660 while (isdigit((unsigned char)*t))
1661 ++t;
1662 view->ch = *ch = *t;
1663 *t = '\0';
1664 /* ignore error, view->count is 0 if instruction is invalid */
1665 view->count = strtonum(line, 0, INT_MAX, NULL);
1666 } else
1667 *ch = *line;
1669 done:
1670 free(line);
1671 return err;
1674 static const struct got_error *
1675 view_input(struct tog_view **new, int *done, struct tog_view *view,
1676 struct tog_view_list_head *views, int fast_refresh)
1678 const struct got_error *err = NULL;
1679 struct tog_view *v;
1680 int ch, errcode;
1682 *new = NULL;
1684 if (view->action)
1685 action_report(view);
1687 /* Clear "no matches" indicator. */
1688 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1689 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1690 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1691 view->count = 0;
1694 if (view->searching && !view->search_next_done) {
1695 errcode = pthread_mutex_unlock(&tog_mutex);
1696 if (errcode)
1697 return got_error_set_errno(errcode,
1698 "pthread_mutex_unlock");
1699 sched_yield();
1700 errcode = pthread_mutex_lock(&tog_mutex);
1701 if (errcode)
1702 return got_error_set_errno(errcode,
1703 "pthread_mutex_lock");
1704 view->search_next(view);
1705 return NULL;
1708 /* Allow threads to make progress while we are waiting for input. */
1709 errcode = pthread_mutex_unlock(&tog_mutex);
1710 if (errcode)
1711 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1713 if (using_mock_io) {
1714 err = tog_read_script_key(tog_io.f, view, &ch, done);
1715 if (err) {
1716 errcode = pthread_mutex_lock(&tog_mutex);
1717 return err;
1719 } else if (view->count && --view->count) {
1720 cbreak();
1721 nodelay(view->window, TRUE);
1722 ch = wgetch(view->window);
1723 /* let C-g or backspace abort unfinished count */
1724 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1725 view->count = 0;
1726 else
1727 ch = view->ch;
1728 } else {
1729 ch = wgetch(view->window);
1730 if (ch >= '1' && ch <= '9')
1731 view->ch = ch = get_compound_key(view, ch);
1733 if (view->hiline && ch != ERR && ch != 0)
1734 view->hiline = 0; /* key pressed, clear line highlight */
1735 nodelay(view->window, TRUE);
1736 errcode = pthread_mutex_lock(&tog_mutex);
1737 if (errcode)
1738 return got_error_set_errno(errcode, "pthread_mutex_lock");
1740 if (tog_sigwinch_received || tog_sigcont_received) {
1741 tog_resizeterm();
1742 tog_sigwinch_received = 0;
1743 tog_sigcont_received = 0;
1744 TAILQ_FOREACH(v, views, entry) {
1745 err = view_resize(v);
1746 if (err)
1747 return err;
1748 err = v->input(new, v, KEY_RESIZE);
1749 if (err)
1750 return err;
1751 if (v->child) {
1752 err = view_resize(v->child);
1753 if (err)
1754 return err;
1755 err = v->child->input(new, v->child,
1756 KEY_RESIZE);
1757 if (err)
1758 return err;
1759 if (v->child->resized_x || v->child->resized_y) {
1760 err = view_resize_split(v, 0);
1761 if (err)
1762 return err;
1768 switch (ch) {
1769 case '?':
1770 case 'H':
1771 case KEY_F(1):
1772 if (view->type == TOG_VIEW_HELP)
1773 err = view->reset(view);
1774 else
1775 err = view_request_new(new, view, TOG_VIEW_HELP);
1776 break;
1777 case '\t':
1778 view->count = 0;
1779 if (view->child) {
1780 view->focussed = 0;
1781 view->child->focussed = 1;
1782 view->focus_child = 1;
1783 } else if (view->parent) {
1784 view->focussed = 0;
1785 view->parent->focussed = 1;
1786 view->parent->focus_child = 0;
1787 if (!view_is_splitscreen(view)) {
1788 if (view->parent->resize) {
1789 err = view->parent->resize(view->parent,
1790 0);
1791 if (err)
1792 return err;
1794 offset_selection_up(view->parent);
1795 err = view_fullscreen(view->parent);
1796 if (err)
1797 return err;
1800 break;
1801 case 'q':
1802 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1803 if (view->parent->resize) {
1804 /* might need more commits to fill fullscreen */
1805 err = view->parent->resize(view->parent, 0);
1806 if (err)
1807 break;
1809 offset_selection_up(view->parent);
1811 err = view->input(new, view, ch);
1812 view->dying = 1;
1813 break;
1814 case 'Q':
1815 *done = 1;
1816 break;
1817 case 'F':
1818 view->count = 0;
1819 if (view_is_parent_view(view)) {
1820 if (view->child == NULL)
1821 break;
1822 if (view_is_splitscreen(view->child)) {
1823 view->focussed = 0;
1824 view->child->focussed = 1;
1825 err = view_fullscreen(view->child);
1826 } else {
1827 err = view_splitscreen(view->child);
1828 if (!err)
1829 err = view_resize_split(view, 0);
1831 if (err)
1832 break;
1833 err = view->child->input(new, view->child,
1834 KEY_RESIZE);
1835 } else {
1836 if (view_is_splitscreen(view)) {
1837 view->parent->focussed = 0;
1838 view->focussed = 1;
1839 err = view_fullscreen(view);
1840 } else {
1841 err = view_splitscreen(view);
1842 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1843 err = view_resize(view->parent);
1844 if (!err)
1845 err = view_resize_split(view, 0);
1847 if (err)
1848 break;
1849 err = view->input(new, view, KEY_RESIZE);
1851 if (err)
1852 break;
1853 if (view->resize) {
1854 err = view->resize(view, 0);
1855 if (err)
1856 break;
1858 if (view->parent) {
1859 if (view->parent->resize) {
1860 err = view->parent->resize(view->parent, 0);
1861 if (err != NULL)
1862 break;
1864 err = offset_selection_down(view->parent);
1865 if (err != NULL)
1866 break;
1868 err = offset_selection_down(view);
1869 break;
1870 case 'S':
1871 view->count = 0;
1872 err = switch_split(view);
1873 break;
1874 case '-':
1875 err = view_resize_split(view, -1);
1876 break;
1877 case '+':
1878 err = view_resize_split(view, 1);
1879 break;
1880 case KEY_RESIZE:
1881 break;
1882 case '/':
1883 view->count = 0;
1884 if (view->search_start)
1885 view_search_start(view, fast_refresh);
1886 else
1887 err = view->input(new, view, ch);
1888 break;
1889 case 'N':
1890 case 'n':
1891 if (view->search_started && view->search_next) {
1892 view->searching = (ch == 'n' ?
1893 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1894 view->search_next_done = 0;
1895 view->search_next(view);
1896 } else
1897 err = view->input(new, view, ch);
1898 break;
1899 case 'A':
1900 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1901 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1902 view->action = "Patience diff algorithm";
1903 } else {
1904 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1905 view->action = "Myers diff algorithm";
1907 TAILQ_FOREACH(v, views, entry) {
1908 if (v->reset) {
1909 err = v->reset(v);
1910 if (err)
1911 return err;
1913 if (v->child && v->child->reset) {
1914 err = v->child->reset(v->child);
1915 if (err)
1916 return err;
1919 break;
1920 case TOG_KEY_SCRDUMP:
1921 err = screendump(view);
1922 break;
1923 default:
1924 err = view->input(new, view, ch);
1925 break;
1928 return err;
1931 static int
1932 view_needs_focus_indication(struct tog_view *view)
1934 if (view_is_parent_view(view)) {
1935 if (view->child == NULL || view->child->focussed)
1936 return 0;
1937 if (!view_is_splitscreen(view->child))
1938 return 0;
1939 } else if (!view_is_splitscreen(view))
1940 return 0;
1942 return view->focussed;
1945 static const struct got_error *
1946 tog_io_close(void)
1948 const struct got_error *err = NULL;
1950 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1951 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1952 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1953 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1954 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1955 err = got_ferror(tog_io.f, GOT_ERR_IO);
1956 if (tog_io.sdump && fclose(tog_io.sdump) == EOF && err == NULL)
1957 err = got_ferror(tog_io.sdump, GOT_ERR_IO);
1959 return err;
1962 static const struct got_error *
1963 view_loop(struct tog_view *view)
1965 const struct got_error *err = NULL;
1966 struct tog_view_list_head views;
1967 struct tog_view *new_view;
1968 char *mode;
1969 int fast_refresh = 10;
1970 int done = 0, errcode;
1972 mode = getenv("TOG_VIEW_SPLIT_MODE");
1973 if (!mode || !(*mode == 'h' || *mode == 'H'))
1974 view->mode = TOG_VIEW_SPLIT_VERT;
1975 else
1976 view->mode = TOG_VIEW_SPLIT_HRZN;
1978 errcode = pthread_mutex_lock(&tog_mutex);
1979 if (errcode)
1980 return got_error_set_errno(errcode, "pthread_mutex_lock");
1982 TAILQ_INIT(&views);
1983 TAILQ_INSERT_HEAD(&views, view, entry);
1985 view->focussed = 1;
1986 err = view->show(view);
1987 if (err)
1988 return err;
1989 update_panels();
1990 doupdate();
1991 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1992 !tog_fatal_signal_received()) {
1993 /* Refresh fast during initialization, then become slower. */
1994 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
1995 halfdelay(10); /* switch to once per second */
1997 err = view_input(&new_view, &done, view, &views, fast_refresh);
1998 if (err)
1999 break;
2001 if (view->dying && view == TAILQ_FIRST(&views) &&
2002 TAILQ_NEXT(view, entry) == NULL)
2003 done = 1;
2004 if (done) {
2005 struct tog_view *v;
2008 * When we quit, scroll the screen up a single line
2009 * so we don't lose any information.
2011 TAILQ_FOREACH(v, &views, entry) {
2012 wmove(v->window, 0, 0);
2013 wdeleteln(v->window);
2014 wnoutrefresh(v->window);
2015 if (v->child && !view_is_fullscreen(v)) {
2016 wmove(v->child->window, 0, 0);
2017 wdeleteln(v->child->window);
2018 wnoutrefresh(v->child->window);
2021 doupdate();
2024 if (view->dying) {
2025 struct tog_view *v, *prev = NULL;
2027 if (view_is_parent_view(view))
2028 prev = TAILQ_PREV(view, tog_view_list_head,
2029 entry);
2030 else if (view->parent)
2031 prev = view->parent;
2033 if (view->parent) {
2034 view->parent->child = NULL;
2035 view->parent->focus_child = 0;
2036 /* Restore fullscreen line height. */
2037 view->parent->nlines = view->parent->lines;
2038 err = view_resize(view->parent);
2039 if (err)
2040 break;
2041 /* Make resized splits persist. */
2042 view_transfer_size(view->parent, view);
2043 } else
2044 TAILQ_REMOVE(&views, view, entry);
2046 err = view_close(view);
2047 if (err)
2048 goto done;
2050 view = NULL;
2051 TAILQ_FOREACH(v, &views, entry) {
2052 if (v->focussed)
2053 break;
2055 if (view == NULL && new_view == NULL) {
2056 /* No view has focus. Try to pick one. */
2057 if (prev)
2058 view = prev;
2059 else if (!TAILQ_EMPTY(&views)) {
2060 view = TAILQ_LAST(&views,
2061 tog_view_list_head);
2063 if (view) {
2064 if (view->focus_child) {
2065 view->child->focussed = 1;
2066 view = view->child;
2067 } else
2068 view->focussed = 1;
2072 if (new_view) {
2073 struct tog_view *v, *t;
2074 /* Only allow one parent view per type. */
2075 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2076 if (v->type != new_view->type)
2077 continue;
2078 TAILQ_REMOVE(&views, v, entry);
2079 err = view_close(v);
2080 if (err)
2081 goto done;
2082 break;
2084 TAILQ_INSERT_TAIL(&views, new_view, entry);
2085 view = new_view;
2087 if (view && !done) {
2088 if (view_is_parent_view(view)) {
2089 if (view->child && view->child->focussed)
2090 view = view->child;
2091 } else {
2092 if (view->parent && view->parent->focussed)
2093 view = view->parent;
2095 show_panel(view->panel);
2096 if (view->child && view_is_splitscreen(view->child))
2097 show_panel(view->child->panel);
2098 if (view->parent && view_is_splitscreen(view)) {
2099 err = view->parent->show(view->parent);
2100 if (err)
2101 goto done;
2103 err = view->show(view);
2104 if (err)
2105 goto done;
2106 if (view->child) {
2107 err = view->child->show(view->child);
2108 if (err)
2109 goto done;
2111 update_panels();
2112 doupdate();
2115 done:
2116 while (!TAILQ_EMPTY(&views)) {
2117 const struct got_error *close_err;
2118 view = TAILQ_FIRST(&views);
2119 TAILQ_REMOVE(&views, view, entry);
2120 close_err = view_close(view);
2121 if (close_err && err == NULL)
2122 err = close_err;
2125 errcode = pthread_mutex_unlock(&tog_mutex);
2126 if (errcode && err == NULL)
2127 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2129 return err;
2132 __dead static void
2133 usage_log(void)
2135 endwin();
2136 fprintf(stderr,
2137 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2138 getprogname());
2139 exit(1);
2142 /* Create newly allocated wide-character string equivalent to a byte string. */
2143 static const struct got_error *
2144 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2146 char *vis = NULL;
2147 const struct got_error *err = NULL;
2149 *ws = NULL;
2150 *wlen = mbstowcs(NULL, s, 0);
2151 if (*wlen == (size_t)-1) {
2152 int vislen;
2153 if (errno != EILSEQ)
2154 return got_error_from_errno("mbstowcs");
2156 /* byte string invalid in current encoding; try to "fix" it */
2157 err = got_mbsavis(&vis, &vislen, s);
2158 if (err)
2159 return err;
2160 *wlen = mbstowcs(NULL, vis, 0);
2161 if (*wlen == (size_t)-1) {
2162 err = got_error_from_errno("mbstowcs"); /* give up */
2163 goto done;
2167 *ws = calloc(*wlen + 1, sizeof(**ws));
2168 if (*ws == NULL) {
2169 err = got_error_from_errno("calloc");
2170 goto done;
2173 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2174 err = got_error_from_errno("mbstowcs");
2175 done:
2176 free(vis);
2177 if (err) {
2178 free(*ws);
2179 *ws = NULL;
2180 *wlen = 0;
2182 return err;
2185 static const struct got_error *
2186 expand_tab(char **ptr, const char *src)
2188 char *dst;
2189 size_t len, n, idx = 0, sz = 0;
2191 *ptr = NULL;
2192 n = len = strlen(src);
2193 dst = malloc(n + 1);
2194 if (dst == NULL)
2195 return got_error_from_errno("malloc");
2197 while (idx < len && src[idx]) {
2198 const char c = src[idx];
2200 if (c == '\t') {
2201 size_t nb = TABSIZE - sz % TABSIZE;
2202 char *p;
2204 p = realloc(dst, n + nb);
2205 if (p == NULL) {
2206 free(dst);
2207 return got_error_from_errno("realloc");
2210 dst = p;
2211 n += nb;
2212 memset(dst + sz, ' ', nb);
2213 sz += nb;
2214 } else
2215 dst[sz++] = src[idx];
2216 ++idx;
2219 dst[sz] = '\0';
2220 *ptr = dst;
2221 return NULL;
2225 * Advance at most n columns from wline starting at offset off.
2226 * Return the index to the first character after the span operation.
2227 * Return the combined column width of all spanned wide characters in
2228 * *rcol.
2230 static int
2231 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2233 int width, i, cols = 0;
2235 if (n == 0) {
2236 *rcol = cols;
2237 return off;
2240 for (i = off; wline[i] != L'\0'; ++i) {
2241 if (wline[i] == L'\t')
2242 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2243 else
2244 width = wcwidth(wline[i]);
2246 if (width == -1) {
2247 width = 1;
2248 wline[i] = L'.';
2251 if (cols + width > n)
2252 break;
2253 cols += width;
2256 *rcol = cols;
2257 return i;
2261 * Format a line for display, ensuring that it won't overflow a width limit.
2262 * With scrolling, the width returned refers to the scrolled version of the
2263 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2265 static const struct got_error *
2266 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2267 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2269 const struct got_error *err = NULL;
2270 int cols;
2271 wchar_t *wline = NULL;
2272 char *exstr = NULL;
2273 size_t wlen;
2274 int i, scrollx;
2276 *wlinep = NULL;
2277 *widthp = 0;
2279 if (expand) {
2280 err = expand_tab(&exstr, line);
2281 if (err)
2282 return err;
2285 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2286 free(exstr);
2287 if (err)
2288 return err;
2290 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2292 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2293 wline[wlen - 1] = L'\0';
2294 wlen--;
2296 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2297 wline[wlen - 1] = L'\0';
2298 wlen--;
2301 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2302 wline[i] = L'\0';
2304 if (widthp)
2305 *widthp = cols;
2306 if (scrollxp)
2307 *scrollxp = scrollx;
2308 if (err)
2309 free(wline);
2310 else
2311 *wlinep = wline;
2312 return err;
2315 static const struct got_error*
2316 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2317 struct got_object_id *id, struct got_repository *repo)
2319 static const struct got_error *err = NULL;
2320 struct got_reflist_entry *re;
2321 char *s;
2322 const char *name;
2324 *refs_str = NULL;
2326 if (refs == NULL)
2327 return NULL;
2329 TAILQ_FOREACH(re, refs, entry) {
2330 struct got_tag_object *tag = NULL;
2331 struct got_object_id *ref_id;
2332 int cmp;
2334 name = got_ref_get_name(re->ref);
2335 if (strcmp(name, GOT_REF_HEAD) == 0)
2336 continue;
2337 if (strncmp(name, "refs/", 5) == 0)
2338 name += 5;
2339 if (strncmp(name, "got/", 4) == 0)
2340 continue;
2341 if (strncmp(name, "heads/", 6) == 0)
2342 name += 6;
2343 if (strncmp(name, "remotes/", 8) == 0) {
2344 name += 8;
2345 s = strstr(name, "/" GOT_REF_HEAD);
2346 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
2347 continue;
2349 err = got_ref_resolve(&ref_id, repo, re->ref);
2350 if (err)
2351 break;
2352 if (strncmp(name, "tags/", 5) == 0) {
2353 err = got_object_open_as_tag(&tag, repo, ref_id);
2354 if (err) {
2355 if (err->code != GOT_ERR_OBJ_TYPE) {
2356 free(ref_id);
2357 break;
2359 /* Ref points at something other than a tag. */
2360 err = NULL;
2361 tag = NULL;
2364 cmp = got_object_id_cmp(tag ?
2365 got_object_tag_get_object_id(tag) : ref_id, id);
2366 free(ref_id);
2367 if (tag)
2368 got_object_tag_close(tag);
2369 if (cmp != 0)
2370 continue;
2371 s = *refs_str;
2372 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2373 s ? ", " : "", name) == -1) {
2374 err = got_error_from_errno("asprintf");
2375 free(s);
2376 *refs_str = NULL;
2377 break;
2379 free(s);
2382 return err;
2385 static const struct got_error *
2386 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2387 int col_tab_align)
2389 char *smallerthan;
2391 smallerthan = strchr(author, '<');
2392 if (smallerthan && smallerthan[1] != '\0')
2393 author = smallerthan + 1;
2394 author[strcspn(author, "@>")] = '\0';
2395 return format_line(wauthor, author_width, NULL, author, 0, limit,
2396 col_tab_align, 0);
2399 static const struct got_error *
2400 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2401 struct got_object_id *id, const size_t date_display_cols,
2402 int author_display_cols)
2404 struct tog_log_view_state *s = &view->state.log;
2405 const struct got_error *err = NULL;
2406 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2407 char *refs_str = NULL;
2408 char *logmsg0 = NULL, *logmsg = NULL;
2409 char *author = NULL;
2410 wchar_t *wrefstr = NULL, *wlogmsg = NULL, *wauthor = NULL;
2411 int author_width, refstr_width, logmsg_width;
2412 char *newline, *line = NULL;
2413 int col, limit, scrollx, logmsg_x;
2414 const int avail = view->ncols;
2415 struct tm tm;
2416 time_t committer_time;
2417 struct tog_color *tc;
2418 struct got_reflist_head *refs;
2420 committer_time = got_object_commit_get_committer_time(commit);
2421 if (gmtime_r(&committer_time, &tm) == NULL)
2422 return got_error_from_errno("gmtime_r");
2423 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2424 return got_error(GOT_ERR_NO_SPACE);
2426 if (avail <= date_display_cols)
2427 limit = MIN(sizeof(datebuf) - 1, avail);
2428 else
2429 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2430 tc = get_color(&s->colors, TOG_COLOR_DATE);
2431 if (tc)
2432 wattr_on(view->window,
2433 COLOR_PAIR(tc->colorpair), NULL);
2434 waddnstr(view->window, datebuf, limit);
2435 if (tc)
2436 wattr_off(view->window,
2437 COLOR_PAIR(tc->colorpair), NULL);
2438 col = limit;
2439 if (col > avail)
2440 goto done;
2442 if (avail >= 120) {
2443 char *id_str;
2444 err = got_object_id_str(&id_str, id);
2445 if (err)
2446 goto done;
2447 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2448 if (tc)
2449 wattr_on(view->window,
2450 COLOR_PAIR(tc->colorpair), NULL);
2451 wprintw(view->window, "%.8s ", id_str);
2452 if (tc)
2453 wattr_off(view->window,
2454 COLOR_PAIR(tc->colorpair), NULL);
2455 free(id_str);
2456 col += 9;
2457 if (col > avail)
2458 goto done;
2461 if (s->use_committer)
2462 author = strdup(got_object_commit_get_committer(commit));
2463 else
2464 author = strdup(got_object_commit_get_author(commit));
2465 if (author == NULL) {
2466 err = got_error_from_errno("strdup");
2467 goto done;
2469 err = format_author(&wauthor, &author_width, author, avail - col, col);
2470 if (err)
2471 goto done;
2472 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2473 if (tc)
2474 wattr_on(view->window,
2475 COLOR_PAIR(tc->colorpair), NULL);
2476 waddwstr(view->window, wauthor);
2477 col += author_width;
2478 while (col < avail && author_width < author_display_cols + 2) {
2479 waddch(view->window, ' ');
2480 col++;
2481 author_width++;
2483 if (tc)
2484 wattr_off(view->window,
2485 COLOR_PAIR(tc->colorpair), NULL);
2486 if (col > avail)
2487 goto done;
2489 err = got_object_commit_get_logmsg(&logmsg0, commit);
2490 if (err)
2491 goto done;
2492 logmsg = logmsg0;
2493 while (*logmsg == '\n')
2494 logmsg++;
2495 newline = strchr(logmsg, '\n');
2496 if (newline)
2497 *newline = '\0';
2499 limit = avail - col;
2500 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2501 limit--; /* for the border */
2503 /* Prepend reference labels to log message if possible .*/
2504 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, id);
2505 err = build_refs_str(&refs_str, refs, id, s->repo);
2506 if (err)
2507 goto done;
2508 if (refs_str) {
2509 char *rs;
2511 if (asprintf(&rs, "[%s]", refs_str) == -1) {
2512 err = got_error_from_errno("asprintf");
2513 goto done;
2515 err = format_line(&wrefstr, &refstr_width,
2516 &scrollx, rs, view->x, limit, col, 1);
2517 free(rs);
2518 if (err)
2519 goto done;
2520 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2521 if (tc)
2522 wattr_on(view->window,
2523 COLOR_PAIR(tc->colorpair), NULL);
2524 waddwstr(view->window, &wrefstr[scrollx]);
2525 if (tc)
2526 wattr_off(view->window,
2527 COLOR_PAIR(tc->colorpair), NULL);
2528 col += MAX(refstr_width, 0);
2529 if (col > avail)
2530 goto done;
2532 if (col < avail) {
2533 waddch(view->window, ' ');
2534 col++;
2537 if (refstr_width > 0)
2538 logmsg_x = 0;
2539 else {
2540 int unscrolled_refstr_width;
2541 size_t len = wcslen(wrefstr);
2544 * No need to check for -1 return value here since
2545 * unprintables have been replaced by span_wline().
2547 unscrolled_refstr_width = wcswidth(wrefstr, len);
2548 unscrolled_refstr_width += 1; /* trailing space */
2549 logmsg_x = view->x - unscrolled_refstr_width;
2552 limit = avail - col;
2553 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2554 limit--; /* for the border */
2555 } else
2556 logmsg_x = view->x;
2558 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, logmsg_x,
2559 limit, col, 1);
2560 if (err)
2561 goto done;
2562 waddwstr(view->window, &wlogmsg[scrollx]);
2563 col += MAX(logmsg_width, 0);
2564 while (col < avail) {
2565 waddch(view->window, ' ');
2566 col++;
2568 done:
2569 free(logmsg0);
2570 free(wlogmsg);
2571 free(wrefstr);
2572 free(refs_str);
2573 free(author);
2574 free(wauthor);
2575 free(line);
2576 return err;
2579 static struct commit_queue_entry *
2580 alloc_commit_queue_entry(struct got_commit_object *commit,
2581 struct got_object_id *id)
2583 struct commit_queue_entry *entry;
2584 struct got_object_id *dup;
2586 entry = calloc(1, sizeof(*entry));
2587 if (entry == NULL)
2588 return NULL;
2590 dup = got_object_id_dup(id);
2591 if (dup == NULL) {
2592 free(entry);
2593 return NULL;
2596 entry->id = dup;
2597 entry->commit = commit;
2598 return entry;
2601 static void
2602 pop_commit(struct commit_queue *commits)
2604 struct commit_queue_entry *entry;
2606 entry = TAILQ_FIRST(&commits->head);
2607 TAILQ_REMOVE(&commits->head, entry, entry);
2608 got_object_commit_close(entry->commit);
2609 commits->ncommits--;
2610 free(entry->id);
2611 free(entry);
2614 static void
2615 free_commits(struct commit_queue *commits)
2617 while (!TAILQ_EMPTY(&commits->head))
2618 pop_commit(commits);
2621 static const struct got_error *
2622 match_commit(int *have_match, struct got_object_id *id,
2623 struct got_commit_object *commit, regex_t *regex)
2625 const struct got_error *err = NULL;
2626 regmatch_t regmatch;
2627 char *id_str = NULL, *logmsg = NULL;
2629 *have_match = 0;
2631 err = got_object_id_str(&id_str, id);
2632 if (err)
2633 return err;
2635 err = got_object_commit_get_logmsg(&logmsg, commit);
2636 if (err)
2637 goto done;
2639 if (regexec(regex, got_object_commit_get_author(commit), 1,
2640 &regmatch, 0) == 0 ||
2641 regexec(regex, got_object_commit_get_committer(commit), 1,
2642 &regmatch, 0) == 0 ||
2643 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2644 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2645 *have_match = 1;
2646 done:
2647 free(id_str);
2648 free(logmsg);
2649 return err;
2652 static const struct got_error *
2653 queue_commits(struct tog_log_thread_args *a)
2655 const struct got_error *err = NULL;
2658 * We keep all commits open throughout the lifetime of the log
2659 * view in order to avoid having to re-fetch commits from disk
2660 * while updating the display.
2662 do {
2663 struct got_object_id id;
2664 struct got_commit_object *commit;
2665 struct commit_queue_entry *entry;
2666 int limit_match = 0;
2667 int errcode;
2669 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2670 NULL, NULL);
2671 if (err)
2672 break;
2674 err = got_object_open_as_commit(&commit, a->repo, &id);
2675 if (err)
2676 break;
2677 entry = alloc_commit_queue_entry(commit, &id);
2678 if (entry == NULL) {
2679 err = got_error_from_errno("alloc_commit_queue_entry");
2680 break;
2683 errcode = pthread_mutex_lock(&tog_mutex);
2684 if (errcode) {
2685 err = got_error_set_errno(errcode,
2686 "pthread_mutex_lock");
2687 break;
2690 entry->idx = a->real_commits->ncommits;
2691 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2692 a->real_commits->ncommits++;
2694 if (*a->limiting) {
2695 err = match_commit(&limit_match, &id, commit,
2696 a->limit_regex);
2697 if (err)
2698 break;
2700 if (limit_match) {
2701 struct commit_queue_entry *matched;
2703 matched = alloc_commit_queue_entry(
2704 entry->commit, entry->id);
2705 if (matched == NULL) {
2706 err = got_error_from_errno(
2707 "alloc_commit_queue_entry");
2708 break;
2710 matched->commit = entry->commit;
2711 got_object_commit_retain(entry->commit);
2713 matched->idx = a->limit_commits->ncommits;
2714 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2715 matched, entry);
2716 a->limit_commits->ncommits++;
2720 * This is how we signal log_thread() that we
2721 * have found a match, and that it should be
2722 * counted as a new entry for the view.
2724 a->limit_match = limit_match;
2727 if (*a->searching == TOG_SEARCH_FORWARD &&
2728 !*a->search_next_done) {
2729 int have_match;
2730 err = match_commit(&have_match, &id, commit, a->regex);
2731 if (err)
2732 break;
2734 if (*a->limiting) {
2735 if (limit_match && have_match)
2736 *a->search_next_done =
2737 TOG_SEARCH_HAVE_MORE;
2738 } else if (have_match)
2739 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2742 errcode = pthread_mutex_unlock(&tog_mutex);
2743 if (errcode && err == NULL)
2744 err = got_error_set_errno(errcode,
2745 "pthread_mutex_unlock");
2746 if (err)
2747 break;
2748 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2750 return err;
2753 static void
2754 select_commit(struct tog_log_view_state *s)
2756 struct commit_queue_entry *entry;
2757 int ncommits = 0;
2759 entry = s->first_displayed_entry;
2760 while (entry) {
2761 if (ncommits == s->selected) {
2762 s->selected_entry = entry;
2763 break;
2765 entry = TAILQ_NEXT(entry, entry);
2766 ncommits++;
2770 static const struct got_error *
2771 draw_commits(struct tog_view *view)
2773 const struct got_error *err = NULL;
2774 struct tog_log_view_state *s = &view->state.log;
2775 struct commit_queue_entry *entry = s->selected_entry;
2776 int limit = view->nlines;
2777 int width;
2778 int ncommits, author_cols = 4, refstr_cols;
2779 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2780 char *refs_str = NULL;
2781 wchar_t *wline;
2782 struct tog_color *tc;
2783 static const size_t date_display_cols = 12;
2784 struct got_reflist_head *refs;
2786 if (view_is_hsplit_top(view))
2787 --limit; /* account for border */
2789 if (s->selected_entry &&
2790 !(view->searching && view->search_next_done == 0)) {
2791 err = got_object_id_str(&id_str, s->selected_entry->id);
2792 if (err)
2793 return err;
2794 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2795 s->selected_entry->id);
2796 err = build_refs_str(&refs_str, refs, s->selected_entry->id,
2797 s->repo);
2798 if (err)
2799 goto done;
2802 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2803 halfdelay(10); /* disable fast refresh */
2805 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2806 if (asprintf(&ncommits_str, " [%d/%d] %s",
2807 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2808 (view->searching && !view->search_next_done) ?
2809 "searching..." : "loading...") == -1) {
2810 err = got_error_from_errno("asprintf");
2811 goto done;
2813 } else {
2814 const char *search_str = NULL;
2815 const char *limit_str = NULL;
2817 if (view->searching) {
2818 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2819 search_str = "no more matches";
2820 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2821 search_str = "no matches found";
2822 else if (!view->search_next_done)
2823 search_str = "searching...";
2826 if (s->limit_view && s->commits->ncommits == 0)
2827 limit_str = "no matches found";
2829 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2830 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2831 search_str ? search_str : (refs_str ? refs_str : ""),
2832 limit_str ? limit_str : "") == -1) {
2833 err = got_error_from_errno("asprintf");
2834 goto done;
2838 free(refs_str);
2839 refs_str = NULL;
2841 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2842 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2843 "........................................",
2844 s->in_repo_path, ncommits_str) == -1) {
2845 err = got_error_from_errno("asprintf");
2846 header = NULL;
2847 goto done;
2849 } else if (asprintf(&header, "commit %s%s",
2850 id_str ? id_str : "........................................",
2851 ncommits_str) == -1) {
2852 err = got_error_from_errno("asprintf");
2853 header = NULL;
2854 goto done;
2856 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2857 if (err)
2858 goto done;
2860 werase(view->window);
2862 if (view_needs_focus_indication(view))
2863 wstandout(view->window);
2864 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2865 if (tc)
2866 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2867 waddwstr(view->window, wline);
2868 while (width < view->ncols) {
2869 waddch(view->window, ' ');
2870 width++;
2872 if (tc)
2873 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2874 if (view_needs_focus_indication(view))
2875 wstandend(view->window);
2876 free(wline);
2877 if (limit <= 1)
2878 goto done;
2880 /* Grow author column size if necessary, and set view->maxx. */
2881 entry = s->first_displayed_entry;
2882 ncommits = 0;
2883 view->maxx = 0;
2884 while (entry) {
2885 struct got_commit_object *c = entry->commit;
2886 char *author, *eol, *msg, *msg0;
2887 wchar_t *wauthor, *wmsg;
2888 int width;
2889 if (ncommits >= limit - 1)
2890 break;
2891 if (s->use_committer)
2892 author = strdup(got_object_commit_get_committer(c));
2893 else
2894 author = strdup(got_object_commit_get_author(c));
2895 if (author == NULL) {
2896 err = got_error_from_errno("strdup");
2897 goto done;
2899 err = format_author(&wauthor, &width, author, COLS,
2900 date_display_cols);
2901 if (author_cols < width)
2902 author_cols = width;
2903 free(wauthor);
2904 free(author);
2905 if (err)
2906 goto done;
2907 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2908 entry->id);
2909 err = build_refs_str(&refs_str, refs, entry->id, s->repo);
2910 if (err)
2911 goto done;
2912 if (refs_str) {
2913 wchar_t *ws;
2914 err = format_line(&ws, &width, NULL, refs_str,
2915 0, INT_MAX, date_display_cols + author_cols, 0);
2916 free(ws);
2917 free(refs_str);
2918 refs_str = NULL;
2919 if (err)
2920 goto done;
2921 refstr_cols = width + 3; /* account for [ ] + space */
2922 } else
2923 refstr_cols = 0;
2924 err = got_object_commit_get_logmsg(&msg0, c);
2925 if (err)
2926 goto done;
2927 msg = msg0;
2928 while (*msg == '\n')
2929 ++msg;
2930 if ((eol = strchr(msg, '\n')))
2931 *eol = '\0';
2932 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2933 date_display_cols + author_cols + refstr_cols, 0);
2934 if (err)
2935 goto done;
2936 view->maxx = MAX(view->maxx, width + refstr_cols);
2937 free(msg0);
2938 free(wmsg);
2939 ncommits++;
2940 entry = TAILQ_NEXT(entry, entry);
2943 entry = s->first_displayed_entry;
2944 s->last_displayed_entry = s->first_displayed_entry;
2945 ncommits = 0;
2946 while (entry) {
2947 if (ncommits >= limit - 1)
2948 break;
2949 if (ncommits == s->selected)
2950 wstandout(view->window);
2951 err = draw_commit(view, entry->commit, entry->id,
2952 date_display_cols, author_cols);
2953 if (ncommits == s->selected)
2954 wstandend(view->window);
2955 if (err)
2956 goto done;
2957 ncommits++;
2958 s->last_displayed_entry = entry;
2959 entry = TAILQ_NEXT(entry, entry);
2962 view_border(view);
2963 done:
2964 free(id_str);
2965 free(refs_str);
2966 free(ncommits_str);
2967 free(header);
2968 return err;
2971 static void
2972 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2974 struct commit_queue_entry *entry;
2975 int nscrolled = 0;
2977 entry = TAILQ_FIRST(&s->commits->head);
2978 if (s->first_displayed_entry == entry)
2979 return;
2981 entry = s->first_displayed_entry;
2982 while (entry && nscrolled < maxscroll) {
2983 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2984 if (entry) {
2985 s->first_displayed_entry = entry;
2986 nscrolled++;
2991 static const struct got_error *
2992 trigger_log_thread(struct tog_view *view, int wait)
2994 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2995 int errcode;
2997 if (!using_mock_io)
2998 halfdelay(1); /* fast refresh while loading commits */
3000 while (!ta->log_complete && !tog_thread_error &&
3001 (ta->commits_needed > 0 || ta->load_all)) {
3002 /* Wake the log thread. */
3003 errcode = pthread_cond_signal(&ta->need_commits);
3004 if (errcode)
3005 return got_error_set_errno(errcode,
3006 "pthread_cond_signal");
3009 * The mutex will be released while the view loop waits
3010 * in wgetch(), at which time the log thread will run.
3012 if (!wait)
3013 break;
3015 /* Display progress update in log view. */
3016 show_log_view(view);
3017 update_panels();
3018 doupdate();
3020 /* Wait right here while next commit is being loaded. */
3021 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
3022 if (errcode)
3023 return got_error_set_errno(errcode,
3024 "pthread_cond_wait");
3026 /* Display progress update in log view. */
3027 show_log_view(view);
3028 update_panels();
3029 doupdate();
3032 return NULL;
3035 static const struct got_error *
3036 request_log_commits(struct tog_view *view)
3038 struct tog_log_view_state *state = &view->state.log;
3039 const struct got_error *err = NULL;
3041 if (state->thread_args.log_complete)
3042 return NULL;
3044 state->thread_args.commits_needed += view->nscrolled;
3045 err = trigger_log_thread(view, 1);
3046 view->nscrolled = 0;
3048 return err;
3051 static const struct got_error *
3052 log_scroll_down(struct tog_view *view, int maxscroll)
3054 struct tog_log_view_state *s = &view->state.log;
3055 const struct got_error *err = NULL;
3056 struct commit_queue_entry *pentry;
3057 int nscrolled = 0, ncommits_needed;
3059 if (s->last_displayed_entry == NULL)
3060 return NULL;
3062 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
3063 if (s->commits->ncommits < ncommits_needed &&
3064 !s->thread_args.log_complete) {
3066 * Ask the log thread for required amount of commits.
3068 s->thread_args.commits_needed +=
3069 ncommits_needed - s->commits->ncommits;
3070 err = trigger_log_thread(view, 1);
3071 if (err)
3072 return err;
3075 do {
3076 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
3077 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
3078 break;
3080 s->last_displayed_entry = pentry ?
3081 pentry : s->last_displayed_entry;
3083 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3084 if (pentry == NULL)
3085 break;
3086 s->first_displayed_entry = pentry;
3087 } while (++nscrolled < maxscroll);
3089 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3090 view->nscrolled += nscrolled;
3091 else
3092 view->nscrolled = 0;
3094 return err;
3097 static const struct got_error *
3098 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3099 struct got_commit_object *commit, struct got_object_id *commit_id,
3100 struct tog_view *log_view, struct got_repository *repo)
3102 const struct got_error *err;
3103 struct got_object_qid *parent_id;
3104 struct tog_view *diff_view;
3106 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3107 if (diff_view == NULL)
3108 return got_error_from_errno("view_open");
3110 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3111 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3112 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3113 if (err == NULL)
3114 *new_view = diff_view;
3115 return err;
3118 static const struct got_error *
3119 tree_view_visit_subtree(struct tog_tree_view_state *s,
3120 struct got_tree_object *subtree)
3122 struct tog_parent_tree *parent;
3124 parent = calloc(1, sizeof(*parent));
3125 if (parent == NULL)
3126 return got_error_from_errno("calloc");
3128 parent->tree = s->tree;
3129 parent->first_displayed_entry = s->first_displayed_entry;
3130 parent->selected_entry = s->selected_entry;
3131 parent->selected = s->selected;
3132 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3133 s->tree = subtree;
3134 s->selected = 0;
3135 s->first_displayed_entry = NULL;
3136 return NULL;
3139 static const struct got_error *
3140 tree_view_walk_path(struct tog_tree_view_state *s,
3141 struct got_commit_object *commit, const char *path)
3143 const struct got_error *err = NULL;
3144 struct got_tree_object *tree = NULL;
3145 const char *p;
3146 char *slash, *subpath = NULL;
3148 /* Walk the path and open corresponding tree objects. */
3149 p = path;
3150 while (*p) {
3151 struct got_tree_entry *te;
3152 struct got_object_id *tree_id;
3153 char *te_name;
3155 while (p[0] == '/')
3156 p++;
3158 /* Ensure the correct subtree entry is selected. */
3159 slash = strchr(p, '/');
3160 if (slash == NULL)
3161 te_name = strdup(p);
3162 else
3163 te_name = strndup(p, slash - p);
3164 if (te_name == NULL) {
3165 err = got_error_from_errno("strndup");
3166 break;
3168 te = got_object_tree_find_entry(s->tree, te_name);
3169 if (te == NULL) {
3170 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3171 free(te_name);
3172 break;
3174 free(te_name);
3175 s->first_displayed_entry = s->selected_entry = te;
3177 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3178 break; /* jump to this file's entry */
3180 slash = strchr(p, '/');
3181 if (slash)
3182 subpath = strndup(path, slash - path);
3183 else
3184 subpath = strdup(path);
3185 if (subpath == NULL) {
3186 err = got_error_from_errno("strdup");
3187 break;
3190 err = got_object_id_by_path(&tree_id, s->repo, commit,
3191 subpath);
3192 if (err)
3193 break;
3195 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3196 free(tree_id);
3197 if (err)
3198 break;
3200 err = tree_view_visit_subtree(s, tree);
3201 if (err) {
3202 got_object_tree_close(tree);
3203 break;
3205 if (slash == NULL)
3206 break;
3207 free(subpath);
3208 subpath = NULL;
3209 p = slash;
3212 free(subpath);
3213 return err;
3216 static const struct got_error *
3217 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3218 struct commit_queue_entry *entry, const char *path,
3219 const char *head_ref_name, struct got_repository *repo)
3221 const struct got_error *err = NULL;
3222 struct tog_tree_view_state *s;
3223 struct tog_view *tree_view;
3225 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3226 if (tree_view == NULL)
3227 return got_error_from_errno("view_open");
3229 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3230 if (err)
3231 return err;
3232 s = &tree_view->state.tree;
3234 *new_view = tree_view;
3236 if (got_path_is_root_dir(path))
3237 return NULL;
3239 return tree_view_walk_path(s, entry->commit, path);
3242 static const struct got_error *
3243 block_signals_used_by_main_thread(void)
3245 sigset_t sigset;
3246 int errcode;
3248 if (sigemptyset(&sigset) == -1)
3249 return got_error_from_errno("sigemptyset");
3251 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3252 if (sigaddset(&sigset, SIGWINCH) == -1)
3253 return got_error_from_errno("sigaddset");
3254 if (sigaddset(&sigset, SIGCONT) == -1)
3255 return got_error_from_errno("sigaddset");
3256 if (sigaddset(&sigset, SIGINT) == -1)
3257 return got_error_from_errno("sigaddset");
3258 if (sigaddset(&sigset, SIGTERM) == -1)
3259 return got_error_from_errno("sigaddset");
3261 /* ncurses handles SIGTSTP */
3262 if (sigaddset(&sigset, SIGTSTP) == -1)
3263 return got_error_from_errno("sigaddset");
3265 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3266 if (errcode)
3267 return got_error_set_errno(errcode, "pthread_sigmask");
3269 return NULL;
3272 static void *
3273 log_thread(void *arg)
3275 const struct got_error *err = NULL;
3276 int errcode = 0;
3277 struct tog_log_thread_args *a = arg;
3278 int done = 0;
3281 * Sync startup with main thread such that we begin our
3282 * work once view_input() has released the mutex.
3284 errcode = pthread_mutex_lock(&tog_mutex);
3285 if (errcode) {
3286 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3287 return (void *)err;
3290 err = block_signals_used_by_main_thread();
3291 if (err) {
3292 pthread_mutex_unlock(&tog_mutex);
3293 goto done;
3296 while (!done && !err && !tog_fatal_signal_received()) {
3297 errcode = pthread_mutex_unlock(&tog_mutex);
3298 if (errcode) {
3299 err = got_error_set_errno(errcode,
3300 "pthread_mutex_unlock");
3301 goto done;
3303 err = queue_commits(a);
3304 if (err) {
3305 if (err->code != GOT_ERR_ITER_COMPLETED)
3306 goto done;
3307 err = NULL;
3308 done = 1;
3309 } else if (a->commits_needed > 0 && !a->load_all) {
3310 if (*a->limiting) {
3311 if (a->limit_match)
3312 a->commits_needed--;
3313 } else
3314 a->commits_needed--;
3317 errcode = pthread_mutex_lock(&tog_mutex);
3318 if (errcode) {
3319 err = got_error_set_errno(errcode,
3320 "pthread_mutex_lock");
3321 goto done;
3322 } else if (*a->quit)
3323 done = 1;
3324 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3325 *a->first_displayed_entry =
3326 TAILQ_FIRST(&a->limit_commits->head);
3327 *a->selected_entry = *a->first_displayed_entry;
3328 } else if (*a->first_displayed_entry == NULL) {
3329 *a->first_displayed_entry =
3330 TAILQ_FIRST(&a->real_commits->head);
3331 *a->selected_entry = *a->first_displayed_entry;
3334 errcode = pthread_cond_signal(&a->commit_loaded);
3335 if (errcode) {
3336 err = got_error_set_errno(errcode,
3337 "pthread_cond_signal");
3338 pthread_mutex_unlock(&tog_mutex);
3339 goto done;
3342 if (done)
3343 a->commits_needed = 0;
3344 else {
3345 if (a->commits_needed == 0 && !a->load_all) {
3346 errcode = pthread_cond_wait(&a->need_commits,
3347 &tog_mutex);
3348 if (errcode) {
3349 err = got_error_set_errno(errcode,
3350 "pthread_cond_wait");
3351 pthread_mutex_unlock(&tog_mutex);
3352 goto done;
3354 if (*a->quit)
3355 done = 1;
3359 a->log_complete = 1;
3360 errcode = pthread_mutex_unlock(&tog_mutex);
3361 if (errcode)
3362 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3363 done:
3364 if (err) {
3365 tog_thread_error = 1;
3366 pthread_cond_signal(&a->commit_loaded);
3368 return (void *)err;
3371 static const struct got_error *
3372 stop_log_thread(struct tog_log_view_state *s)
3374 const struct got_error *err = NULL, *thread_err = NULL;
3375 int errcode;
3377 if (s->thread) {
3378 s->quit = 1;
3379 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3380 if (errcode)
3381 return got_error_set_errno(errcode,
3382 "pthread_cond_signal");
3383 errcode = pthread_mutex_unlock(&tog_mutex);
3384 if (errcode)
3385 return got_error_set_errno(errcode,
3386 "pthread_mutex_unlock");
3387 errcode = pthread_join(s->thread, (void **)&thread_err);
3388 if (errcode)
3389 return got_error_set_errno(errcode, "pthread_join");
3390 errcode = pthread_mutex_lock(&tog_mutex);
3391 if (errcode)
3392 return got_error_set_errno(errcode,
3393 "pthread_mutex_lock");
3394 s->thread = NULL;
3397 if (s->thread_args.repo) {
3398 err = got_repo_close(s->thread_args.repo);
3399 s->thread_args.repo = NULL;
3402 if (s->thread_args.pack_fds) {
3403 const struct got_error *pack_err =
3404 got_repo_pack_fds_close(s->thread_args.pack_fds);
3405 if (err == NULL)
3406 err = pack_err;
3407 s->thread_args.pack_fds = NULL;
3410 if (s->thread_args.graph) {
3411 got_commit_graph_close(s->thread_args.graph);
3412 s->thread_args.graph = NULL;
3415 return err ? err : thread_err;
3418 static const struct got_error *
3419 close_log_view(struct tog_view *view)
3421 const struct got_error *err = NULL;
3422 struct tog_log_view_state *s = &view->state.log;
3423 int errcode;
3425 err = stop_log_thread(s);
3427 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3428 if (errcode && err == NULL)
3429 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3431 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3432 if (errcode && err == NULL)
3433 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3435 free_commits(&s->limit_commits);
3436 free_commits(&s->real_commits);
3437 free(s->in_repo_path);
3438 s->in_repo_path = NULL;
3439 free(s->start_id);
3440 s->start_id = NULL;
3441 free(s->head_ref_name);
3442 s->head_ref_name = NULL;
3443 return err;
3447 * We use two queues to implement the limit feature: first consists of
3448 * commits matching the current limit_regex; second is the real queue
3449 * of all known commits (real_commits). When the user starts limiting,
3450 * we swap queues such that all movement and displaying functionality
3451 * works with very slight change.
3453 static const struct got_error *
3454 limit_log_view(struct tog_view *view)
3456 struct tog_log_view_state *s = &view->state.log;
3457 struct commit_queue_entry *entry;
3458 struct tog_view *v = view;
3459 const struct got_error *err = NULL;
3460 char pattern[1024];
3461 int ret;
3463 if (view_is_hsplit_top(view))
3464 v = view->child;
3465 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3466 v = view->parent;
3468 /* Get the pattern */
3469 wmove(v->window, v->nlines - 1, 0);
3470 wclrtoeol(v->window);
3471 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3472 nodelay(v->window, FALSE);
3473 nocbreak();
3474 echo();
3475 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3476 cbreak();
3477 noecho();
3478 nodelay(v->window, TRUE);
3479 if (ret == ERR)
3480 return NULL;
3482 if (*pattern == '\0') {
3484 * Safety measure for the situation where the user
3485 * resets limit without previously limiting anything.
3487 if (!s->limit_view)
3488 return NULL;
3491 * User could have pressed Ctrl+L, which refreshed the
3492 * commit queues, it means we can't save previously
3493 * (before limit took place) displayed entries,
3494 * because they would point to already free'ed memory,
3495 * so we are forced to always select first entry of
3496 * the queue.
3498 s->commits = &s->real_commits;
3499 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3500 s->selected_entry = s->first_displayed_entry;
3501 s->selected = 0;
3502 s->limit_view = 0;
3504 return NULL;
3507 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3508 return NULL;
3510 s->limit_view = 1;
3512 /* Clear the screen while loading limit view */
3513 s->first_displayed_entry = NULL;
3514 s->last_displayed_entry = NULL;
3515 s->selected_entry = NULL;
3516 s->commits = &s->limit_commits;
3518 /* Prepare limit queue for new search */
3519 free_commits(&s->limit_commits);
3520 s->limit_commits.ncommits = 0;
3522 /* First process commits, which are in queue already */
3523 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3524 int have_match = 0;
3526 err = match_commit(&have_match, entry->id,
3527 entry->commit, &s->limit_regex);
3528 if (err)
3529 return err;
3531 if (have_match) {
3532 struct commit_queue_entry *matched;
3534 matched = alloc_commit_queue_entry(entry->commit,
3535 entry->id);
3536 if (matched == NULL) {
3537 err = got_error_from_errno(
3538 "alloc_commit_queue_entry");
3539 break;
3541 matched->commit = entry->commit;
3542 got_object_commit_retain(entry->commit);
3544 matched->idx = s->limit_commits.ncommits;
3545 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3546 matched, entry);
3547 s->limit_commits.ncommits++;
3551 /* Second process all the commits, until we fill the screen */
3552 if (s->limit_commits.ncommits < view->nlines - 1 &&
3553 !s->thread_args.log_complete) {
3554 s->thread_args.commits_needed +=
3555 view->nlines - s->limit_commits.ncommits - 1;
3556 err = trigger_log_thread(view, 1);
3557 if (err)
3558 return err;
3561 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3562 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3563 s->selected = 0;
3565 return NULL;
3568 static const struct got_error *
3569 search_start_log_view(struct tog_view *view)
3571 struct tog_log_view_state *s = &view->state.log;
3573 s->matched_entry = NULL;
3574 s->search_entry = NULL;
3575 return NULL;
3578 static const struct got_error *
3579 search_next_log_view(struct tog_view *view)
3581 const struct got_error *err = NULL;
3582 struct tog_log_view_state *s = &view->state.log;
3583 struct commit_queue_entry *entry;
3585 /* Display progress update in log view. */
3586 show_log_view(view);
3587 update_panels();
3588 doupdate();
3590 if (s->search_entry) {
3591 int errcode, ch;
3592 errcode = pthread_mutex_unlock(&tog_mutex);
3593 if (errcode)
3594 return got_error_set_errno(errcode,
3595 "pthread_mutex_unlock");
3596 ch = wgetch(view->window);
3597 errcode = pthread_mutex_lock(&tog_mutex);
3598 if (errcode)
3599 return got_error_set_errno(errcode,
3600 "pthread_mutex_lock");
3601 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3602 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3603 return NULL;
3605 if (view->searching == TOG_SEARCH_FORWARD)
3606 entry = TAILQ_NEXT(s->search_entry, entry);
3607 else
3608 entry = TAILQ_PREV(s->search_entry,
3609 commit_queue_head, entry);
3610 } else if (s->matched_entry) {
3612 * If the user has moved the cursor after we hit a match,
3613 * the position from where we should continue searching
3614 * might have changed.
3616 if (view->searching == TOG_SEARCH_FORWARD)
3617 entry = TAILQ_NEXT(s->selected_entry, entry);
3618 else
3619 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3620 entry);
3621 } else {
3622 entry = s->selected_entry;
3625 while (1) {
3626 int have_match = 0;
3628 if (entry == NULL) {
3629 if (s->thread_args.log_complete ||
3630 view->searching == TOG_SEARCH_BACKWARD) {
3631 view->search_next_done =
3632 (s->matched_entry == NULL ?
3633 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3634 s->search_entry = NULL;
3635 return NULL;
3638 * Poke the log thread for more commits and return,
3639 * allowing the main loop to make progress. Search
3640 * will resume at s->search_entry once we come back.
3642 s->thread_args.commits_needed++;
3643 return trigger_log_thread(view, 0);
3646 err = match_commit(&have_match, entry->id, entry->commit,
3647 &view->regex);
3648 if (err)
3649 break;
3650 if (have_match) {
3651 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3652 s->matched_entry = entry;
3653 break;
3656 s->search_entry = entry;
3657 if (view->searching == TOG_SEARCH_FORWARD)
3658 entry = TAILQ_NEXT(entry, entry);
3659 else
3660 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3663 if (s->matched_entry) {
3664 int cur = s->selected_entry->idx;
3665 while (cur < s->matched_entry->idx) {
3666 err = input_log_view(NULL, view, KEY_DOWN);
3667 if (err)
3668 return err;
3669 cur++;
3671 while (cur > s->matched_entry->idx) {
3672 err = input_log_view(NULL, view, KEY_UP);
3673 if (err)
3674 return err;
3675 cur--;
3679 s->search_entry = NULL;
3681 return NULL;
3684 static const struct got_error *
3685 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3686 struct got_repository *repo, const char *head_ref_name,
3687 const char *in_repo_path, int log_branches)
3689 const struct got_error *err = NULL;
3690 struct tog_log_view_state *s = &view->state.log;
3691 struct got_repository *thread_repo = NULL;
3692 struct got_commit_graph *thread_graph = NULL;
3693 int errcode;
3695 if (in_repo_path != s->in_repo_path) {
3696 free(s->in_repo_path);
3697 s->in_repo_path = strdup(in_repo_path);
3698 if (s->in_repo_path == NULL) {
3699 err = got_error_from_errno("strdup");
3700 goto done;
3704 /* The commit queue only contains commits being displayed. */
3705 TAILQ_INIT(&s->real_commits.head);
3706 s->real_commits.ncommits = 0;
3707 s->commits = &s->real_commits;
3709 TAILQ_INIT(&s->limit_commits.head);
3710 s->limit_view = 0;
3711 s->limit_commits.ncommits = 0;
3713 s->repo = repo;
3714 if (head_ref_name) {
3715 s->head_ref_name = strdup(head_ref_name);
3716 if (s->head_ref_name == NULL) {
3717 err = got_error_from_errno("strdup");
3718 goto done;
3721 s->start_id = got_object_id_dup(start_id);
3722 if (s->start_id == NULL) {
3723 err = got_error_from_errno("got_object_id_dup");
3724 goto done;
3726 s->log_branches = log_branches;
3727 s->use_committer = 1;
3729 STAILQ_INIT(&s->colors);
3730 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3731 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3732 get_color_value("TOG_COLOR_COMMIT"));
3733 if (err)
3734 goto done;
3735 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3736 get_color_value("TOG_COLOR_AUTHOR"));
3737 if (err) {
3738 free_colors(&s->colors);
3739 goto done;
3741 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3742 get_color_value("TOG_COLOR_DATE"));
3743 if (err) {
3744 free_colors(&s->colors);
3745 goto done;
3749 view->show = show_log_view;
3750 view->input = input_log_view;
3751 view->resize = resize_log_view;
3752 view->close = close_log_view;
3753 view->search_start = search_start_log_view;
3754 view->search_next = search_next_log_view;
3756 if (s->thread_args.pack_fds == NULL) {
3757 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3758 if (err)
3759 goto done;
3761 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3762 s->thread_args.pack_fds);
3763 if (err)
3764 goto done;
3765 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3766 !s->log_branches);
3767 if (err)
3768 goto done;
3769 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3770 s->repo, NULL, NULL);
3771 if (err)
3772 goto done;
3774 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3775 if (errcode) {
3776 err = got_error_set_errno(errcode, "pthread_cond_init");
3777 goto done;
3779 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3780 if (errcode) {
3781 err = got_error_set_errno(errcode, "pthread_cond_init");
3782 goto done;
3785 s->thread_args.commits_needed = view->nlines;
3786 s->thread_args.graph = thread_graph;
3787 s->thread_args.real_commits = &s->real_commits;
3788 s->thread_args.limit_commits = &s->limit_commits;
3789 s->thread_args.in_repo_path = s->in_repo_path;
3790 s->thread_args.start_id = s->start_id;
3791 s->thread_args.repo = thread_repo;
3792 s->thread_args.log_complete = 0;
3793 s->thread_args.quit = &s->quit;
3794 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3795 s->thread_args.selected_entry = &s->selected_entry;
3796 s->thread_args.searching = &view->searching;
3797 s->thread_args.search_next_done = &view->search_next_done;
3798 s->thread_args.regex = &view->regex;
3799 s->thread_args.limiting = &s->limit_view;
3800 s->thread_args.limit_regex = &s->limit_regex;
3801 s->thread_args.limit_commits = &s->limit_commits;
3802 done:
3803 if (err) {
3804 if (view->close == NULL)
3805 close_log_view(view);
3806 view_close(view);
3808 return err;
3811 static const struct got_error *
3812 show_log_view(struct tog_view *view)
3814 const struct got_error *err;
3815 struct tog_log_view_state *s = &view->state.log;
3817 if (s->thread == NULL) {
3818 int errcode = pthread_create(&s->thread, NULL, log_thread,
3819 &s->thread_args);
3820 if (errcode)
3821 return got_error_set_errno(errcode, "pthread_create");
3822 if (s->thread_args.commits_needed > 0) {
3823 err = trigger_log_thread(view, 1);
3824 if (err)
3825 return err;
3829 return draw_commits(view);
3832 static void
3833 log_move_cursor_up(struct tog_view *view, int page, int home)
3835 struct tog_log_view_state *s = &view->state.log;
3837 if (s->first_displayed_entry == NULL)
3838 return;
3839 if (s->selected_entry->idx == 0)
3840 view->count = 0;
3842 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3843 || home)
3844 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3846 if (!page && !home && s->selected > 0)
3847 --s->selected;
3848 else
3849 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3851 select_commit(s);
3852 return;
3855 static const struct got_error *
3856 log_move_cursor_down(struct tog_view *view, int page)
3858 struct tog_log_view_state *s = &view->state.log;
3859 const struct got_error *err = NULL;
3860 int eos = view->nlines - 2;
3862 if (s->first_displayed_entry == NULL)
3863 return NULL;
3865 if (s->thread_args.log_complete &&
3866 s->selected_entry->idx >= s->commits->ncommits - 1)
3867 return NULL;
3869 if (view_is_hsplit_top(view))
3870 --eos; /* border consumes the last line */
3872 if (!page) {
3873 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3874 ++s->selected;
3875 else
3876 err = log_scroll_down(view, 1);
3877 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3878 struct commit_queue_entry *entry;
3879 int n;
3881 s->selected = 0;
3882 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3883 s->last_displayed_entry = entry;
3884 for (n = 0; n <= eos; n++) {
3885 if (entry == NULL)
3886 break;
3887 s->first_displayed_entry = entry;
3888 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3890 if (n > 0)
3891 s->selected = n - 1;
3892 } else {
3893 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3894 s->thread_args.log_complete)
3895 s->selected += MIN(page,
3896 s->commits->ncommits - s->selected_entry->idx - 1);
3897 else
3898 err = log_scroll_down(view, page);
3900 if (err)
3901 return err;
3904 * We might necessarily overshoot in horizontal
3905 * splits; if so, select the last displayed commit.
3907 if (s->first_displayed_entry && s->last_displayed_entry) {
3908 s->selected = MIN(s->selected,
3909 s->last_displayed_entry->idx -
3910 s->first_displayed_entry->idx);
3913 select_commit(s);
3915 if (s->thread_args.log_complete &&
3916 s->selected_entry->idx == s->commits->ncommits - 1)
3917 view->count = 0;
3919 return NULL;
3922 static void
3923 view_get_split(struct tog_view *view, int *y, int *x)
3925 *x = 0;
3926 *y = 0;
3928 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3929 if (view->child && view->child->resized_y)
3930 *y = view->child->resized_y;
3931 else if (view->resized_y)
3932 *y = view->resized_y;
3933 else
3934 *y = view_split_begin_y(view->lines);
3935 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3936 if (view->child && view->child->resized_x)
3937 *x = view->child->resized_x;
3938 else if (view->resized_x)
3939 *x = view->resized_x;
3940 else
3941 *x = view_split_begin_x(view->begin_x);
3945 /* Split view horizontally at y and offset view->state->selected line. */
3946 static const struct got_error *
3947 view_init_hsplit(struct tog_view *view, int y)
3949 const struct got_error *err = NULL;
3951 view->nlines = y;
3952 view->ncols = COLS;
3953 err = view_resize(view);
3954 if (err)
3955 return err;
3957 err = offset_selection_down(view);
3959 return err;
3962 static const struct got_error *
3963 log_goto_line(struct tog_view *view, int nlines)
3965 const struct got_error *err = NULL;
3966 struct tog_log_view_state *s = &view->state.log;
3967 int g, idx = s->selected_entry->idx;
3969 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3970 return NULL;
3972 g = view->gline;
3973 view->gline = 0;
3975 if (g >= s->first_displayed_entry->idx + 1 &&
3976 g <= s->last_displayed_entry->idx + 1 &&
3977 g - s->first_displayed_entry->idx - 1 < nlines) {
3978 s->selected = g - s->first_displayed_entry->idx - 1;
3979 select_commit(s);
3980 return NULL;
3983 if (idx + 1 < g) {
3984 err = log_move_cursor_down(view, g - idx - 1);
3985 if (!err && g > s->selected_entry->idx + 1)
3986 err = log_move_cursor_down(view,
3987 g - s->first_displayed_entry->idx - 1);
3988 if (err)
3989 return err;
3990 } else if (idx + 1 > g)
3991 log_move_cursor_up(view, idx - g + 1, 0);
3993 if (g < nlines && s->first_displayed_entry->idx == 0)
3994 s->selected = g - 1;
3996 select_commit(s);
3997 return NULL;
4001 static void
4002 horizontal_scroll_input(struct tog_view *view, int ch)
4005 switch (ch) {
4006 case KEY_LEFT:
4007 case 'h':
4008 view->x -= MIN(view->x, 2);
4009 if (view->x <= 0)
4010 view->count = 0;
4011 break;
4012 case KEY_RIGHT:
4013 case 'l':
4014 if (view->x + view->ncols / 2 < view->maxx)
4015 view->x += 2;
4016 else
4017 view->count = 0;
4018 break;
4019 case '0':
4020 view->x = 0;
4021 break;
4022 case '$':
4023 view->x = MAX(view->maxx - view->ncols / 2, 0);
4024 view->count = 0;
4025 break;
4026 default:
4027 break;
4031 static const struct got_error *
4032 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
4034 const struct got_error *err = NULL;
4035 struct tog_log_view_state *s = &view->state.log;
4036 int eos, nscroll;
4038 if (s->thread_args.load_all) {
4039 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
4040 s->thread_args.load_all = 0;
4041 else if (s->thread_args.log_complete) {
4042 err = log_move_cursor_down(view, s->commits->ncommits);
4043 s->thread_args.load_all = 0;
4045 if (err)
4046 return err;
4049 eos = nscroll = view->nlines - 1;
4050 if (view_is_hsplit_top(view))
4051 --eos; /* border */
4053 if (view->gline)
4054 return log_goto_line(view, eos);
4056 switch (ch) {
4057 case '&':
4058 err = limit_log_view(view);
4059 break;
4060 case 'q':
4061 s->quit = 1;
4062 break;
4063 case '0':
4064 case '$':
4065 case KEY_RIGHT:
4066 case 'l':
4067 case KEY_LEFT:
4068 case 'h':
4069 horizontal_scroll_input(view, ch);
4070 break;
4071 case 'k':
4072 case KEY_UP:
4073 case '<':
4074 case ',':
4075 case CTRL('p'):
4076 log_move_cursor_up(view, 0, 0);
4077 break;
4078 case 'g':
4079 case '=':
4080 case KEY_HOME:
4081 log_move_cursor_up(view, 0, 1);
4082 view->count = 0;
4083 break;
4084 case CTRL('u'):
4085 case 'u':
4086 nscroll /= 2;
4087 /* FALL THROUGH */
4088 case KEY_PPAGE:
4089 case CTRL('b'):
4090 case 'b':
4091 log_move_cursor_up(view, nscroll, 0);
4092 break;
4093 case 'j':
4094 case KEY_DOWN:
4095 case '>':
4096 case '.':
4097 case CTRL('n'):
4098 err = log_move_cursor_down(view, 0);
4099 break;
4100 case '@':
4101 s->use_committer = !s->use_committer;
4102 view->action = s->use_committer ?
4103 "show committer" : "show commit author";
4104 break;
4105 case 'G':
4106 case '*':
4107 case KEY_END: {
4108 /* We don't know yet how many commits, so we're forced to
4109 * traverse them all. */
4110 view->count = 0;
4111 s->thread_args.load_all = 1;
4112 if (!s->thread_args.log_complete)
4113 return trigger_log_thread(view, 0);
4114 err = log_move_cursor_down(view, s->commits->ncommits);
4115 s->thread_args.load_all = 0;
4116 break;
4118 case CTRL('d'):
4119 case 'd':
4120 nscroll /= 2;
4121 /* FALL THROUGH */
4122 case KEY_NPAGE:
4123 case CTRL('f'):
4124 case 'f':
4125 case ' ':
4126 err = log_move_cursor_down(view, nscroll);
4127 break;
4128 case KEY_RESIZE:
4129 if (s->selected > view->nlines - 2)
4130 s->selected = view->nlines - 2;
4131 if (s->selected > s->commits->ncommits - 1)
4132 s->selected = s->commits->ncommits - 1;
4133 select_commit(s);
4134 if (s->commits->ncommits < view->nlines - 1 &&
4135 !s->thread_args.log_complete) {
4136 s->thread_args.commits_needed += (view->nlines - 1) -
4137 s->commits->ncommits;
4138 err = trigger_log_thread(view, 1);
4140 break;
4141 case KEY_ENTER:
4142 case '\r':
4143 view->count = 0;
4144 if (s->selected_entry == NULL)
4145 break;
4146 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4147 break;
4148 case 'T':
4149 view->count = 0;
4150 if (s->selected_entry == NULL)
4151 break;
4152 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4153 break;
4154 case KEY_BACKSPACE:
4155 case CTRL('l'):
4156 case 'B':
4157 view->count = 0;
4158 if (ch == KEY_BACKSPACE &&
4159 got_path_is_root_dir(s->in_repo_path))
4160 break;
4161 err = stop_log_thread(s);
4162 if (err)
4163 return err;
4164 if (ch == KEY_BACKSPACE) {
4165 char *parent_path;
4166 err = got_path_dirname(&parent_path, s->in_repo_path);
4167 if (err)
4168 return err;
4169 free(s->in_repo_path);
4170 s->in_repo_path = parent_path;
4171 s->thread_args.in_repo_path = s->in_repo_path;
4172 } else if (ch == CTRL('l')) {
4173 struct got_object_id *start_id;
4174 err = got_repo_match_object_id(&start_id, NULL,
4175 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4176 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4177 if (err) {
4178 if (s->head_ref_name == NULL ||
4179 err->code != GOT_ERR_NOT_REF)
4180 return err;
4181 /* Try to cope with deleted references. */
4182 free(s->head_ref_name);
4183 s->head_ref_name = NULL;
4184 err = got_repo_match_object_id(&start_id,
4185 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4186 &tog_refs, s->repo);
4187 if (err)
4188 return err;
4190 free(s->start_id);
4191 s->start_id = start_id;
4192 s->thread_args.start_id = s->start_id;
4193 } else /* 'B' */
4194 s->log_branches = !s->log_branches;
4196 if (s->thread_args.pack_fds == NULL) {
4197 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4198 if (err)
4199 return err;
4201 err = got_repo_open(&s->thread_args.repo,
4202 got_repo_get_path(s->repo), NULL,
4203 s->thread_args.pack_fds);
4204 if (err)
4205 return err;
4206 tog_free_refs();
4207 err = tog_load_refs(s->repo, 0);
4208 if (err)
4209 return err;
4210 err = got_commit_graph_open(&s->thread_args.graph,
4211 s->in_repo_path, !s->log_branches);
4212 if (err)
4213 return err;
4214 err = got_commit_graph_iter_start(s->thread_args.graph,
4215 s->start_id, s->repo, NULL, NULL);
4216 if (err)
4217 return err;
4218 free_commits(&s->real_commits);
4219 free_commits(&s->limit_commits);
4220 s->first_displayed_entry = NULL;
4221 s->last_displayed_entry = NULL;
4222 s->selected_entry = NULL;
4223 s->selected = 0;
4224 s->thread_args.log_complete = 0;
4225 s->quit = 0;
4226 s->thread_args.commits_needed = view->lines;
4227 s->matched_entry = NULL;
4228 s->search_entry = NULL;
4229 view->offset = 0;
4230 break;
4231 case 'R':
4232 view->count = 0;
4233 err = view_request_new(new_view, view, TOG_VIEW_REF);
4234 break;
4235 default:
4236 view->count = 0;
4237 break;
4240 return err;
4243 static const struct got_error *
4244 apply_unveil(const char *repo_path, const char *worktree_path)
4246 const struct got_error *error;
4248 #ifdef PROFILE
4249 if (unveil("gmon.out", "rwc") != 0)
4250 return got_error_from_errno2("unveil", "gmon.out");
4251 #endif
4252 if (repo_path && unveil(repo_path, "r") != 0)
4253 return got_error_from_errno2("unveil", repo_path);
4255 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4256 return got_error_from_errno2("unveil", worktree_path);
4258 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4259 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4261 error = got_privsep_unveil_exec_helpers();
4262 if (error != NULL)
4263 return error;
4265 if (unveil(NULL, NULL) != 0)
4266 return got_error_from_errno("unveil");
4268 return NULL;
4271 static const struct got_error *
4272 init_mock_term(const char *test_script_path)
4274 const struct got_error *err = NULL;
4275 const char *screen_dump_path;
4276 int in;
4278 if (test_script_path == NULL || *test_script_path == '\0')
4279 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4281 tog_io.f = fopen(test_script_path, "re");
4282 if (tog_io.f == NULL) {
4283 err = got_error_from_errno_fmt("fopen: %s",
4284 test_script_path);
4285 goto done;
4288 /* test mode, we don't want any output */
4289 tog_io.cout = fopen("/dev/null", "w+");
4290 if (tog_io.cout == NULL) {
4291 err = got_error_from_errno2("fopen", "/dev/null");
4292 goto done;
4295 in = dup(fileno(tog_io.cout));
4296 if (in == -1) {
4297 err = got_error_from_errno("dup");
4298 goto done;
4300 tog_io.cin = fdopen(in, "r");
4301 if (tog_io.cin == NULL) {
4302 err = got_error_from_errno("fdopen");
4303 close(in);
4304 goto done;
4307 screen_dump_path = getenv("TOG_SCR_DUMP");
4308 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4309 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4310 tog_io.sdump = fopen(screen_dump_path, "we");
4311 if (tog_io.sdump == NULL) {
4312 err = got_error_from_errno2("fopen", screen_dump_path);
4313 goto done;
4316 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4317 err = got_error_from_errno("fseeko");
4318 goto done;
4321 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4322 err = got_error_msg(GOT_ERR_IO,
4323 "newterm: failed to initialise curses");
4325 using_mock_io = 1;
4327 done:
4328 if (err)
4329 tog_io_close();
4330 return err;
4333 static void
4334 init_curses(void)
4337 * Override default signal handlers before starting ncurses.
4338 * This should prevent ncurses from installing its own
4339 * broken cleanup() signal handler.
4341 signal(SIGWINCH, tog_sigwinch);
4342 signal(SIGPIPE, tog_sigpipe);
4343 signal(SIGCONT, tog_sigcont);
4344 signal(SIGINT, tog_sigint);
4345 signal(SIGTERM, tog_sigterm);
4347 if (using_mock_io) /* In test mode we use a fake terminal */
4348 return;
4350 initscr();
4352 cbreak();
4353 halfdelay(1); /* Fast refresh while initial view is loading. */
4354 noecho();
4355 nonl();
4356 intrflush(stdscr, FALSE);
4357 keypad(stdscr, TRUE);
4358 curs_set(0);
4359 if (getenv("TOG_COLORS") != NULL) {
4360 start_color();
4361 use_default_colors();
4364 return;
4367 static const struct got_error *
4368 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4369 struct got_repository *repo, struct got_worktree *worktree)
4371 const struct got_error *err = NULL;
4373 if (argc == 0) {
4374 *in_repo_path = strdup("/");
4375 if (*in_repo_path == NULL)
4376 return got_error_from_errno("strdup");
4377 return NULL;
4380 if (worktree) {
4381 const char *prefix = got_worktree_get_path_prefix(worktree);
4382 char *p;
4384 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4385 if (err)
4386 return err;
4387 if (asprintf(in_repo_path, "%s%s%s", prefix,
4388 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4389 p) == -1) {
4390 err = got_error_from_errno("asprintf");
4391 *in_repo_path = NULL;
4393 free(p);
4394 } else
4395 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4397 return err;
4400 static const struct got_error *
4401 cmd_log(int argc, char *argv[])
4403 const struct got_error *error;
4404 struct got_repository *repo = NULL;
4405 struct got_worktree *worktree = NULL;
4406 struct got_object_id *start_id = NULL;
4407 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4408 char *keyword_idstr = NULL, *start_commit = NULL, *label = NULL;
4409 struct got_reference *ref = NULL;
4410 const char *head_ref_name = NULL;
4411 int ch, log_branches = 0;
4412 struct tog_view *view;
4413 int *pack_fds = NULL;
4415 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4416 switch (ch) {
4417 case 'b':
4418 log_branches = 1;
4419 break;
4420 case 'c':
4421 start_commit = optarg;
4422 break;
4423 case 'r':
4424 repo_path = realpath(optarg, NULL);
4425 if (repo_path == NULL)
4426 return got_error_from_errno2("realpath",
4427 optarg);
4428 break;
4429 default:
4430 usage_log();
4431 /* NOTREACHED */
4435 argc -= optind;
4436 argv += optind;
4438 if (argc > 1)
4439 usage_log();
4441 error = got_repo_pack_fds_open(&pack_fds);
4442 if (error != NULL)
4443 goto done;
4445 if (repo_path == NULL) {
4446 cwd = getcwd(NULL, 0);
4447 if (cwd == NULL)
4448 return got_error_from_errno("getcwd");
4449 error = got_worktree_open(&worktree, cwd, NULL);
4450 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4451 goto done;
4452 if (worktree)
4453 repo_path =
4454 strdup(got_worktree_get_repo_path(worktree));
4455 else
4456 repo_path = strdup(cwd);
4457 if (repo_path == NULL) {
4458 error = got_error_from_errno("strdup");
4459 goto done;
4463 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4464 if (error != NULL)
4465 goto done;
4467 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4468 repo, worktree);
4469 if (error)
4470 goto done;
4472 init_curses();
4474 error = apply_unveil(got_repo_get_path(repo),
4475 worktree ? got_worktree_get_root_path(worktree) : NULL);
4476 if (error)
4477 goto done;
4479 /* already loaded by tog_log_with_path()? */
4480 if (TAILQ_EMPTY(&tog_refs)) {
4481 error = tog_load_refs(repo, 0);
4482 if (error)
4483 goto done;
4486 if (start_commit == NULL) {
4487 error = got_repo_match_object_id(&start_id, &label,
4488 worktree ? got_worktree_get_head_ref_name(worktree) :
4489 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4490 if (error)
4491 goto done;
4492 head_ref_name = label;
4493 } else {
4494 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4495 repo, worktree);
4496 if (error != NULL)
4497 goto done;
4498 if (keyword_idstr != NULL)
4499 start_commit = keyword_idstr;
4501 error = got_ref_open(&ref, repo, start_commit, 0);
4502 if (error == NULL)
4503 head_ref_name = got_ref_get_name(ref);
4504 else if (error->code != GOT_ERR_NOT_REF)
4505 goto done;
4506 error = got_repo_match_object_id(&start_id, NULL,
4507 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4508 if (error)
4509 goto done;
4512 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4513 if (view == NULL) {
4514 error = got_error_from_errno("view_open");
4515 goto done;
4517 error = open_log_view(view, start_id, repo, head_ref_name,
4518 in_repo_path, log_branches);
4519 if (error)
4520 goto done;
4521 if (worktree) {
4522 /* Release work tree lock. */
4523 got_worktree_close(worktree);
4524 worktree = NULL;
4526 error = view_loop(view);
4527 done:
4528 free(keyword_idstr);
4529 free(in_repo_path);
4530 free(repo_path);
4531 free(cwd);
4532 free(start_id);
4533 free(label);
4534 if (ref)
4535 got_ref_close(ref);
4536 if (repo) {
4537 const struct got_error *close_err = got_repo_close(repo);
4538 if (error == NULL)
4539 error = close_err;
4541 if (worktree)
4542 got_worktree_close(worktree);
4543 if (pack_fds) {
4544 const struct got_error *pack_err =
4545 got_repo_pack_fds_close(pack_fds);
4546 if (error == NULL)
4547 error = pack_err;
4549 tog_free_refs();
4550 return error;
4553 __dead static void
4554 usage_diff(void)
4556 endwin();
4557 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4558 "object1 object2\n", getprogname());
4559 exit(1);
4562 static int
4563 match_line(const char *line, regex_t *regex, size_t nmatch,
4564 regmatch_t *regmatch)
4566 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4569 static struct tog_color *
4570 match_color(struct tog_colors *colors, const char *line)
4572 struct tog_color *tc = NULL;
4574 STAILQ_FOREACH(tc, colors, entry) {
4575 if (match_line(line, &tc->regex, 0, NULL))
4576 return tc;
4579 return NULL;
4582 static const struct got_error *
4583 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4584 WINDOW *window, int skipcol, regmatch_t *regmatch)
4586 const struct got_error *err = NULL;
4587 char *exstr = NULL;
4588 wchar_t *wline = NULL;
4589 int rme, rms, n, width, scrollx;
4590 int width0 = 0, width1 = 0, width2 = 0;
4591 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4593 *wtotal = 0;
4595 rms = regmatch->rm_so;
4596 rme = regmatch->rm_eo;
4598 err = expand_tab(&exstr, line);
4599 if (err)
4600 return err;
4602 /* Split the line into 3 segments, according to match offsets. */
4603 seg0 = strndup(exstr, rms);
4604 if (seg0 == NULL) {
4605 err = got_error_from_errno("strndup");
4606 goto done;
4608 seg1 = strndup(exstr + rms, rme - rms);
4609 if (seg1 == NULL) {
4610 err = got_error_from_errno("strndup");
4611 goto done;
4613 seg2 = strdup(exstr + rme);
4614 if (seg2 == NULL) {
4615 err = got_error_from_errno("strndup");
4616 goto done;
4619 /* draw up to matched token if we haven't scrolled past it */
4620 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4621 col_tab_align, 1);
4622 if (err)
4623 goto done;
4624 n = MAX(width0 - skipcol, 0);
4625 if (n) {
4626 free(wline);
4627 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4628 wlimit, col_tab_align, 1);
4629 if (err)
4630 goto done;
4631 waddwstr(window, &wline[scrollx]);
4632 wlimit -= width;
4633 *wtotal += width;
4636 if (wlimit > 0) {
4637 int i = 0, w = 0;
4638 size_t wlen;
4640 free(wline);
4641 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4642 col_tab_align, 1);
4643 if (err)
4644 goto done;
4645 wlen = wcslen(wline);
4646 while (i < wlen) {
4647 width = wcwidth(wline[i]);
4648 if (width == -1) {
4649 /* should not happen, tabs are expanded */
4650 err = got_error(GOT_ERR_RANGE);
4651 goto done;
4653 if (width0 + w + width > skipcol)
4654 break;
4655 w += width;
4656 i++;
4658 /* draw (visible part of) matched token (if scrolled into it) */
4659 if (width1 - w > 0) {
4660 wattron(window, A_STANDOUT);
4661 waddwstr(window, &wline[i]);
4662 wattroff(window, A_STANDOUT);
4663 wlimit -= (width1 - w);
4664 *wtotal += (width1 - w);
4668 if (wlimit > 0) { /* draw rest of line */
4669 free(wline);
4670 if (skipcol > width0 + width1) {
4671 err = format_line(&wline, &width2, &scrollx, seg2,
4672 skipcol - (width0 + width1), wlimit,
4673 col_tab_align, 1);
4674 if (err)
4675 goto done;
4676 waddwstr(window, &wline[scrollx]);
4677 } else {
4678 err = format_line(&wline, &width2, NULL, seg2, 0,
4679 wlimit, col_tab_align, 1);
4680 if (err)
4681 goto done;
4682 waddwstr(window, wline);
4684 *wtotal += width2;
4686 done:
4687 free(wline);
4688 free(exstr);
4689 free(seg0);
4690 free(seg1);
4691 free(seg2);
4692 return err;
4695 static int
4696 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4698 FILE *f = NULL;
4699 int *eof, *first, *selected;
4701 if (view->type == TOG_VIEW_DIFF) {
4702 struct tog_diff_view_state *s = &view->state.diff;
4704 first = &s->first_displayed_line;
4705 selected = first;
4706 eof = &s->eof;
4707 f = s->f;
4708 } else if (view->type == TOG_VIEW_HELP) {
4709 struct tog_help_view_state *s = &view->state.help;
4711 first = &s->first_displayed_line;
4712 selected = first;
4713 eof = &s->eof;
4714 f = s->f;
4715 } else if (view->type == TOG_VIEW_BLAME) {
4716 struct tog_blame_view_state *s = &view->state.blame;
4718 first = &s->first_displayed_line;
4719 selected = &s->selected_line;
4720 eof = &s->eof;
4721 f = s->blame.f;
4722 } else
4723 return 0;
4725 /* Center gline in the middle of the page like vi(1). */
4726 if (*lineno < view->gline - (view->nlines - 3) / 2)
4727 return 0;
4728 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4729 rewind(f);
4730 *eof = 0;
4731 *first = 1;
4732 *lineno = 0;
4733 *nprinted = 0;
4734 return 0;
4737 *selected = view->gline <= (view->nlines - 3) / 2 ?
4738 view->gline : (view->nlines - 3) / 2 + 1;
4739 view->gline = 0;
4741 return 1;
4744 static const struct got_error *
4745 draw_file(struct tog_view *view, const char *header)
4747 struct tog_diff_view_state *s = &view->state.diff;
4748 regmatch_t *regmatch = &view->regmatch;
4749 const struct got_error *err;
4750 int nprinted = 0;
4751 char *line;
4752 size_t linesize = 0;
4753 ssize_t linelen;
4754 wchar_t *wline;
4755 int width;
4756 int max_lines = view->nlines;
4757 int nlines = s->nlines;
4758 off_t line_offset;
4760 s->lineno = s->first_displayed_line - 1;
4761 line_offset = s->lines[s->first_displayed_line - 1].offset;
4762 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4763 return got_error_from_errno("fseek");
4765 werase(view->window);
4767 if (view->gline > s->nlines - 1)
4768 view->gline = s->nlines - 1;
4770 if (header) {
4771 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4772 1 : view->gline - (view->nlines - 3) / 2 :
4773 s->lineno + s->selected_line;
4775 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4776 return got_error_from_errno("asprintf");
4777 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4778 0, 0);
4779 free(line);
4780 if (err)
4781 return err;
4783 if (view_needs_focus_indication(view))
4784 wstandout(view->window);
4785 waddwstr(view->window, wline);
4786 free(wline);
4787 wline = NULL;
4788 while (width++ < view->ncols)
4789 waddch(view->window, ' ');
4790 if (view_needs_focus_indication(view))
4791 wstandend(view->window);
4793 if (max_lines <= 1)
4794 return NULL;
4795 max_lines--;
4798 s->eof = 0;
4799 view->maxx = 0;
4800 line = NULL;
4801 while (max_lines > 0 && nprinted < max_lines) {
4802 enum got_diff_line_type linetype;
4803 attr_t attr = 0;
4805 linelen = getline(&line, &linesize, s->f);
4806 if (linelen == -1) {
4807 if (feof(s->f)) {
4808 s->eof = 1;
4809 break;
4811 free(line);
4812 return got_ferror(s->f, GOT_ERR_IO);
4815 if (++s->lineno < s->first_displayed_line)
4816 continue;
4817 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4818 continue;
4819 if (s->lineno == view->hiline)
4820 attr = A_STANDOUT;
4822 /* Set view->maxx based on full line length. */
4823 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4824 view->x ? 1 : 0);
4825 if (err) {
4826 free(line);
4827 return err;
4829 view->maxx = MAX(view->maxx, width);
4830 free(wline);
4831 wline = NULL;
4833 linetype = s->lines[s->lineno].type;
4834 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4835 linetype < GOT_DIFF_LINE_CONTEXT)
4836 attr |= COLOR_PAIR(linetype);
4837 if (attr)
4838 wattron(view->window, attr);
4839 if (s->first_displayed_line + nprinted == s->matched_line &&
4840 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4841 err = add_matched_line(&width, line, view->ncols, 0,
4842 view->window, view->x, regmatch);
4843 if (err) {
4844 free(line);
4845 return err;
4847 } else {
4848 int skip;
4849 err = format_line(&wline, &width, &skip, line,
4850 view->x, view->ncols, 0, view->x ? 1 : 0);
4851 if (err) {
4852 free(line);
4853 return err;
4855 waddwstr(view->window, &wline[skip]);
4856 free(wline);
4857 wline = NULL;
4859 if (s->lineno == view->hiline) {
4860 /* highlight full gline length */
4861 while (width++ < view->ncols)
4862 waddch(view->window, ' ');
4863 } else {
4864 if (width <= view->ncols - 1)
4865 waddch(view->window, '\n');
4867 if (attr)
4868 wattroff(view->window, attr);
4869 if (++nprinted == 1)
4870 s->first_displayed_line = s->lineno;
4872 free(line);
4873 if (nprinted >= 1)
4874 s->last_displayed_line = s->first_displayed_line +
4875 (nprinted - 1);
4876 else
4877 s->last_displayed_line = s->first_displayed_line;
4879 view_border(view);
4881 if (s->eof) {
4882 while (nprinted < view->nlines) {
4883 waddch(view->window, '\n');
4884 nprinted++;
4887 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4888 view->ncols, 0, 0);
4889 if (err) {
4890 return err;
4893 wstandout(view->window);
4894 waddwstr(view->window, wline);
4895 free(wline);
4896 wline = NULL;
4897 wstandend(view->window);
4900 return NULL;
4903 static char *
4904 get_datestr(time_t *time, char *datebuf)
4906 struct tm mytm, *tm;
4907 char *p, *s;
4909 tm = gmtime_r(time, &mytm);
4910 if (tm == NULL)
4911 return NULL;
4912 s = asctime_r(tm, datebuf);
4913 if (s == NULL)
4914 return NULL;
4915 p = strchr(s, '\n');
4916 if (p)
4917 *p = '\0';
4918 return s;
4921 static const struct got_error *
4922 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4923 off_t off, uint8_t type)
4925 struct got_diff_line *p;
4927 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4928 if (p == NULL)
4929 return got_error_from_errno("reallocarray");
4930 *lines = p;
4931 (*lines)[*nlines].offset = off;
4932 (*lines)[*nlines].type = type;
4933 (*nlines)++;
4935 return NULL;
4938 static const struct got_error *
4939 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4940 struct got_diff_line *s_lines, size_t s_nlines)
4942 struct got_diff_line *p;
4943 char buf[BUFSIZ];
4944 size_t i, r;
4946 if (fseeko(src, 0L, SEEK_SET) == -1)
4947 return got_error_from_errno("fseeko");
4949 for (;;) {
4950 r = fread(buf, 1, sizeof(buf), src);
4951 if (r == 0) {
4952 if (ferror(src))
4953 return got_error_from_errno("fread");
4954 if (feof(src))
4955 break;
4957 if (fwrite(buf, 1, r, dst) != r)
4958 return got_ferror(dst, GOT_ERR_IO);
4961 if (s_nlines == 0 && *d_nlines == 0)
4962 return NULL;
4965 * If commit info was in dst, increment line offsets
4966 * of the appended diff content, but skip s_lines[0]
4967 * because offset zero is already in *d_lines.
4969 if (*d_nlines > 0) {
4970 for (i = 1; i < s_nlines; ++i)
4971 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4973 if (s_nlines > 0) {
4974 --s_nlines;
4975 ++s_lines;
4979 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4980 if (p == NULL) {
4981 /* d_lines is freed in close_diff_view() */
4982 return got_error_from_errno("reallocarray");
4985 *d_lines = p;
4987 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4988 *d_nlines += s_nlines;
4990 return NULL;
4993 static const struct got_error *
4994 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4995 struct got_object_id *commit_id, struct got_reflist_head *refs,
4996 struct got_repository *repo, int ignore_ws, int force_text_diff,
4997 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4999 const struct got_error *err = NULL;
5000 char datebuf[26], *datestr;
5001 struct got_commit_object *commit;
5002 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
5003 time_t committer_time;
5004 const char *author, *committer;
5005 char *refs_str = NULL;
5006 struct got_pathlist_entry *pe;
5007 off_t outoff = 0;
5008 int n;
5010 err = build_refs_str(&refs_str, refs, commit_id, repo);
5011 if (err)
5012 return err;
5014 err = got_object_open_as_commit(&commit, repo, commit_id);
5015 if (err)
5016 return err;
5018 err = got_object_id_str(&id_str, commit_id);
5019 if (err) {
5020 err = got_error_from_errno("got_object_id_str");
5021 goto done;
5024 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
5025 if (err)
5026 goto done;
5028 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
5029 refs_str ? refs_str : "", refs_str ? ")" : "");
5030 if (n < 0) {
5031 err = got_error_from_errno("fprintf");
5032 goto done;
5034 outoff += n;
5035 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
5036 if (err)
5037 goto done;
5039 n = fprintf(outfile, "from: %s\n",
5040 got_object_commit_get_author(commit));
5041 if (n < 0) {
5042 err = got_error_from_errno("fprintf");
5043 goto done;
5045 outoff += n;
5046 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
5047 if (err)
5048 goto done;
5050 author = got_object_commit_get_author(commit);
5051 committer = got_object_commit_get_committer(commit);
5052 if (strcmp(author, committer) != 0) {
5053 n = fprintf(outfile, "via: %s\n", committer);
5054 if (n < 0) {
5055 err = got_error_from_errno("fprintf");
5056 goto done;
5058 outoff += n;
5059 err = add_line_metadata(lines, nlines, outoff,
5060 GOT_DIFF_LINE_AUTHOR);
5061 if (err)
5062 goto done;
5064 committer_time = got_object_commit_get_committer_time(commit);
5065 datestr = get_datestr(&committer_time, datebuf);
5066 if (datestr) {
5067 n = fprintf(outfile, "date: %s UTC\n", datestr);
5068 if (n < 0) {
5069 err = got_error_from_errno("fprintf");
5070 goto done;
5072 outoff += n;
5073 err = add_line_metadata(lines, nlines, outoff,
5074 GOT_DIFF_LINE_DATE);
5075 if (err)
5076 goto done;
5078 if (got_object_commit_get_nparents(commit) > 1) {
5079 const struct got_object_id_queue *parent_ids;
5080 struct got_object_qid *qid;
5081 int pn = 1;
5082 parent_ids = got_object_commit_get_parent_ids(commit);
5083 STAILQ_FOREACH(qid, parent_ids, entry) {
5084 err = got_object_id_str(&id_str, &qid->id);
5085 if (err)
5086 goto done;
5087 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5088 if (n < 0) {
5089 err = got_error_from_errno("fprintf");
5090 goto done;
5092 outoff += n;
5093 err = add_line_metadata(lines, nlines, outoff,
5094 GOT_DIFF_LINE_META);
5095 if (err)
5096 goto done;
5097 free(id_str);
5098 id_str = NULL;
5102 err = got_object_commit_get_logmsg(&logmsg, commit);
5103 if (err)
5104 goto done;
5105 s = logmsg;
5106 while ((line = strsep(&s, "\n")) != NULL) {
5107 n = fprintf(outfile, "%s\n", line);
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_LOGMSG);
5115 if (err)
5116 goto done;
5119 TAILQ_FOREACH(pe, dsa->paths, entry) {
5120 struct got_diff_changed_path *cp = pe->data;
5121 int pad = dsa->max_path_len - pe->path_len + 1;
5123 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5124 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5125 dsa->rm_cols + 1, cp->rm);
5126 if (n < 0) {
5127 err = got_error_from_errno("fprintf");
5128 goto done;
5130 outoff += n;
5131 err = add_line_metadata(lines, nlines, outoff,
5132 GOT_DIFF_LINE_CHANGES);
5133 if (err)
5134 goto done;
5137 fputc('\n', outfile);
5138 outoff++;
5139 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5140 if (err)
5141 goto done;
5143 n = fprintf(outfile,
5144 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5145 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5146 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5147 if (n < 0) {
5148 err = got_error_from_errno("fprintf");
5149 goto done;
5151 outoff += n;
5152 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5153 if (err)
5154 goto done;
5156 fputc('\n', outfile);
5157 outoff++;
5158 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5159 done:
5160 free(id_str);
5161 free(logmsg);
5162 free(refs_str);
5163 got_object_commit_close(commit);
5164 if (err) {
5165 free(*lines);
5166 *lines = NULL;
5167 *nlines = 0;
5169 return err;
5172 static const struct got_error *
5173 create_diff(struct tog_diff_view_state *s)
5175 const struct got_error *err = NULL;
5176 FILE *f = NULL, *tmp_diff_file = NULL;
5177 int obj_type;
5178 struct got_diff_line *lines = NULL;
5179 struct got_pathlist_head changed_paths;
5181 TAILQ_INIT(&changed_paths);
5183 free(s->lines);
5184 s->lines = malloc(sizeof(*s->lines));
5185 if (s->lines == NULL)
5186 return got_error_from_errno("malloc");
5187 s->nlines = 0;
5189 f = got_opentemp();
5190 if (f == NULL) {
5191 err = got_error_from_errno("got_opentemp");
5192 goto done;
5194 tmp_diff_file = got_opentemp();
5195 if (tmp_diff_file == NULL) {
5196 err = got_error_from_errno("got_opentemp");
5197 goto done;
5199 if (s->f && fclose(s->f) == EOF) {
5200 err = got_error_from_errno("fclose");
5201 goto done;
5203 s->f = f;
5205 if (s->id1)
5206 err = got_object_get_type(&obj_type, s->repo, s->id1);
5207 else
5208 err = got_object_get_type(&obj_type, s->repo, s->id2);
5209 if (err)
5210 goto done;
5212 switch (obj_type) {
5213 case GOT_OBJ_TYPE_BLOB:
5214 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5215 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5216 s->label1, s->label2, tog_diff_algo, s->diff_context,
5217 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5218 s->f);
5219 break;
5220 case GOT_OBJ_TYPE_TREE:
5221 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5222 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5223 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5224 s->force_text_diff, NULL, s->repo, s->f);
5225 break;
5226 case GOT_OBJ_TYPE_COMMIT: {
5227 const struct got_object_id_queue *parent_ids;
5228 struct got_object_qid *pid;
5229 struct got_commit_object *commit2;
5230 struct got_reflist_head *refs;
5231 size_t nlines = 0;
5232 struct got_diffstat_cb_arg dsa = {
5233 0, 0, 0, 0, 0, 0,
5234 &changed_paths,
5235 s->ignore_whitespace,
5236 s->force_text_diff,
5237 tog_diff_algo
5240 lines = malloc(sizeof(*lines));
5241 if (lines == NULL) {
5242 err = got_error_from_errno("malloc");
5243 goto done;
5246 /* build diff first in tmp file then append to commit info */
5247 err = got_diff_objects_as_commits(&lines, &nlines,
5248 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5249 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5250 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5251 if (err)
5252 break;
5254 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5255 if (err)
5256 goto done;
5257 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5258 /* Show commit info if we're diffing to a parent/root commit. */
5259 if (s->id1 == NULL) {
5260 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5261 refs, s->repo, s->ignore_whitespace,
5262 s->force_text_diff, &dsa, s->f);
5263 if (err)
5264 goto done;
5265 } else {
5266 parent_ids = got_object_commit_get_parent_ids(commit2);
5267 STAILQ_FOREACH(pid, parent_ids, entry) {
5268 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5269 err = write_commit_info(&s->lines,
5270 &s->nlines, s->id2, refs, s->repo,
5271 s->ignore_whitespace,
5272 s->force_text_diff, &dsa, s->f);
5273 if (err)
5274 goto done;
5275 break;
5279 got_object_commit_close(commit2);
5281 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5282 lines, nlines);
5283 break;
5285 default:
5286 err = got_error(GOT_ERR_OBJ_TYPE);
5287 break;
5289 done:
5290 free(lines);
5291 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5292 if (s->f && fflush(s->f) != 0 && err == NULL)
5293 err = got_error_from_errno("fflush");
5294 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5295 err = got_error_from_errno("fclose");
5296 return err;
5299 static void
5300 diff_view_indicate_progress(struct tog_view *view)
5302 mvwaddstr(view->window, 0, 0, "diffing...");
5303 update_panels();
5304 doupdate();
5307 static const struct got_error *
5308 search_start_diff_view(struct tog_view *view)
5310 struct tog_diff_view_state *s = &view->state.diff;
5312 s->matched_line = 0;
5313 return NULL;
5316 static void
5317 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5318 size_t *nlines, int **first, int **last, int **match, int **selected)
5320 struct tog_diff_view_state *s = &view->state.diff;
5322 *f = s->f;
5323 *nlines = s->nlines;
5324 *line_offsets = NULL;
5325 *match = &s->matched_line;
5326 *first = &s->first_displayed_line;
5327 *last = &s->last_displayed_line;
5328 *selected = &s->selected_line;
5331 static const struct got_error *
5332 search_next_view_match(struct tog_view *view)
5334 const struct got_error *err = NULL;
5335 FILE *f;
5336 int lineno;
5337 char *line = NULL;
5338 size_t linesize = 0;
5339 ssize_t linelen;
5340 off_t *line_offsets;
5341 size_t nlines = 0;
5342 int *first, *last, *match, *selected;
5344 if (!view->search_setup)
5345 return got_error_msg(GOT_ERR_NOT_IMPL,
5346 "view search not supported");
5347 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5348 &match, &selected);
5350 if (!view->searching) {
5351 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5352 return NULL;
5355 if (*match) {
5356 if (view->searching == TOG_SEARCH_FORWARD)
5357 lineno = *first + 1;
5358 else
5359 lineno = *first - 1;
5360 } else
5361 lineno = *first - 1 + *selected;
5363 while (1) {
5364 off_t offset;
5366 if (lineno <= 0 || lineno > nlines) {
5367 if (*match == 0) {
5368 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5369 break;
5372 if (view->searching == TOG_SEARCH_FORWARD)
5373 lineno = 1;
5374 else
5375 lineno = nlines;
5378 offset = view->type == TOG_VIEW_DIFF ?
5379 view->state.diff.lines[lineno - 1].offset :
5380 line_offsets[lineno - 1];
5381 if (fseeko(f, offset, SEEK_SET) != 0) {
5382 free(line);
5383 return got_error_from_errno("fseeko");
5385 linelen = getline(&line, &linesize, f);
5386 if (linelen != -1) {
5387 char *exstr;
5388 err = expand_tab(&exstr, line);
5389 if (err)
5390 break;
5391 if (match_line(exstr, &view->regex, 1,
5392 &view->regmatch)) {
5393 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5394 *match = lineno;
5395 free(exstr);
5396 break;
5398 free(exstr);
5400 if (view->searching == TOG_SEARCH_FORWARD)
5401 lineno++;
5402 else
5403 lineno--;
5405 free(line);
5407 if (*match) {
5408 *first = *match;
5409 *selected = 1;
5412 return err;
5415 static const struct got_error *
5416 close_diff_view(struct tog_view *view)
5418 const struct got_error *err = NULL;
5419 struct tog_diff_view_state *s = &view->state.diff;
5421 free(s->id1);
5422 s->id1 = NULL;
5423 free(s->id2);
5424 s->id2 = NULL;
5425 if (s->f && fclose(s->f) == EOF)
5426 err = got_error_from_errno("fclose");
5427 s->f = NULL;
5428 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5429 err = got_error_from_errno("fclose");
5430 s->f1 = NULL;
5431 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5432 err = got_error_from_errno("fclose");
5433 s->f2 = NULL;
5434 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5435 err = got_error_from_errno("close");
5436 s->fd1 = -1;
5437 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5438 err = got_error_from_errno("close");
5439 s->fd2 = -1;
5440 free(s->lines);
5441 s->lines = NULL;
5442 s->nlines = 0;
5443 return err;
5446 static const struct got_error *
5447 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5448 struct got_object_id *id2, const char *label1, const char *label2,
5449 int diff_context, int ignore_whitespace, int force_text_diff,
5450 struct tog_view *parent_view, struct got_repository *repo)
5452 const struct got_error *err;
5453 struct tog_diff_view_state *s = &view->state.diff;
5455 memset(s, 0, sizeof(*s));
5456 s->fd1 = -1;
5457 s->fd2 = -1;
5459 if (id1 != NULL && id2 != NULL) {
5460 int type1, type2;
5462 err = got_object_get_type(&type1, repo, id1);
5463 if (err)
5464 goto done;
5465 err = got_object_get_type(&type2, repo, id2);
5466 if (err)
5467 goto done;
5469 if (type1 != type2) {
5470 err = got_error(GOT_ERR_OBJ_TYPE);
5471 goto done;
5474 s->first_displayed_line = 1;
5475 s->last_displayed_line = view->nlines;
5476 s->selected_line = 1;
5477 s->repo = repo;
5478 s->id1 = id1;
5479 s->id2 = id2;
5480 s->label1 = label1;
5481 s->label2 = label2;
5483 if (id1) {
5484 s->id1 = got_object_id_dup(id1);
5485 if (s->id1 == NULL) {
5486 err = got_error_from_errno("got_object_id_dup");
5487 goto done;
5489 } else
5490 s->id1 = NULL;
5492 s->id2 = got_object_id_dup(id2);
5493 if (s->id2 == NULL) {
5494 err = got_error_from_errno("got_object_id_dup");
5495 goto done;
5498 s->f1 = got_opentemp();
5499 if (s->f1 == NULL) {
5500 err = got_error_from_errno("got_opentemp");
5501 goto done;
5504 s->f2 = got_opentemp();
5505 if (s->f2 == NULL) {
5506 err = got_error_from_errno("got_opentemp");
5507 goto done;
5510 s->fd1 = got_opentempfd();
5511 if (s->fd1 == -1) {
5512 err = got_error_from_errno("got_opentempfd");
5513 goto done;
5516 s->fd2 = got_opentempfd();
5517 if (s->fd2 == -1) {
5518 err = got_error_from_errno("got_opentempfd");
5519 goto done;
5522 s->diff_context = diff_context;
5523 s->ignore_whitespace = ignore_whitespace;
5524 s->force_text_diff = force_text_diff;
5525 s->parent_view = parent_view;
5526 s->repo = repo;
5528 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5529 int rc;
5531 rc = init_pair(GOT_DIFF_LINE_MINUS,
5532 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5533 if (rc != ERR)
5534 rc = init_pair(GOT_DIFF_LINE_PLUS,
5535 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5536 if (rc != ERR)
5537 rc = init_pair(GOT_DIFF_LINE_HUNK,
5538 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5539 if (rc != ERR)
5540 rc = init_pair(GOT_DIFF_LINE_META,
5541 get_color_value("TOG_COLOR_DIFF_META"), -1);
5542 if (rc != ERR)
5543 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5544 get_color_value("TOG_COLOR_DIFF_META"), -1);
5545 if (rc != ERR)
5546 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5547 get_color_value("TOG_COLOR_DIFF_META"), -1);
5548 if (rc != ERR)
5549 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5550 get_color_value("TOG_COLOR_DIFF_META"), -1);
5551 if (rc != ERR)
5552 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5553 get_color_value("TOG_COLOR_AUTHOR"), -1);
5554 if (rc != ERR)
5555 rc = init_pair(GOT_DIFF_LINE_DATE,
5556 get_color_value("TOG_COLOR_DATE"), -1);
5557 if (rc == ERR) {
5558 err = got_error(GOT_ERR_RANGE);
5559 goto done;
5563 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5564 view_is_splitscreen(view))
5565 show_log_view(parent_view); /* draw border */
5566 diff_view_indicate_progress(view);
5568 err = create_diff(s);
5570 view->show = show_diff_view;
5571 view->input = input_diff_view;
5572 view->reset = reset_diff_view;
5573 view->close = close_diff_view;
5574 view->search_start = search_start_diff_view;
5575 view->search_setup = search_setup_diff_view;
5576 view->search_next = search_next_view_match;
5577 done:
5578 if (err) {
5579 if (view->close == NULL)
5580 close_diff_view(view);
5581 view_close(view);
5583 return err;
5586 static const struct got_error *
5587 show_diff_view(struct tog_view *view)
5589 const struct got_error *err;
5590 struct tog_diff_view_state *s = &view->state.diff;
5591 char *id_str1 = NULL, *id_str2, *header;
5592 const char *label1, *label2;
5594 if (s->id1) {
5595 err = got_object_id_str(&id_str1, s->id1);
5596 if (err)
5597 return err;
5598 label1 = s->label1 ? s->label1 : id_str1;
5599 } else
5600 label1 = "/dev/null";
5602 err = got_object_id_str(&id_str2, s->id2);
5603 if (err)
5604 return err;
5605 label2 = s->label2 ? s->label2 : id_str2;
5607 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5608 err = got_error_from_errno("asprintf");
5609 free(id_str1);
5610 free(id_str2);
5611 return err;
5613 free(id_str1);
5614 free(id_str2);
5616 err = draw_file(view, header);
5617 free(header);
5618 return err;
5621 static const struct got_error *
5622 set_selected_commit(struct tog_diff_view_state *s,
5623 struct commit_queue_entry *entry)
5625 const struct got_error *err;
5626 const struct got_object_id_queue *parent_ids;
5627 struct got_commit_object *selected_commit;
5628 struct got_object_qid *pid;
5630 free(s->id2);
5631 s->id2 = got_object_id_dup(entry->id);
5632 if (s->id2 == NULL)
5633 return got_error_from_errno("got_object_id_dup");
5635 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5636 if (err)
5637 return err;
5638 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5639 free(s->id1);
5640 pid = STAILQ_FIRST(parent_ids);
5641 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5642 got_object_commit_close(selected_commit);
5643 return NULL;
5646 static const struct got_error *
5647 reset_diff_view(struct tog_view *view)
5649 struct tog_diff_view_state *s = &view->state.diff;
5651 view->count = 0;
5652 wclear(view->window);
5653 s->first_displayed_line = 1;
5654 s->last_displayed_line = view->nlines;
5655 s->matched_line = 0;
5656 diff_view_indicate_progress(view);
5657 return create_diff(s);
5660 static void
5661 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5663 int start, i;
5665 i = start = s->first_displayed_line - 1;
5667 while (s->lines[i].type != type) {
5668 if (i == 0)
5669 i = s->nlines - 1;
5670 if (--i == start)
5671 return; /* do nothing, requested type not in file */
5674 s->selected_line = 1;
5675 s->first_displayed_line = i;
5678 static void
5679 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5681 int start, i;
5683 i = start = s->first_displayed_line + 1;
5685 while (s->lines[i].type != type) {
5686 if (i == s->nlines - 1)
5687 i = 0;
5688 if (++i == start)
5689 return; /* do nothing, requested type not in file */
5692 s->selected_line = 1;
5693 s->first_displayed_line = i;
5696 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5697 int, int, int);
5698 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5699 int, int);
5701 static const struct got_error *
5702 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5704 const struct got_error *err = NULL;
5705 struct tog_diff_view_state *s = &view->state.diff;
5706 struct tog_log_view_state *ls;
5707 struct commit_queue_entry *old_selected_entry;
5708 char *line = NULL;
5709 size_t linesize = 0;
5710 ssize_t linelen;
5711 int i, nscroll = view->nlines - 1, up = 0;
5713 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5715 switch (ch) {
5716 case '0':
5717 case '$':
5718 case KEY_RIGHT:
5719 case 'l':
5720 case KEY_LEFT:
5721 case 'h':
5722 horizontal_scroll_input(view, ch);
5723 break;
5724 case 'a':
5725 case 'w':
5726 if (ch == 'a') {
5727 s->force_text_diff = !s->force_text_diff;
5728 view->action = s->force_text_diff ?
5729 "force ASCII text enabled" :
5730 "force ASCII text disabled";
5732 else if (ch == 'w') {
5733 s->ignore_whitespace = !s->ignore_whitespace;
5734 view->action = s->ignore_whitespace ?
5735 "ignore whitespace enabled" :
5736 "ignore whitespace disabled";
5738 err = reset_diff_view(view);
5739 break;
5740 case 'g':
5741 case KEY_HOME:
5742 s->first_displayed_line = 1;
5743 view->count = 0;
5744 break;
5745 case 'G':
5746 case KEY_END:
5747 view->count = 0;
5748 if (s->eof)
5749 break;
5751 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5752 s->eof = 1;
5753 break;
5754 case 'k':
5755 case KEY_UP:
5756 case CTRL('p'):
5757 if (s->first_displayed_line > 1)
5758 s->first_displayed_line--;
5759 else
5760 view->count = 0;
5761 break;
5762 case CTRL('u'):
5763 case 'u':
5764 nscroll /= 2;
5765 /* FALL THROUGH */
5766 case KEY_PPAGE:
5767 case CTRL('b'):
5768 case 'b':
5769 if (s->first_displayed_line == 1) {
5770 view->count = 0;
5771 break;
5773 i = 0;
5774 while (i++ < nscroll && s->first_displayed_line > 1)
5775 s->first_displayed_line--;
5776 break;
5777 case 'j':
5778 case KEY_DOWN:
5779 case CTRL('n'):
5780 if (!s->eof)
5781 s->first_displayed_line++;
5782 else
5783 view->count = 0;
5784 break;
5785 case CTRL('d'):
5786 case 'd':
5787 nscroll /= 2;
5788 /* FALL THROUGH */
5789 case KEY_NPAGE:
5790 case CTRL('f'):
5791 case 'f':
5792 case ' ':
5793 if (s->eof) {
5794 view->count = 0;
5795 break;
5797 i = 0;
5798 while (!s->eof && i++ < nscroll) {
5799 linelen = getline(&line, &linesize, s->f);
5800 s->first_displayed_line++;
5801 if (linelen == -1) {
5802 if (feof(s->f)) {
5803 s->eof = 1;
5804 } else
5805 err = got_ferror(s->f, GOT_ERR_IO);
5806 break;
5809 free(line);
5810 break;
5811 case '(':
5812 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5813 break;
5814 case ')':
5815 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5816 break;
5817 case '{':
5818 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5819 break;
5820 case '}':
5821 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5822 break;
5823 case '[':
5824 if (s->diff_context > 0) {
5825 s->diff_context--;
5826 s->matched_line = 0;
5827 diff_view_indicate_progress(view);
5828 err = create_diff(s);
5829 if (s->first_displayed_line + view->nlines - 1 >
5830 s->nlines) {
5831 s->first_displayed_line = 1;
5832 s->last_displayed_line = view->nlines;
5834 } else
5835 view->count = 0;
5836 break;
5837 case ']':
5838 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5839 s->diff_context++;
5840 s->matched_line = 0;
5841 diff_view_indicate_progress(view);
5842 err = create_diff(s);
5843 } else
5844 view->count = 0;
5845 break;
5846 case '<':
5847 case ',':
5848 case 'K':
5849 up = 1;
5850 /* FALL THROUGH */
5851 case '>':
5852 case '.':
5853 case 'J':
5854 if (s->parent_view == NULL) {
5855 view->count = 0;
5856 break;
5858 s->parent_view->count = view->count;
5860 if (s->parent_view->type == TOG_VIEW_LOG) {
5861 ls = &s->parent_view->state.log;
5862 old_selected_entry = ls->selected_entry;
5864 err = input_log_view(NULL, s->parent_view,
5865 up ? KEY_UP : KEY_DOWN);
5866 if (err)
5867 break;
5868 view->count = s->parent_view->count;
5870 if (old_selected_entry == ls->selected_entry)
5871 break;
5873 err = set_selected_commit(s, ls->selected_entry);
5874 if (err)
5875 break;
5876 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5877 struct tog_blame_view_state *bs;
5878 struct got_object_id *id, *prev_id;
5880 bs = &s->parent_view->state.blame;
5881 prev_id = get_annotation_for_line(bs->blame.lines,
5882 bs->blame.nlines, bs->last_diffed_line);
5884 err = input_blame_view(&view, s->parent_view,
5885 up ? KEY_UP : KEY_DOWN);
5886 if (err)
5887 break;
5888 view->count = s->parent_view->count;
5890 if (prev_id == NULL)
5891 break;
5892 id = get_selected_commit_id(bs->blame.lines,
5893 bs->blame.nlines, bs->first_displayed_line,
5894 bs->selected_line);
5895 if (id == NULL)
5896 break;
5898 if (!got_object_id_cmp(prev_id, id))
5899 break;
5901 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5902 if (err)
5903 break;
5905 s->first_displayed_line = 1;
5906 s->last_displayed_line = view->nlines;
5907 s->matched_line = 0;
5908 view->x = 0;
5910 diff_view_indicate_progress(view);
5911 err = create_diff(s);
5912 break;
5913 default:
5914 view->count = 0;
5915 break;
5918 return err;
5921 static const struct got_error *
5922 cmd_diff(int argc, char *argv[])
5924 const struct got_error *error;
5925 struct got_repository *repo = NULL;
5926 struct got_worktree *worktree = NULL;
5927 struct got_object_id *id1 = NULL, *id2 = NULL;
5928 char *repo_path = NULL, *cwd = NULL;
5929 char *id_str1 = NULL, *id_str2 = NULL;
5930 char *keyword_idstr1 = NULL, *keyword_idstr2 = NULL;
5931 char *label1 = NULL, *label2 = NULL;
5932 int diff_context = 3, ignore_whitespace = 0;
5933 int ch, force_text_diff = 0;
5934 const char *errstr;
5935 struct tog_view *view;
5936 int *pack_fds = NULL;
5938 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5939 switch (ch) {
5940 case 'a':
5941 force_text_diff = 1;
5942 break;
5943 case 'C':
5944 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5945 &errstr);
5946 if (errstr != NULL)
5947 errx(1, "number of context lines is %s: %s",
5948 errstr, errstr);
5949 break;
5950 case 'r':
5951 repo_path = realpath(optarg, NULL);
5952 if (repo_path == NULL)
5953 return got_error_from_errno2("realpath",
5954 optarg);
5955 got_path_strip_trailing_slashes(repo_path);
5956 break;
5957 case 'w':
5958 ignore_whitespace = 1;
5959 break;
5960 default:
5961 usage_diff();
5962 /* NOTREACHED */
5966 argc -= optind;
5967 argv += optind;
5969 if (argc == 0) {
5970 usage_diff(); /* TODO show local worktree changes */
5971 } else if (argc == 2) {
5972 id_str1 = argv[0];
5973 id_str2 = argv[1];
5974 } else
5975 usage_diff();
5977 error = got_repo_pack_fds_open(&pack_fds);
5978 if (error)
5979 goto done;
5981 if (repo_path == NULL) {
5982 cwd = getcwd(NULL, 0);
5983 if (cwd == NULL)
5984 return got_error_from_errno("getcwd");
5985 error = got_worktree_open(&worktree, cwd, NULL);
5986 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5987 goto done;
5988 if (worktree)
5989 repo_path =
5990 strdup(got_worktree_get_repo_path(worktree));
5991 else
5992 repo_path = strdup(cwd);
5993 if (repo_path == NULL) {
5994 error = got_error_from_errno("strdup");
5995 goto done;
5999 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6000 if (error)
6001 goto done;
6003 init_curses();
6005 error = apply_unveil(got_repo_get_path(repo), NULL);
6006 if (error)
6007 goto done;
6009 error = tog_load_refs(repo, 0);
6010 if (error)
6011 goto done;
6013 if (id_str1 != NULL) {
6014 error = got_keyword_to_idstr(&keyword_idstr1, id_str1,
6015 repo, worktree);
6016 if (error != NULL)
6017 goto done;
6018 if (keyword_idstr1 != NULL)
6019 id_str1 = keyword_idstr1;
6021 if (id_str2 != NULL) {
6022 error = got_keyword_to_idstr(&keyword_idstr2, id_str2,
6023 repo, worktree);
6024 if (error != NULL)
6025 goto done;
6026 if (keyword_idstr2 != NULL)
6027 id_str2 = keyword_idstr2;
6030 error = got_repo_match_object_id(&id1, &label1, id_str1,
6031 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6032 if (error)
6033 goto done;
6035 error = got_repo_match_object_id(&id2, &label2, id_str2,
6036 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6037 if (error)
6038 goto done;
6040 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
6041 if (view == NULL) {
6042 error = got_error_from_errno("view_open");
6043 goto done;
6045 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
6046 ignore_whitespace, force_text_diff, NULL, repo);
6047 if (error)
6048 goto done;
6049 error = view_loop(view);
6050 done:
6051 free(keyword_idstr1);
6052 free(keyword_idstr2);
6053 free(label1);
6054 free(label2);
6055 free(repo_path);
6056 free(cwd);
6057 if (repo) {
6058 const struct got_error *close_err = got_repo_close(repo);
6059 if (error == NULL)
6060 error = close_err;
6062 if (worktree)
6063 got_worktree_close(worktree);
6064 if (pack_fds) {
6065 const struct got_error *pack_err =
6066 got_repo_pack_fds_close(pack_fds);
6067 if (error == NULL)
6068 error = pack_err;
6070 tog_free_refs();
6071 return error;
6074 __dead static void
6075 usage_blame(void)
6077 endwin();
6078 fprintf(stderr,
6079 "usage: %s blame [-c commit] [-r repository-path] path\n",
6080 getprogname());
6081 exit(1);
6084 struct tog_blame_line {
6085 int annotated;
6086 struct got_object_id *id;
6089 static const struct got_error *
6090 draw_blame(struct tog_view *view)
6092 struct tog_blame_view_state *s = &view->state.blame;
6093 struct tog_blame *blame = &s->blame;
6094 regmatch_t *regmatch = &view->regmatch;
6095 const struct got_error *err;
6096 int lineno = 0, nprinted = 0;
6097 char *line = NULL;
6098 size_t linesize = 0;
6099 ssize_t linelen;
6100 wchar_t *wline;
6101 int width;
6102 struct tog_blame_line *blame_line;
6103 struct got_object_id *prev_id = NULL;
6104 char *id_str;
6105 struct tog_color *tc;
6107 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6108 if (err)
6109 return err;
6111 rewind(blame->f);
6112 werase(view->window);
6114 if (asprintf(&line, "commit %s", id_str) == -1) {
6115 err = got_error_from_errno("asprintf");
6116 free(id_str);
6117 return err;
6120 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6121 free(line);
6122 line = NULL;
6123 if (err)
6124 return err;
6125 if (view_needs_focus_indication(view))
6126 wstandout(view->window);
6127 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6128 if (tc)
6129 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6130 waddwstr(view->window, wline);
6131 while (width++ < view->ncols)
6132 waddch(view->window, ' ');
6133 if (tc)
6134 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6135 if (view_needs_focus_indication(view))
6136 wstandend(view->window);
6137 free(wline);
6138 wline = NULL;
6140 if (view->gline > blame->nlines)
6141 view->gline = blame->nlines;
6143 if (tog_io.wait_for_ui) {
6144 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6145 int rc;
6147 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6148 if (rc)
6149 return got_error_set_errno(rc, "pthread_cond_wait");
6150 tog_io.wait_for_ui = 0;
6153 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6154 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6155 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6156 free(id_str);
6157 return got_error_from_errno("asprintf");
6159 free(id_str);
6160 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6161 free(line);
6162 line = NULL;
6163 if (err)
6164 return err;
6165 waddwstr(view->window, wline);
6166 free(wline);
6167 wline = NULL;
6168 if (width < view->ncols - 1)
6169 waddch(view->window, '\n');
6171 s->eof = 0;
6172 view->maxx = 0;
6173 while (nprinted < view->nlines - 2) {
6174 linelen = getline(&line, &linesize, blame->f);
6175 if (linelen == -1) {
6176 if (feof(blame->f)) {
6177 s->eof = 1;
6178 break;
6180 free(line);
6181 return got_ferror(blame->f, GOT_ERR_IO);
6183 if (++lineno < s->first_displayed_line)
6184 continue;
6185 if (view->gline && !gotoline(view, &lineno, &nprinted))
6186 continue;
6188 /* Set view->maxx based on full line length. */
6189 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6190 if (err) {
6191 free(line);
6192 return err;
6194 free(wline);
6195 wline = NULL;
6196 view->maxx = MAX(view->maxx, width);
6198 if (nprinted == s->selected_line - 1)
6199 wstandout(view->window);
6201 if (blame->nlines > 0) {
6202 blame_line = &blame->lines[lineno - 1];
6203 if (blame_line->annotated && prev_id &&
6204 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6205 !(nprinted == s->selected_line - 1)) {
6206 waddstr(view->window, " ");
6207 } else if (blame_line->annotated) {
6208 char *id_str;
6209 err = got_object_id_str(&id_str,
6210 blame_line->id);
6211 if (err) {
6212 free(line);
6213 return err;
6215 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6216 if (tc)
6217 wattr_on(view->window,
6218 COLOR_PAIR(tc->colorpair), NULL);
6219 wprintw(view->window, "%.8s", id_str);
6220 if (tc)
6221 wattr_off(view->window,
6222 COLOR_PAIR(tc->colorpair), NULL);
6223 free(id_str);
6224 prev_id = blame_line->id;
6225 } else {
6226 waddstr(view->window, "........");
6227 prev_id = NULL;
6229 } else {
6230 waddstr(view->window, "........");
6231 prev_id = NULL;
6234 if (nprinted == s->selected_line - 1)
6235 wstandend(view->window);
6236 waddstr(view->window, " ");
6238 if (view->ncols <= 9) {
6239 width = 9;
6240 } else if (s->first_displayed_line + nprinted ==
6241 s->matched_line &&
6242 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6243 err = add_matched_line(&width, line, view->ncols - 9, 9,
6244 view->window, view->x, regmatch);
6245 if (err) {
6246 free(line);
6247 return err;
6249 width += 9;
6250 } else {
6251 int skip;
6252 err = format_line(&wline, &width, &skip, line,
6253 view->x, view->ncols - 9, 9, 1);
6254 if (err) {
6255 free(line);
6256 return err;
6258 waddwstr(view->window, &wline[skip]);
6259 width += 9;
6260 free(wline);
6261 wline = NULL;
6264 if (width <= view->ncols - 1)
6265 waddch(view->window, '\n');
6266 if (++nprinted == 1)
6267 s->first_displayed_line = lineno;
6269 free(line);
6270 s->last_displayed_line = lineno;
6272 view_border(view);
6274 return NULL;
6277 static const struct got_error *
6278 blame_cb(void *arg, int nlines, int lineno,
6279 struct got_commit_object *commit, struct got_object_id *id)
6281 const struct got_error *err = NULL;
6282 struct tog_blame_cb_args *a = arg;
6283 struct tog_blame_line *line;
6284 int errcode;
6286 if (nlines != a->nlines ||
6287 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6288 return got_error(GOT_ERR_RANGE);
6290 errcode = pthread_mutex_lock(&tog_mutex);
6291 if (errcode)
6292 return got_error_set_errno(errcode, "pthread_mutex_lock");
6294 if (*a->quit) { /* user has quit the blame view */
6295 err = got_error(GOT_ERR_ITER_COMPLETED);
6296 goto done;
6299 if (lineno == -1)
6300 goto done; /* no change in this commit */
6302 line = &a->lines[lineno - 1];
6303 if (line->annotated)
6304 goto done;
6306 line->id = got_object_id_dup(id);
6307 if (line->id == NULL) {
6308 err = got_error_from_errno("got_object_id_dup");
6309 goto done;
6311 line->annotated = 1;
6312 done:
6313 errcode = pthread_mutex_unlock(&tog_mutex);
6314 if (errcode)
6315 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6316 return err;
6319 static void *
6320 blame_thread(void *arg)
6322 const struct got_error *err, *close_err;
6323 struct tog_blame_thread_args *ta = arg;
6324 struct tog_blame_cb_args *a = ta->cb_args;
6325 int errcode, fd1 = -1, fd2 = -1;
6326 FILE *f1 = NULL, *f2 = NULL;
6328 fd1 = got_opentempfd();
6329 if (fd1 == -1)
6330 return (void *)got_error_from_errno("got_opentempfd");
6332 fd2 = got_opentempfd();
6333 if (fd2 == -1) {
6334 err = got_error_from_errno("got_opentempfd");
6335 goto done;
6338 f1 = got_opentemp();
6339 if (f1 == NULL) {
6340 err = (void *)got_error_from_errno("got_opentemp");
6341 goto done;
6343 f2 = got_opentemp();
6344 if (f2 == NULL) {
6345 err = (void *)got_error_from_errno("got_opentemp");
6346 goto done;
6349 err = block_signals_used_by_main_thread();
6350 if (err)
6351 goto done;
6353 err = got_blame(ta->path, a->commit_id, ta->repo,
6354 tog_diff_algo, blame_cb, ta->cb_args,
6355 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6356 if (err && err->code == GOT_ERR_CANCELLED)
6357 err = NULL;
6359 errcode = pthread_mutex_lock(&tog_mutex);
6360 if (errcode) {
6361 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6362 goto done;
6365 close_err = got_repo_close(ta->repo);
6366 if (err == NULL)
6367 err = close_err;
6368 ta->repo = NULL;
6369 *ta->complete = 1;
6371 if (tog_io.wait_for_ui) {
6372 errcode = pthread_cond_signal(&ta->blame_complete);
6373 if (errcode && err == NULL)
6374 err = got_error_set_errno(errcode,
6375 "pthread_cond_signal");
6378 errcode = pthread_mutex_unlock(&tog_mutex);
6379 if (errcode && err == NULL)
6380 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6382 done:
6383 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6384 err = got_error_from_errno("close");
6385 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6386 err = got_error_from_errno("close");
6387 if (f1 && fclose(f1) == EOF && err == NULL)
6388 err = got_error_from_errno("fclose");
6389 if (f2 && fclose(f2) == EOF && err == NULL)
6390 err = got_error_from_errno("fclose");
6392 return (void *)err;
6395 static struct got_object_id *
6396 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6397 int first_displayed_line, int selected_line)
6399 struct tog_blame_line *line;
6401 if (nlines <= 0)
6402 return NULL;
6404 line = &lines[first_displayed_line - 1 + selected_line - 1];
6405 if (!line->annotated)
6406 return NULL;
6408 return line->id;
6411 static struct got_object_id *
6412 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6413 int lineno)
6415 struct tog_blame_line *line;
6417 if (nlines <= 0 || lineno >= nlines)
6418 return NULL;
6420 line = &lines[lineno - 1];
6421 if (!line->annotated)
6422 return NULL;
6424 return line->id;
6427 static const struct got_error *
6428 stop_blame(struct tog_blame *blame)
6430 const struct got_error *err = NULL;
6431 int i;
6433 if (blame->thread) {
6434 int errcode;
6435 errcode = pthread_mutex_unlock(&tog_mutex);
6436 if (errcode)
6437 return got_error_set_errno(errcode,
6438 "pthread_mutex_unlock");
6439 errcode = pthread_join(blame->thread, (void **)&err);
6440 if (errcode)
6441 return got_error_set_errno(errcode, "pthread_join");
6442 errcode = pthread_mutex_lock(&tog_mutex);
6443 if (errcode)
6444 return got_error_set_errno(errcode,
6445 "pthread_mutex_lock");
6446 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6447 err = NULL;
6448 blame->thread = NULL;
6450 if (blame->thread_args.repo) {
6451 const struct got_error *close_err;
6452 close_err = got_repo_close(blame->thread_args.repo);
6453 if (err == NULL)
6454 err = close_err;
6455 blame->thread_args.repo = NULL;
6457 if (blame->f) {
6458 if (fclose(blame->f) == EOF && err == NULL)
6459 err = got_error_from_errno("fclose");
6460 blame->f = NULL;
6462 if (blame->lines) {
6463 for (i = 0; i < blame->nlines; i++)
6464 free(blame->lines[i].id);
6465 free(blame->lines);
6466 blame->lines = NULL;
6468 free(blame->cb_args.commit_id);
6469 blame->cb_args.commit_id = NULL;
6470 if (blame->pack_fds) {
6471 const struct got_error *pack_err =
6472 got_repo_pack_fds_close(blame->pack_fds);
6473 if (err == NULL)
6474 err = pack_err;
6475 blame->pack_fds = NULL;
6477 return err;
6480 static const struct got_error *
6481 cancel_blame_view(void *arg)
6483 const struct got_error *err = NULL;
6484 int *done = arg;
6485 int errcode;
6487 errcode = pthread_mutex_lock(&tog_mutex);
6488 if (errcode)
6489 return got_error_set_errno(errcode,
6490 "pthread_mutex_unlock");
6492 if (*done)
6493 err = got_error(GOT_ERR_CANCELLED);
6495 errcode = pthread_mutex_unlock(&tog_mutex);
6496 if (errcode)
6497 return got_error_set_errno(errcode,
6498 "pthread_mutex_lock");
6500 return err;
6503 static const struct got_error *
6504 run_blame(struct tog_view *view)
6506 struct tog_blame_view_state *s = &view->state.blame;
6507 struct tog_blame *blame = &s->blame;
6508 const struct got_error *err = NULL;
6509 struct got_commit_object *commit = NULL;
6510 struct got_blob_object *blob = NULL;
6511 struct got_repository *thread_repo = NULL;
6512 struct got_object_id *obj_id = NULL;
6513 int obj_type, fd = -1;
6514 int *pack_fds = NULL;
6516 err = got_object_open_as_commit(&commit, s->repo,
6517 &s->blamed_commit->id);
6518 if (err)
6519 return err;
6521 fd = got_opentempfd();
6522 if (fd == -1) {
6523 err = got_error_from_errno("got_opentempfd");
6524 goto done;
6527 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6528 if (err)
6529 goto done;
6531 err = got_object_get_type(&obj_type, s->repo, obj_id);
6532 if (err)
6533 goto done;
6535 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6536 err = got_error(GOT_ERR_OBJ_TYPE);
6537 goto done;
6540 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6541 if (err)
6542 goto done;
6543 blame->f = got_opentemp();
6544 if (blame->f == NULL) {
6545 err = got_error_from_errno("got_opentemp");
6546 goto done;
6548 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6549 &blame->line_offsets, blame->f, blob);
6550 if (err)
6551 goto done;
6552 if (blame->nlines == 0) {
6553 s->blame_complete = 1;
6554 goto done;
6557 /* Don't include \n at EOF in the blame line count. */
6558 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6559 blame->nlines--;
6561 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6562 if (blame->lines == NULL) {
6563 err = got_error_from_errno("calloc");
6564 goto done;
6567 err = got_repo_pack_fds_open(&pack_fds);
6568 if (err)
6569 goto done;
6570 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6571 pack_fds);
6572 if (err)
6573 goto done;
6575 blame->pack_fds = pack_fds;
6576 blame->cb_args.view = view;
6577 blame->cb_args.lines = blame->lines;
6578 blame->cb_args.nlines = blame->nlines;
6579 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6580 if (blame->cb_args.commit_id == NULL) {
6581 err = got_error_from_errno("got_object_id_dup");
6582 goto done;
6584 blame->cb_args.quit = &s->done;
6586 blame->thread_args.path = s->path;
6587 blame->thread_args.repo = thread_repo;
6588 blame->thread_args.cb_args = &blame->cb_args;
6589 blame->thread_args.complete = &s->blame_complete;
6590 blame->thread_args.cancel_cb = cancel_blame_view;
6591 blame->thread_args.cancel_arg = &s->done;
6592 s->blame_complete = 0;
6594 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6595 s->first_displayed_line = 1;
6596 s->last_displayed_line = view->nlines;
6597 s->selected_line = 1;
6599 s->matched_line = 0;
6601 done:
6602 if (commit)
6603 got_object_commit_close(commit);
6604 if (fd != -1 && close(fd) == -1 && err == NULL)
6605 err = got_error_from_errno("close");
6606 if (blob)
6607 got_object_blob_close(blob);
6608 free(obj_id);
6609 if (err)
6610 stop_blame(blame);
6611 return err;
6614 static const struct got_error *
6615 open_blame_view(struct tog_view *view, char *path,
6616 struct got_object_id *commit_id, struct got_repository *repo)
6618 const struct got_error *err = NULL;
6619 struct tog_blame_view_state *s = &view->state.blame;
6621 STAILQ_INIT(&s->blamed_commits);
6623 s->path = strdup(path);
6624 if (s->path == NULL)
6625 return got_error_from_errno("strdup");
6627 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6628 if (err) {
6629 free(s->path);
6630 return err;
6633 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6634 s->first_displayed_line = 1;
6635 s->last_displayed_line = view->nlines;
6636 s->selected_line = 1;
6637 s->blame_complete = 0;
6638 s->repo = repo;
6639 s->commit_id = commit_id;
6640 memset(&s->blame, 0, sizeof(s->blame));
6642 STAILQ_INIT(&s->colors);
6643 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6644 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6645 get_color_value("TOG_COLOR_COMMIT"));
6646 if (err)
6647 return err;
6650 view->show = show_blame_view;
6651 view->input = input_blame_view;
6652 view->reset = reset_blame_view;
6653 view->close = close_blame_view;
6654 view->search_start = search_start_blame_view;
6655 view->search_setup = search_setup_blame_view;
6656 view->search_next = search_next_view_match;
6658 if (using_mock_io) {
6659 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6660 int rc;
6662 rc = pthread_cond_init(&bta->blame_complete, NULL);
6663 if (rc)
6664 return got_error_set_errno(rc, "pthread_cond_init");
6667 return run_blame(view);
6670 static const struct got_error *
6671 close_blame_view(struct tog_view *view)
6673 const struct got_error *err = NULL;
6674 struct tog_blame_view_state *s = &view->state.blame;
6676 if (s->blame.thread)
6677 err = stop_blame(&s->blame);
6679 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6680 struct got_object_qid *blamed_commit;
6681 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6682 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6683 got_object_qid_free(blamed_commit);
6686 if (using_mock_io) {
6687 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6688 int rc;
6690 rc = pthread_cond_destroy(&bta->blame_complete);
6691 if (rc && err == NULL)
6692 err = got_error_set_errno(rc, "pthread_cond_destroy");
6695 free(s->path);
6696 free_colors(&s->colors);
6697 return err;
6700 static const struct got_error *
6701 search_start_blame_view(struct tog_view *view)
6703 struct tog_blame_view_state *s = &view->state.blame;
6705 s->matched_line = 0;
6706 return NULL;
6709 static void
6710 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6711 size_t *nlines, int **first, int **last, int **match, int **selected)
6713 struct tog_blame_view_state *s = &view->state.blame;
6715 *f = s->blame.f;
6716 *nlines = s->blame.nlines;
6717 *line_offsets = s->blame.line_offsets;
6718 *match = &s->matched_line;
6719 *first = &s->first_displayed_line;
6720 *last = &s->last_displayed_line;
6721 *selected = &s->selected_line;
6724 static const struct got_error *
6725 show_blame_view(struct tog_view *view)
6727 const struct got_error *err = NULL;
6728 struct tog_blame_view_state *s = &view->state.blame;
6729 int errcode;
6731 if (s->blame.thread == NULL && !s->blame_complete) {
6732 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6733 &s->blame.thread_args);
6734 if (errcode)
6735 return got_error_set_errno(errcode, "pthread_create");
6737 if (!using_mock_io)
6738 halfdelay(1); /* fast refresh while annotating */
6741 if (s->blame_complete && !using_mock_io)
6742 halfdelay(10); /* disable fast refresh */
6744 err = draw_blame(view);
6746 view_border(view);
6747 return err;
6750 static const struct got_error *
6751 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6752 struct got_repository *repo, struct got_object_id *id)
6754 struct tog_view *log_view;
6755 const struct got_error *err = NULL;
6757 *new_view = NULL;
6759 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6760 if (log_view == NULL)
6761 return got_error_from_errno("view_open");
6763 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6764 if (err)
6765 view_close(log_view);
6766 else
6767 *new_view = log_view;
6769 return err;
6772 static const struct got_error *
6773 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6775 const struct got_error *err = NULL, *thread_err = NULL;
6776 struct tog_view *diff_view;
6777 struct tog_blame_view_state *s = &view->state.blame;
6778 int eos, nscroll, begin_y = 0, begin_x = 0;
6780 eos = nscroll = view->nlines - 2;
6781 if (view_is_hsplit_top(view))
6782 --eos; /* border */
6784 switch (ch) {
6785 case '0':
6786 case '$':
6787 case KEY_RIGHT:
6788 case 'l':
6789 case KEY_LEFT:
6790 case 'h':
6791 horizontal_scroll_input(view, ch);
6792 break;
6793 case 'q':
6794 s->done = 1;
6795 break;
6796 case 'g':
6797 case KEY_HOME:
6798 s->selected_line = 1;
6799 s->first_displayed_line = 1;
6800 view->count = 0;
6801 break;
6802 case 'G':
6803 case KEY_END:
6804 if (s->blame.nlines < eos) {
6805 s->selected_line = s->blame.nlines;
6806 s->first_displayed_line = 1;
6807 } else {
6808 s->selected_line = eos;
6809 s->first_displayed_line = s->blame.nlines - (eos - 1);
6811 view->count = 0;
6812 break;
6813 case 'k':
6814 case KEY_UP:
6815 case CTRL('p'):
6816 if (s->selected_line > 1)
6817 s->selected_line--;
6818 else if (s->selected_line == 1 &&
6819 s->first_displayed_line > 1)
6820 s->first_displayed_line--;
6821 else
6822 view->count = 0;
6823 break;
6824 case CTRL('u'):
6825 case 'u':
6826 nscroll /= 2;
6827 /* FALL THROUGH */
6828 case KEY_PPAGE:
6829 case CTRL('b'):
6830 case 'b':
6831 if (s->first_displayed_line == 1) {
6832 if (view->count > 1)
6833 nscroll += nscroll;
6834 s->selected_line = MAX(1, s->selected_line - nscroll);
6835 view->count = 0;
6836 break;
6838 if (s->first_displayed_line > nscroll)
6839 s->first_displayed_line -= nscroll;
6840 else
6841 s->first_displayed_line = 1;
6842 break;
6843 case 'j':
6844 case KEY_DOWN:
6845 case CTRL('n'):
6846 if (s->selected_line < eos && s->first_displayed_line +
6847 s->selected_line <= s->blame.nlines)
6848 s->selected_line++;
6849 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6850 s->first_displayed_line++;
6851 else
6852 view->count = 0;
6853 break;
6854 case 'c':
6855 case 'p': {
6856 struct got_object_id *id = NULL;
6858 view->count = 0;
6859 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6860 s->first_displayed_line, s->selected_line);
6861 if (id == NULL)
6862 break;
6863 if (ch == 'p') {
6864 struct got_commit_object *commit, *pcommit;
6865 struct got_object_qid *pid;
6866 struct got_object_id *blob_id = NULL;
6867 int obj_type;
6868 err = got_object_open_as_commit(&commit,
6869 s->repo, id);
6870 if (err)
6871 break;
6872 pid = STAILQ_FIRST(
6873 got_object_commit_get_parent_ids(commit));
6874 if (pid == NULL) {
6875 got_object_commit_close(commit);
6876 break;
6878 /* Check if path history ends here. */
6879 err = got_object_open_as_commit(&pcommit,
6880 s->repo, &pid->id);
6881 if (err)
6882 break;
6883 err = got_object_id_by_path(&blob_id, s->repo,
6884 pcommit, s->path);
6885 got_object_commit_close(pcommit);
6886 if (err) {
6887 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6888 err = NULL;
6889 got_object_commit_close(commit);
6890 break;
6892 err = got_object_get_type(&obj_type, s->repo,
6893 blob_id);
6894 free(blob_id);
6895 /* Can't blame non-blob type objects. */
6896 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6897 got_object_commit_close(commit);
6898 break;
6900 err = got_object_qid_alloc(&s->blamed_commit,
6901 &pid->id);
6902 got_object_commit_close(commit);
6903 } else {
6904 if (got_object_id_cmp(id,
6905 &s->blamed_commit->id) == 0)
6906 break;
6907 err = got_object_qid_alloc(&s->blamed_commit,
6908 id);
6910 if (err)
6911 break;
6912 s->done = 1;
6913 thread_err = stop_blame(&s->blame);
6914 s->done = 0;
6915 if (thread_err)
6916 break;
6917 STAILQ_INSERT_HEAD(&s->blamed_commits,
6918 s->blamed_commit, entry);
6919 err = run_blame(view);
6920 if (err)
6921 break;
6922 break;
6924 case 'C': {
6925 struct got_object_qid *first;
6927 view->count = 0;
6928 first = STAILQ_FIRST(&s->blamed_commits);
6929 if (!got_object_id_cmp(&first->id, s->commit_id))
6930 break;
6931 s->done = 1;
6932 thread_err = stop_blame(&s->blame);
6933 s->done = 0;
6934 if (thread_err)
6935 break;
6936 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6937 got_object_qid_free(s->blamed_commit);
6938 s->blamed_commit =
6939 STAILQ_FIRST(&s->blamed_commits);
6940 err = run_blame(view);
6941 if (err)
6942 break;
6943 break;
6945 case 'L':
6946 view->count = 0;
6947 s->id_to_log = get_selected_commit_id(s->blame.lines,
6948 s->blame.nlines, s->first_displayed_line, s->selected_line);
6949 if (s->id_to_log)
6950 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6951 break;
6952 case KEY_ENTER:
6953 case '\r': {
6954 struct got_object_id *id = NULL;
6955 struct got_object_qid *pid;
6956 struct got_commit_object *commit = NULL;
6958 view->count = 0;
6959 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6960 s->first_displayed_line, s->selected_line);
6961 if (id == NULL)
6962 break;
6963 err = got_object_open_as_commit(&commit, s->repo, id);
6964 if (err)
6965 break;
6966 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6967 if (*new_view) {
6968 /* traversed from diff view, release diff resources */
6969 err = close_diff_view(*new_view);
6970 if (err)
6971 break;
6972 diff_view = *new_view;
6973 } else {
6974 if (view_is_parent_view(view))
6975 view_get_split(view, &begin_y, &begin_x);
6977 diff_view = view_open(0, 0, begin_y, begin_x,
6978 TOG_VIEW_DIFF);
6979 if (diff_view == NULL) {
6980 got_object_commit_close(commit);
6981 err = got_error_from_errno("view_open");
6982 break;
6985 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6986 id, NULL, NULL, 3, 0, 0, view, s->repo);
6987 got_object_commit_close(commit);
6988 if (err)
6989 break;
6990 s->last_diffed_line = s->first_displayed_line - 1 +
6991 s->selected_line;
6992 if (*new_view)
6993 break; /* still open from active diff view */
6994 if (view_is_parent_view(view) &&
6995 view->mode == TOG_VIEW_SPLIT_HRZN) {
6996 err = view_init_hsplit(view, begin_y);
6997 if (err)
6998 break;
7001 view->focussed = 0;
7002 diff_view->focussed = 1;
7003 diff_view->mode = view->mode;
7004 diff_view->nlines = view->lines - begin_y;
7005 if (view_is_parent_view(view)) {
7006 view_transfer_size(diff_view, view);
7007 err = view_close_child(view);
7008 if (err)
7009 break;
7010 err = view_set_child(view, diff_view);
7011 if (err)
7012 break;
7013 view->focus_child = 1;
7014 } else
7015 *new_view = diff_view;
7016 if (err)
7017 break;
7018 break;
7020 case CTRL('d'):
7021 case 'd':
7022 nscroll /= 2;
7023 /* FALL THROUGH */
7024 case KEY_NPAGE:
7025 case CTRL('f'):
7026 case 'f':
7027 case ' ':
7028 if (s->last_displayed_line >= s->blame.nlines &&
7029 s->selected_line >= MIN(s->blame.nlines,
7030 view->nlines - 2)) {
7031 view->count = 0;
7032 break;
7034 if (s->last_displayed_line >= s->blame.nlines &&
7035 s->selected_line < view->nlines - 2) {
7036 s->selected_line +=
7037 MIN(nscroll, s->last_displayed_line -
7038 s->first_displayed_line - s->selected_line + 1);
7040 if (s->last_displayed_line + nscroll <= s->blame.nlines)
7041 s->first_displayed_line += nscroll;
7042 else
7043 s->first_displayed_line =
7044 s->blame.nlines - (view->nlines - 3);
7045 break;
7046 case KEY_RESIZE:
7047 if (s->selected_line > view->nlines - 2) {
7048 s->selected_line = MIN(s->blame.nlines,
7049 view->nlines - 2);
7051 break;
7052 default:
7053 view->count = 0;
7054 break;
7056 return thread_err ? thread_err : err;
7059 static const struct got_error *
7060 reset_blame_view(struct tog_view *view)
7062 const struct got_error *err;
7063 struct tog_blame_view_state *s = &view->state.blame;
7065 view->count = 0;
7066 s->done = 1;
7067 err = stop_blame(&s->blame);
7068 s->done = 0;
7069 if (err)
7070 return err;
7071 return run_blame(view);
7074 static const struct got_error *
7075 cmd_blame(int argc, char *argv[])
7077 const struct got_error *error;
7078 struct got_repository *repo = NULL;
7079 struct got_worktree *worktree = NULL;
7080 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7081 char *link_target = NULL;
7082 struct got_object_id *commit_id = NULL;
7083 struct got_commit_object *commit = NULL;
7084 char *keyword_idstr = NULL, *commit_id_str = NULL;
7085 int ch;
7086 struct tog_view *view = NULL;
7087 int *pack_fds = NULL;
7089 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7090 switch (ch) {
7091 case 'c':
7092 commit_id_str = optarg;
7093 break;
7094 case 'r':
7095 repo_path = realpath(optarg, NULL);
7096 if (repo_path == NULL)
7097 return got_error_from_errno2("realpath",
7098 optarg);
7099 break;
7100 default:
7101 usage_blame();
7102 /* NOTREACHED */
7106 argc -= optind;
7107 argv += optind;
7109 if (argc != 1)
7110 usage_blame();
7112 error = got_repo_pack_fds_open(&pack_fds);
7113 if (error != NULL)
7114 goto done;
7116 if (repo_path == NULL) {
7117 cwd = getcwd(NULL, 0);
7118 if (cwd == NULL)
7119 return got_error_from_errno("getcwd");
7120 error = got_worktree_open(&worktree, cwd, NULL);
7121 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7122 goto done;
7123 if (worktree)
7124 repo_path =
7125 strdup(got_worktree_get_repo_path(worktree));
7126 else
7127 repo_path = strdup(cwd);
7128 if (repo_path == NULL) {
7129 error = got_error_from_errno("strdup");
7130 goto done;
7134 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7135 if (error != NULL)
7136 goto done;
7138 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7139 worktree);
7140 if (error)
7141 goto done;
7143 init_curses();
7145 error = apply_unveil(got_repo_get_path(repo), NULL);
7146 if (error)
7147 goto done;
7149 error = tog_load_refs(repo, 0);
7150 if (error)
7151 goto done;
7153 if (commit_id_str == NULL) {
7154 struct got_reference *head_ref;
7155 error = got_ref_open(&head_ref, repo, worktree ?
7156 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7157 if (error != NULL)
7158 goto done;
7159 error = got_ref_resolve(&commit_id, repo, head_ref);
7160 got_ref_close(head_ref);
7161 } else {
7162 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
7163 repo, worktree);
7164 if (error != NULL)
7165 goto done;
7166 if (keyword_idstr != NULL)
7167 commit_id_str = keyword_idstr;
7169 error = got_repo_match_object_id(&commit_id, NULL,
7170 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7172 if (error != NULL)
7173 goto done;
7175 error = got_object_open_as_commit(&commit, repo, commit_id);
7176 if (error)
7177 goto done;
7179 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7180 commit, repo);
7181 if (error)
7182 goto done;
7184 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7185 if (view == NULL) {
7186 error = got_error_from_errno("view_open");
7187 goto done;
7189 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7190 commit_id, repo);
7191 if (error != NULL) {
7192 if (view->close == NULL)
7193 close_blame_view(view);
7194 view_close(view);
7195 goto done;
7197 if (worktree) {
7198 /* Release work tree lock. */
7199 got_worktree_close(worktree);
7200 worktree = NULL;
7202 error = view_loop(view);
7203 done:
7204 free(repo_path);
7205 free(in_repo_path);
7206 free(link_target);
7207 free(cwd);
7208 free(commit_id);
7209 free(keyword_idstr);
7210 if (commit)
7211 got_object_commit_close(commit);
7212 if (worktree)
7213 got_worktree_close(worktree);
7214 if (repo) {
7215 const struct got_error *close_err = got_repo_close(repo);
7216 if (error == NULL)
7217 error = close_err;
7219 if (pack_fds) {
7220 const struct got_error *pack_err =
7221 got_repo_pack_fds_close(pack_fds);
7222 if (error == NULL)
7223 error = pack_err;
7225 tog_free_refs();
7226 return error;
7229 static const struct got_error *
7230 draw_tree_entries(struct tog_view *view, const char *parent_path)
7232 struct tog_tree_view_state *s = &view->state.tree;
7233 const struct got_error *err = NULL;
7234 struct got_tree_entry *te;
7235 wchar_t *wline;
7236 char *index = NULL;
7237 struct tog_color *tc;
7238 int width, n, nentries, scrollx, i = 1;
7239 int limit = view->nlines;
7241 s->ndisplayed = 0;
7242 if (view_is_hsplit_top(view))
7243 --limit; /* border */
7245 werase(view->window);
7247 if (limit == 0)
7248 return NULL;
7250 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7251 0, 0);
7252 if (err)
7253 return err;
7254 if (view_needs_focus_indication(view))
7255 wstandout(view->window);
7256 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7257 if (tc)
7258 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7259 waddwstr(view->window, wline);
7260 free(wline);
7261 wline = NULL;
7262 while (width++ < view->ncols)
7263 waddch(view->window, ' ');
7264 if (tc)
7265 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7266 if (view_needs_focus_indication(view))
7267 wstandend(view->window);
7268 if (--limit <= 0)
7269 return NULL;
7271 i += s->selected;
7272 if (s->first_displayed_entry) {
7273 i += got_tree_entry_get_index(s->first_displayed_entry);
7274 if (s->tree != s->root)
7275 ++i; /* account for ".." entry */
7277 nentries = got_object_tree_get_nentries(s->tree);
7278 if (asprintf(&index, "[%d/%d] %s",
7279 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7280 return got_error_from_errno("asprintf");
7281 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7282 free(index);
7283 if (err)
7284 return err;
7285 waddwstr(view->window, wline);
7286 free(wline);
7287 wline = NULL;
7288 if (width < view->ncols - 1)
7289 waddch(view->window, '\n');
7290 if (--limit <= 0)
7291 return NULL;
7292 waddch(view->window, '\n');
7293 if (--limit <= 0)
7294 return NULL;
7296 if (s->first_displayed_entry == NULL) {
7297 te = got_object_tree_get_first_entry(s->tree);
7298 if (s->selected == 0) {
7299 if (view->focussed)
7300 wstandout(view->window);
7301 s->selected_entry = NULL;
7303 waddstr(view->window, " ..\n"); /* parent directory */
7304 if (s->selected == 0 && view->focussed)
7305 wstandend(view->window);
7306 s->ndisplayed++;
7307 if (--limit <= 0)
7308 return NULL;
7309 n = 1;
7310 } else {
7311 n = 0;
7312 te = s->first_displayed_entry;
7315 view->maxx = 0;
7316 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7317 char *line = NULL, *id_str = NULL, *link_target = NULL;
7318 const char *modestr = "";
7319 mode_t mode;
7321 te = got_object_tree_get_entry(s->tree, i);
7322 mode = got_tree_entry_get_mode(te);
7324 if (s->show_ids) {
7325 err = got_object_id_str(&id_str,
7326 got_tree_entry_get_id(te));
7327 if (err)
7328 return got_error_from_errno(
7329 "got_object_id_str");
7331 if (got_object_tree_entry_is_submodule(te))
7332 modestr = "$";
7333 else if (S_ISLNK(mode)) {
7334 int i;
7336 err = got_tree_entry_get_symlink_target(&link_target,
7337 te, s->repo);
7338 if (err) {
7339 free(id_str);
7340 return err;
7342 for (i = 0; link_target[i] != '\0'; i++) {
7343 if (!isprint((unsigned char)link_target[i]))
7344 link_target[i] = '?';
7346 modestr = "@";
7348 else if (S_ISDIR(mode))
7349 modestr = "/";
7350 else if (mode & S_IXUSR)
7351 modestr = "*";
7352 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7353 got_tree_entry_get_name(te), modestr,
7354 link_target ? " -> ": "",
7355 link_target ? link_target : "") == -1) {
7356 free(id_str);
7357 free(link_target);
7358 return got_error_from_errno("asprintf");
7360 free(id_str);
7361 free(link_target);
7363 /* use full line width to determine view->maxx */
7364 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7365 if (err) {
7366 free(line);
7367 break;
7369 view->maxx = MAX(view->maxx, width);
7370 free(wline);
7371 wline = NULL;
7373 err = format_line(&wline, &width, &scrollx, line, view->x,
7374 view->ncols, 0, 0);
7375 if (err) {
7376 free(line);
7377 break;
7379 if (n == s->selected) {
7380 if (view->focussed)
7381 wstandout(view->window);
7382 s->selected_entry = te;
7384 tc = match_color(&s->colors, line);
7385 if (tc)
7386 wattr_on(view->window,
7387 COLOR_PAIR(tc->colorpair), NULL);
7388 waddwstr(view->window, &wline[scrollx]);
7389 if (tc)
7390 wattr_off(view->window,
7391 COLOR_PAIR(tc->colorpair), NULL);
7392 if (width < view->ncols)
7393 waddch(view->window, '\n');
7394 if (n == s->selected && view->focussed)
7395 wstandend(view->window);
7396 free(line);
7397 free(wline);
7398 wline = NULL;
7399 n++;
7400 s->ndisplayed++;
7401 s->last_displayed_entry = te;
7402 if (--limit <= 0)
7403 break;
7406 return err;
7409 static void
7410 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7412 struct got_tree_entry *te;
7413 int isroot = s->tree == s->root;
7414 int i = 0;
7416 if (s->first_displayed_entry == NULL)
7417 return;
7419 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7420 while (i++ < maxscroll) {
7421 if (te == NULL) {
7422 if (!isroot)
7423 s->first_displayed_entry = NULL;
7424 break;
7426 s->first_displayed_entry = te;
7427 te = got_tree_entry_get_prev(s->tree, te);
7431 static const struct got_error *
7432 tree_scroll_down(struct tog_view *view, int maxscroll)
7434 struct tog_tree_view_state *s = &view->state.tree;
7435 struct got_tree_entry *next, *last;
7436 int n = 0;
7438 if (s->first_displayed_entry)
7439 next = got_tree_entry_get_next(s->tree,
7440 s->first_displayed_entry);
7441 else
7442 next = got_object_tree_get_first_entry(s->tree);
7444 last = s->last_displayed_entry;
7445 while (next && n++ < maxscroll) {
7446 if (last) {
7447 s->last_displayed_entry = last;
7448 last = got_tree_entry_get_next(s->tree, last);
7450 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7451 s->first_displayed_entry = next;
7452 next = got_tree_entry_get_next(s->tree, next);
7456 return NULL;
7459 static const struct got_error *
7460 tree_entry_path(char **path, struct tog_parent_trees *parents,
7461 struct got_tree_entry *te)
7463 const struct got_error *err = NULL;
7464 struct tog_parent_tree *pt;
7465 size_t len = 2; /* for leading slash and NUL */
7467 TAILQ_FOREACH(pt, parents, entry)
7468 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7469 + 1 /* slash */;
7470 if (te)
7471 len += strlen(got_tree_entry_get_name(te));
7473 *path = calloc(1, len);
7474 if (path == NULL)
7475 return got_error_from_errno("calloc");
7477 (*path)[0] = '/';
7478 pt = TAILQ_LAST(parents, tog_parent_trees);
7479 while (pt) {
7480 const char *name = got_tree_entry_get_name(pt->selected_entry);
7481 if (strlcat(*path, name, len) >= len) {
7482 err = got_error(GOT_ERR_NO_SPACE);
7483 goto done;
7485 if (strlcat(*path, "/", len) >= len) {
7486 err = got_error(GOT_ERR_NO_SPACE);
7487 goto done;
7489 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7491 if (te) {
7492 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7493 err = got_error(GOT_ERR_NO_SPACE);
7494 goto done;
7497 done:
7498 if (err) {
7499 free(*path);
7500 *path = NULL;
7502 return err;
7505 static const struct got_error *
7506 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7507 struct got_tree_entry *te, struct tog_parent_trees *parents,
7508 struct got_object_id *commit_id, struct got_repository *repo)
7510 const struct got_error *err = NULL;
7511 char *path;
7512 struct tog_view *blame_view;
7514 *new_view = NULL;
7516 err = tree_entry_path(&path, parents, te);
7517 if (err)
7518 return err;
7520 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7521 if (blame_view == NULL) {
7522 err = got_error_from_errno("view_open");
7523 goto done;
7526 err = open_blame_view(blame_view, path, commit_id, repo);
7527 if (err) {
7528 if (err->code == GOT_ERR_CANCELLED)
7529 err = NULL;
7530 view_close(blame_view);
7531 } else
7532 *new_view = blame_view;
7533 done:
7534 free(path);
7535 return err;
7538 static const struct got_error *
7539 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7540 struct tog_tree_view_state *s)
7542 struct tog_view *log_view;
7543 const struct got_error *err = NULL;
7544 char *path;
7546 *new_view = NULL;
7548 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7549 if (log_view == NULL)
7550 return got_error_from_errno("view_open");
7552 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7553 if (err)
7554 return err;
7556 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7557 path, 0);
7558 if (err)
7559 view_close(log_view);
7560 else
7561 *new_view = log_view;
7562 free(path);
7563 return err;
7566 static const struct got_error *
7567 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7568 const char *head_ref_name, struct got_repository *repo)
7570 const struct got_error *err = NULL;
7571 char *commit_id_str = NULL;
7572 struct tog_tree_view_state *s = &view->state.tree;
7573 struct got_commit_object *commit = NULL;
7575 TAILQ_INIT(&s->parents);
7576 STAILQ_INIT(&s->colors);
7578 s->commit_id = got_object_id_dup(commit_id);
7579 if (s->commit_id == NULL) {
7580 err = got_error_from_errno("got_object_id_dup");
7581 goto done;
7584 err = got_object_open_as_commit(&commit, repo, commit_id);
7585 if (err)
7586 goto done;
7589 * The root is opened here and will be closed when the view is closed.
7590 * Any visited subtrees and their path-wise parents are opened and
7591 * closed on demand.
7593 err = got_object_open_as_tree(&s->root, repo,
7594 got_object_commit_get_tree_id(commit));
7595 if (err)
7596 goto done;
7597 s->tree = s->root;
7599 err = got_object_id_str(&commit_id_str, commit_id);
7600 if (err != NULL)
7601 goto done;
7603 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7604 err = got_error_from_errno("asprintf");
7605 goto done;
7608 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7609 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7610 if (head_ref_name) {
7611 s->head_ref_name = strdup(head_ref_name);
7612 if (s->head_ref_name == NULL) {
7613 err = got_error_from_errno("strdup");
7614 goto done;
7617 s->repo = repo;
7619 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7620 err = add_color(&s->colors, "\\$$",
7621 TOG_COLOR_TREE_SUBMODULE,
7622 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7623 if (err)
7624 goto done;
7625 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7626 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7627 if (err)
7628 goto done;
7629 err = add_color(&s->colors, "/$",
7630 TOG_COLOR_TREE_DIRECTORY,
7631 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7632 if (err)
7633 goto done;
7635 err = add_color(&s->colors, "\\*$",
7636 TOG_COLOR_TREE_EXECUTABLE,
7637 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7638 if (err)
7639 goto done;
7641 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7642 get_color_value("TOG_COLOR_COMMIT"));
7643 if (err)
7644 goto done;
7647 view->show = show_tree_view;
7648 view->input = input_tree_view;
7649 view->close = close_tree_view;
7650 view->search_start = search_start_tree_view;
7651 view->search_next = search_next_tree_view;
7652 done:
7653 free(commit_id_str);
7654 if (commit)
7655 got_object_commit_close(commit);
7656 if (err) {
7657 if (view->close == NULL)
7658 close_tree_view(view);
7659 view_close(view);
7661 return err;
7664 static const struct got_error *
7665 close_tree_view(struct tog_view *view)
7667 struct tog_tree_view_state *s = &view->state.tree;
7669 free_colors(&s->colors);
7670 free(s->tree_label);
7671 s->tree_label = NULL;
7672 free(s->commit_id);
7673 s->commit_id = NULL;
7674 free(s->head_ref_name);
7675 s->head_ref_name = NULL;
7676 while (!TAILQ_EMPTY(&s->parents)) {
7677 struct tog_parent_tree *parent;
7678 parent = TAILQ_FIRST(&s->parents);
7679 TAILQ_REMOVE(&s->parents, parent, entry);
7680 if (parent->tree != s->root)
7681 got_object_tree_close(parent->tree);
7682 free(parent);
7685 if (s->tree != NULL && s->tree != s->root)
7686 got_object_tree_close(s->tree);
7687 if (s->root)
7688 got_object_tree_close(s->root);
7689 return NULL;
7692 static const struct got_error *
7693 search_start_tree_view(struct tog_view *view)
7695 struct tog_tree_view_state *s = &view->state.tree;
7697 s->matched_entry = NULL;
7698 return NULL;
7701 static int
7702 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7704 regmatch_t regmatch;
7706 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7707 0) == 0;
7710 static const struct got_error *
7711 search_next_tree_view(struct tog_view *view)
7713 struct tog_tree_view_state *s = &view->state.tree;
7714 struct got_tree_entry *te = NULL;
7716 if (!view->searching) {
7717 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7718 return NULL;
7721 if (s->matched_entry) {
7722 if (view->searching == TOG_SEARCH_FORWARD) {
7723 if (s->selected_entry)
7724 te = got_tree_entry_get_next(s->tree,
7725 s->selected_entry);
7726 else
7727 te = got_object_tree_get_first_entry(s->tree);
7728 } else {
7729 if (s->selected_entry == NULL)
7730 te = got_object_tree_get_last_entry(s->tree);
7731 else
7732 te = got_tree_entry_get_prev(s->tree,
7733 s->selected_entry);
7735 } else {
7736 if (s->selected_entry)
7737 te = s->selected_entry;
7738 else if (view->searching == TOG_SEARCH_FORWARD)
7739 te = got_object_tree_get_first_entry(s->tree);
7740 else
7741 te = got_object_tree_get_last_entry(s->tree);
7744 while (1) {
7745 if (te == NULL) {
7746 if (s->matched_entry == NULL) {
7747 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7748 return NULL;
7750 if (view->searching == TOG_SEARCH_FORWARD)
7751 te = got_object_tree_get_first_entry(s->tree);
7752 else
7753 te = got_object_tree_get_last_entry(s->tree);
7756 if (match_tree_entry(te, &view->regex)) {
7757 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7758 s->matched_entry = te;
7759 break;
7762 if (view->searching == TOG_SEARCH_FORWARD)
7763 te = got_tree_entry_get_next(s->tree, te);
7764 else
7765 te = got_tree_entry_get_prev(s->tree, te);
7768 if (s->matched_entry) {
7769 s->first_displayed_entry = s->matched_entry;
7770 s->selected = 0;
7773 return NULL;
7776 static const struct got_error *
7777 show_tree_view(struct tog_view *view)
7779 const struct got_error *err = NULL;
7780 struct tog_tree_view_state *s = &view->state.tree;
7781 char *parent_path;
7783 err = tree_entry_path(&parent_path, &s->parents, NULL);
7784 if (err)
7785 return err;
7787 err = draw_tree_entries(view, parent_path);
7788 free(parent_path);
7790 view_border(view);
7791 return err;
7794 static const struct got_error *
7795 tree_goto_line(struct tog_view *view, int nlines)
7797 const struct got_error *err = NULL;
7798 struct tog_tree_view_state *s = &view->state.tree;
7799 struct got_tree_entry **fte, **lte, **ste;
7800 int g, last, first = 1, i = 1;
7801 int root = s->tree == s->root;
7802 int off = root ? 1 : 2;
7804 g = view->gline;
7805 view->gline = 0;
7807 if (g == 0)
7808 g = 1;
7809 else if (g > got_object_tree_get_nentries(s->tree))
7810 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7812 fte = &s->first_displayed_entry;
7813 lte = &s->last_displayed_entry;
7814 ste = &s->selected_entry;
7816 if (*fte != NULL) {
7817 first = got_tree_entry_get_index(*fte);
7818 first += off; /* account for ".." */
7820 last = got_tree_entry_get_index(*lte);
7821 last += off;
7823 if (g >= first && g <= last && g - first < nlines) {
7824 s->selected = g - first;
7825 return NULL; /* gline is on the current page */
7828 if (*ste != NULL) {
7829 i = got_tree_entry_get_index(*ste);
7830 i += off;
7833 if (i < g) {
7834 err = tree_scroll_down(view, g - i);
7835 if (err)
7836 return err;
7837 if (got_tree_entry_get_index(*lte) >=
7838 got_object_tree_get_nentries(s->tree) - 1 &&
7839 first + s->selected < g &&
7840 s->selected < s->ndisplayed - 1) {
7841 first = got_tree_entry_get_index(*fte);
7842 first += off;
7843 s->selected = g - first;
7845 } else if (i > g)
7846 tree_scroll_up(s, i - g);
7848 if (g < nlines &&
7849 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7850 s->selected = g - 1;
7852 return NULL;
7855 static const struct got_error *
7856 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7858 const struct got_error *err = NULL;
7859 struct tog_tree_view_state *s = &view->state.tree;
7860 struct got_tree_entry *te;
7861 int n, nscroll = view->nlines - 3;
7863 if (view->gline)
7864 return tree_goto_line(view, nscroll);
7866 switch (ch) {
7867 case '0':
7868 case '$':
7869 case KEY_RIGHT:
7870 case 'l':
7871 case KEY_LEFT:
7872 case 'h':
7873 horizontal_scroll_input(view, ch);
7874 break;
7875 case 'i':
7876 s->show_ids = !s->show_ids;
7877 view->count = 0;
7878 break;
7879 case 'L':
7880 view->count = 0;
7881 if (!s->selected_entry)
7882 break;
7883 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7884 break;
7885 case 'R':
7886 view->count = 0;
7887 err = view_request_new(new_view, view, TOG_VIEW_REF);
7888 break;
7889 case 'g':
7890 case '=':
7891 case KEY_HOME:
7892 s->selected = 0;
7893 view->count = 0;
7894 if (s->tree == s->root)
7895 s->first_displayed_entry =
7896 got_object_tree_get_first_entry(s->tree);
7897 else
7898 s->first_displayed_entry = NULL;
7899 break;
7900 case 'G':
7901 case '*':
7902 case KEY_END: {
7903 int eos = view->nlines - 3;
7905 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7906 --eos; /* border */
7907 s->selected = 0;
7908 view->count = 0;
7909 te = got_object_tree_get_last_entry(s->tree);
7910 for (n = 0; n < eos; n++) {
7911 if (te == NULL) {
7912 if (s->tree != s->root) {
7913 s->first_displayed_entry = NULL;
7914 n++;
7916 break;
7918 s->first_displayed_entry = te;
7919 te = got_tree_entry_get_prev(s->tree, te);
7921 if (n > 0)
7922 s->selected = n - 1;
7923 break;
7925 case 'k':
7926 case KEY_UP:
7927 case CTRL('p'):
7928 if (s->selected > 0) {
7929 s->selected--;
7930 break;
7932 tree_scroll_up(s, 1);
7933 if (s->selected_entry == NULL ||
7934 (s->tree == s->root && s->selected_entry ==
7935 got_object_tree_get_first_entry(s->tree)))
7936 view->count = 0;
7937 break;
7938 case CTRL('u'):
7939 case 'u':
7940 nscroll /= 2;
7941 /* FALL THROUGH */
7942 case KEY_PPAGE:
7943 case CTRL('b'):
7944 case 'b':
7945 if (s->tree == s->root) {
7946 if (got_object_tree_get_first_entry(s->tree) ==
7947 s->first_displayed_entry)
7948 s->selected -= MIN(s->selected, nscroll);
7949 } else {
7950 if (s->first_displayed_entry == NULL)
7951 s->selected -= MIN(s->selected, nscroll);
7953 tree_scroll_up(s, MAX(0, nscroll));
7954 if (s->selected_entry == NULL ||
7955 (s->tree == s->root && s->selected_entry ==
7956 got_object_tree_get_first_entry(s->tree)))
7957 view->count = 0;
7958 break;
7959 case 'j':
7960 case KEY_DOWN:
7961 case CTRL('n'):
7962 if (s->selected < s->ndisplayed - 1) {
7963 s->selected++;
7964 break;
7966 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7967 == NULL) {
7968 /* can't scroll any further */
7969 view->count = 0;
7970 break;
7972 tree_scroll_down(view, 1);
7973 break;
7974 case CTRL('d'):
7975 case 'd':
7976 nscroll /= 2;
7977 /* FALL THROUGH */
7978 case KEY_NPAGE:
7979 case CTRL('f'):
7980 case 'f':
7981 case ' ':
7982 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7983 == NULL) {
7984 /* can't scroll any further; move cursor down */
7985 if (s->selected < s->ndisplayed - 1)
7986 s->selected += MIN(nscroll,
7987 s->ndisplayed - s->selected - 1);
7988 else
7989 view->count = 0;
7990 break;
7992 tree_scroll_down(view, nscroll);
7993 break;
7994 case KEY_ENTER:
7995 case '\r':
7996 case KEY_BACKSPACE:
7997 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7998 struct tog_parent_tree *parent;
7999 /* user selected '..' */
8000 if (s->tree == s->root) {
8001 view->count = 0;
8002 break;
8004 parent = TAILQ_FIRST(&s->parents);
8005 TAILQ_REMOVE(&s->parents, parent,
8006 entry);
8007 got_object_tree_close(s->tree);
8008 s->tree = parent->tree;
8009 s->first_displayed_entry =
8010 parent->first_displayed_entry;
8011 s->selected_entry =
8012 parent->selected_entry;
8013 s->selected = parent->selected;
8014 if (s->selected > view->nlines - 3) {
8015 err = offset_selection_down(view);
8016 if (err)
8017 break;
8019 free(parent);
8020 } else if (S_ISDIR(got_tree_entry_get_mode(
8021 s->selected_entry))) {
8022 struct got_tree_object *subtree;
8023 view->count = 0;
8024 err = got_object_open_as_tree(&subtree, s->repo,
8025 got_tree_entry_get_id(s->selected_entry));
8026 if (err)
8027 break;
8028 err = tree_view_visit_subtree(s, subtree);
8029 if (err) {
8030 got_object_tree_close(subtree);
8031 break;
8033 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
8034 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
8035 break;
8036 case KEY_RESIZE:
8037 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
8038 s->selected = view->nlines - 4;
8039 view->count = 0;
8040 break;
8041 default:
8042 view->count = 0;
8043 break;
8046 return err;
8049 __dead static void
8050 usage_tree(void)
8052 endwin();
8053 fprintf(stderr,
8054 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
8055 getprogname());
8056 exit(1);
8059 static const struct got_error *
8060 cmd_tree(int argc, char *argv[])
8062 const struct got_error *error;
8063 struct got_repository *repo = NULL;
8064 struct got_worktree *worktree = NULL;
8065 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8066 struct got_object_id *commit_id = NULL;
8067 struct got_commit_object *commit = NULL;
8068 const char *commit_id_arg = NULL;
8069 char *keyword_idstr = NULL, *label = NULL;
8070 struct got_reference *ref = NULL;
8071 const char *head_ref_name = NULL;
8072 int ch;
8073 struct tog_view *view;
8074 int *pack_fds = NULL;
8076 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
8077 switch (ch) {
8078 case 'c':
8079 commit_id_arg = optarg;
8080 break;
8081 case 'r':
8082 repo_path = realpath(optarg, NULL);
8083 if (repo_path == NULL)
8084 return got_error_from_errno2("realpath",
8085 optarg);
8086 break;
8087 default:
8088 usage_tree();
8089 /* NOTREACHED */
8093 argc -= optind;
8094 argv += optind;
8096 if (argc > 1)
8097 usage_tree();
8099 error = got_repo_pack_fds_open(&pack_fds);
8100 if (error != NULL)
8101 goto done;
8103 if (repo_path == NULL) {
8104 cwd = getcwd(NULL, 0);
8105 if (cwd == NULL)
8106 return got_error_from_errno("getcwd");
8107 error = got_worktree_open(&worktree, cwd, NULL);
8108 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8109 goto done;
8110 if (worktree)
8111 repo_path =
8112 strdup(got_worktree_get_repo_path(worktree));
8113 else
8114 repo_path = strdup(cwd);
8115 if (repo_path == NULL) {
8116 error = got_error_from_errno("strdup");
8117 goto done;
8121 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8122 if (error != NULL)
8123 goto done;
8125 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8126 repo, worktree);
8127 if (error)
8128 goto done;
8130 init_curses();
8132 error = apply_unveil(got_repo_get_path(repo), NULL);
8133 if (error)
8134 goto done;
8136 error = tog_load_refs(repo, 0);
8137 if (error)
8138 goto done;
8140 if (commit_id_arg == NULL) {
8141 error = got_repo_match_object_id(&commit_id, &label,
8142 worktree ? got_worktree_get_head_ref_name(worktree) :
8143 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8144 if (error)
8145 goto done;
8146 head_ref_name = label;
8147 } else {
8148 error = got_keyword_to_idstr(&keyword_idstr, commit_id_arg,
8149 repo, worktree);
8150 if (error != NULL)
8151 goto done;
8152 if (keyword_idstr != NULL)
8153 commit_id_arg = keyword_idstr;
8155 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8156 if (error == NULL)
8157 head_ref_name = got_ref_get_name(ref);
8158 else if (error->code != GOT_ERR_NOT_REF)
8159 goto done;
8160 error = got_repo_match_object_id(&commit_id, NULL,
8161 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8162 if (error)
8163 goto done;
8166 error = got_object_open_as_commit(&commit, repo, commit_id);
8167 if (error)
8168 goto done;
8170 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8171 if (view == NULL) {
8172 error = got_error_from_errno("view_open");
8173 goto done;
8175 error = open_tree_view(view, commit_id, head_ref_name, repo);
8176 if (error)
8177 goto done;
8178 if (!got_path_is_root_dir(in_repo_path)) {
8179 error = tree_view_walk_path(&view->state.tree, commit,
8180 in_repo_path);
8181 if (error)
8182 goto done;
8185 if (worktree) {
8186 /* Release work tree lock. */
8187 got_worktree_close(worktree);
8188 worktree = NULL;
8190 error = view_loop(view);
8191 done:
8192 free(keyword_idstr);
8193 free(repo_path);
8194 free(cwd);
8195 free(commit_id);
8196 free(label);
8197 if (ref)
8198 got_ref_close(ref);
8199 if (repo) {
8200 const struct got_error *close_err = got_repo_close(repo);
8201 if (error == NULL)
8202 error = close_err;
8204 if (pack_fds) {
8205 const struct got_error *pack_err =
8206 got_repo_pack_fds_close(pack_fds);
8207 if (error == NULL)
8208 error = pack_err;
8210 tog_free_refs();
8211 return error;
8214 static const struct got_error *
8215 ref_view_load_refs(struct tog_ref_view_state *s)
8217 struct got_reflist_entry *sre;
8218 struct tog_reflist_entry *re;
8220 s->nrefs = 0;
8221 TAILQ_FOREACH(sre, &tog_refs, entry) {
8222 if (strncmp(got_ref_get_name(sre->ref),
8223 "refs/got/", 9) == 0 &&
8224 strncmp(got_ref_get_name(sre->ref),
8225 "refs/got/backup/", 16) != 0)
8226 continue;
8228 re = malloc(sizeof(*re));
8229 if (re == NULL)
8230 return got_error_from_errno("malloc");
8232 re->ref = got_ref_dup(sre->ref);
8233 if (re->ref == NULL)
8234 return got_error_from_errno("got_ref_dup");
8235 re->idx = s->nrefs++;
8236 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8239 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8240 return NULL;
8243 static void
8244 ref_view_free_refs(struct tog_ref_view_state *s)
8246 struct tog_reflist_entry *re;
8248 while (!TAILQ_EMPTY(&s->refs)) {
8249 re = TAILQ_FIRST(&s->refs);
8250 TAILQ_REMOVE(&s->refs, re, entry);
8251 got_ref_close(re->ref);
8252 free(re);
8256 static const struct got_error *
8257 open_ref_view(struct tog_view *view, struct got_repository *repo)
8259 const struct got_error *err = NULL;
8260 struct tog_ref_view_state *s = &view->state.ref;
8262 s->selected_entry = 0;
8263 s->repo = repo;
8265 TAILQ_INIT(&s->refs);
8266 STAILQ_INIT(&s->colors);
8268 err = ref_view_load_refs(s);
8269 if (err)
8270 goto done;
8272 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8273 err = add_color(&s->colors, "^refs/heads/",
8274 TOG_COLOR_REFS_HEADS,
8275 get_color_value("TOG_COLOR_REFS_HEADS"));
8276 if (err)
8277 goto done;
8279 err = add_color(&s->colors, "^refs/tags/",
8280 TOG_COLOR_REFS_TAGS,
8281 get_color_value("TOG_COLOR_REFS_TAGS"));
8282 if (err)
8283 goto done;
8285 err = add_color(&s->colors, "^refs/remotes/",
8286 TOG_COLOR_REFS_REMOTES,
8287 get_color_value("TOG_COLOR_REFS_REMOTES"));
8288 if (err)
8289 goto done;
8291 err = add_color(&s->colors, "^refs/got/backup/",
8292 TOG_COLOR_REFS_BACKUP,
8293 get_color_value("TOG_COLOR_REFS_BACKUP"));
8294 if (err)
8295 goto done;
8298 view->show = show_ref_view;
8299 view->input = input_ref_view;
8300 view->close = close_ref_view;
8301 view->search_start = search_start_ref_view;
8302 view->search_next = search_next_ref_view;
8303 done:
8304 if (err) {
8305 if (view->close == NULL)
8306 close_ref_view(view);
8307 view_close(view);
8309 return err;
8312 static const struct got_error *
8313 close_ref_view(struct tog_view *view)
8315 struct tog_ref_view_state *s = &view->state.ref;
8317 ref_view_free_refs(s);
8318 free_colors(&s->colors);
8320 return NULL;
8323 static const struct got_error *
8324 resolve_reflist_entry(struct got_object_id **commit_id,
8325 struct tog_reflist_entry *re, struct got_repository *repo)
8327 const struct got_error *err = NULL;
8328 struct got_object_id *obj_id;
8329 struct got_tag_object *tag = NULL;
8330 int obj_type;
8332 *commit_id = NULL;
8334 err = got_ref_resolve(&obj_id, repo, re->ref);
8335 if (err)
8336 return err;
8338 err = got_object_get_type(&obj_type, repo, obj_id);
8339 if (err)
8340 goto done;
8342 switch (obj_type) {
8343 case GOT_OBJ_TYPE_COMMIT:
8344 *commit_id = obj_id;
8345 break;
8346 case GOT_OBJ_TYPE_TAG:
8347 err = got_object_open_as_tag(&tag, repo, obj_id);
8348 if (err)
8349 goto done;
8350 free(obj_id);
8351 err = got_object_get_type(&obj_type, repo,
8352 got_object_tag_get_object_id(tag));
8353 if (err)
8354 goto done;
8355 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8356 err = got_error(GOT_ERR_OBJ_TYPE);
8357 goto done;
8359 *commit_id = got_object_id_dup(
8360 got_object_tag_get_object_id(tag));
8361 if (*commit_id == NULL) {
8362 err = got_error_from_errno("got_object_id_dup");
8363 goto done;
8365 break;
8366 default:
8367 err = got_error(GOT_ERR_OBJ_TYPE);
8368 break;
8371 done:
8372 if (tag)
8373 got_object_tag_close(tag);
8374 if (err) {
8375 free(*commit_id);
8376 *commit_id = NULL;
8378 return err;
8381 static const struct got_error *
8382 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8383 struct tog_reflist_entry *re, struct got_repository *repo)
8385 struct tog_view *log_view;
8386 const struct got_error *err = NULL;
8387 struct got_object_id *commit_id = NULL;
8389 *new_view = NULL;
8391 err = resolve_reflist_entry(&commit_id, re, repo);
8392 if (err) {
8393 if (err->code != GOT_ERR_OBJ_TYPE)
8394 return err;
8395 else
8396 return NULL;
8399 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8400 if (log_view == NULL) {
8401 err = got_error_from_errno("view_open");
8402 goto done;
8405 err = open_log_view(log_view, commit_id, repo,
8406 got_ref_get_name(re->ref), "", 0);
8407 done:
8408 if (err)
8409 view_close(log_view);
8410 else
8411 *new_view = log_view;
8412 free(commit_id);
8413 return err;
8416 static void
8417 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8419 struct tog_reflist_entry *re;
8420 int i = 0;
8422 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8423 return;
8425 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8426 while (i++ < maxscroll) {
8427 if (re == NULL)
8428 break;
8429 s->first_displayed_entry = re;
8430 re = TAILQ_PREV(re, tog_reflist_head, entry);
8434 static const struct got_error *
8435 ref_scroll_down(struct tog_view *view, int maxscroll)
8437 struct tog_ref_view_state *s = &view->state.ref;
8438 struct tog_reflist_entry *next, *last;
8439 int n = 0;
8441 if (s->first_displayed_entry)
8442 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8443 else
8444 next = TAILQ_FIRST(&s->refs);
8446 last = s->last_displayed_entry;
8447 while (next && n++ < maxscroll) {
8448 if (last) {
8449 s->last_displayed_entry = last;
8450 last = TAILQ_NEXT(last, entry);
8452 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8453 s->first_displayed_entry = next;
8454 next = TAILQ_NEXT(next, entry);
8458 return NULL;
8461 static const struct got_error *
8462 search_start_ref_view(struct tog_view *view)
8464 struct tog_ref_view_state *s = &view->state.ref;
8466 s->matched_entry = NULL;
8467 return NULL;
8470 static int
8471 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8473 regmatch_t regmatch;
8475 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8476 0) == 0;
8479 static const struct got_error *
8480 search_next_ref_view(struct tog_view *view)
8482 struct tog_ref_view_state *s = &view->state.ref;
8483 struct tog_reflist_entry *re = NULL;
8485 if (!view->searching) {
8486 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8487 return NULL;
8490 if (s->matched_entry) {
8491 if (view->searching == TOG_SEARCH_FORWARD) {
8492 if (s->selected_entry)
8493 re = TAILQ_NEXT(s->selected_entry, entry);
8494 else
8495 re = TAILQ_PREV(s->selected_entry,
8496 tog_reflist_head, entry);
8497 } else {
8498 if (s->selected_entry == NULL)
8499 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8500 else
8501 re = TAILQ_PREV(s->selected_entry,
8502 tog_reflist_head, entry);
8504 } else {
8505 if (s->selected_entry)
8506 re = s->selected_entry;
8507 else if (view->searching == TOG_SEARCH_FORWARD)
8508 re = TAILQ_FIRST(&s->refs);
8509 else
8510 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8513 while (1) {
8514 if (re == NULL) {
8515 if (s->matched_entry == NULL) {
8516 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8517 return NULL;
8519 if (view->searching == TOG_SEARCH_FORWARD)
8520 re = TAILQ_FIRST(&s->refs);
8521 else
8522 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8525 if (match_reflist_entry(re, &view->regex)) {
8526 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8527 s->matched_entry = re;
8528 break;
8531 if (view->searching == TOG_SEARCH_FORWARD)
8532 re = TAILQ_NEXT(re, entry);
8533 else
8534 re = TAILQ_PREV(re, tog_reflist_head, entry);
8537 if (s->matched_entry) {
8538 s->first_displayed_entry = s->matched_entry;
8539 s->selected = 0;
8542 return NULL;
8545 static const struct got_error *
8546 show_ref_view(struct tog_view *view)
8548 const struct got_error *err = NULL;
8549 struct tog_ref_view_state *s = &view->state.ref;
8550 struct tog_reflist_entry *re;
8551 char *line = NULL;
8552 wchar_t *wline;
8553 struct tog_color *tc;
8554 int width, n, scrollx;
8555 int limit = view->nlines;
8557 werase(view->window);
8559 s->ndisplayed = 0;
8560 if (view_is_hsplit_top(view))
8561 --limit; /* border */
8563 if (limit == 0)
8564 return NULL;
8566 re = s->first_displayed_entry;
8568 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8569 s->nrefs) == -1)
8570 return got_error_from_errno("asprintf");
8572 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8573 if (err) {
8574 free(line);
8575 return err;
8577 if (view_needs_focus_indication(view))
8578 wstandout(view->window);
8579 waddwstr(view->window, wline);
8580 while (width++ < view->ncols)
8581 waddch(view->window, ' ');
8582 if (view_needs_focus_indication(view))
8583 wstandend(view->window);
8584 free(wline);
8585 wline = NULL;
8586 free(line);
8587 line = NULL;
8588 if (--limit <= 0)
8589 return NULL;
8591 n = 0;
8592 view->maxx = 0;
8593 while (re && limit > 0) {
8594 char *line = NULL;
8595 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8597 if (s->show_date) {
8598 struct got_commit_object *ci;
8599 struct got_tag_object *tag;
8600 struct got_object_id *id;
8601 struct tm tm;
8602 time_t t;
8604 err = got_ref_resolve(&id, s->repo, re->ref);
8605 if (err)
8606 return err;
8607 err = got_object_open_as_tag(&tag, s->repo, id);
8608 if (err) {
8609 if (err->code != GOT_ERR_OBJ_TYPE) {
8610 free(id);
8611 return err;
8613 err = got_object_open_as_commit(&ci, s->repo,
8614 id);
8615 if (err) {
8616 free(id);
8617 return err;
8619 t = got_object_commit_get_committer_time(ci);
8620 got_object_commit_close(ci);
8621 } else {
8622 t = got_object_tag_get_tagger_time(tag);
8623 got_object_tag_close(tag);
8625 free(id);
8626 if (gmtime_r(&t, &tm) == NULL)
8627 return got_error_from_errno("gmtime_r");
8628 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8629 return got_error(GOT_ERR_NO_SPACE);
8631 if (got_ref_is_symbolic(re->ref)) {
8632 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8633 ymd : "", got_ref_get_name(re->ref),
8634 got_ref_get_symref_target(re->ref)) == -1)
8635 return got_error_from_errno("asprintf");
8636 } else if (s->show_ids) {
8637 struct got_object_id *id;
8638 char *id_str;
8639 err = got_ref_resolve(&id, s->repo, re->ref);
8640 if (err)
8641 return err;
8642 err = got_object_id_str(&id_str, id);
8643 if (err) {
8644 free(id);
8645 return err;
8647 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8648 got_ref_get_name(re->ref), id_str) == -1) {
8649 err = got_error_from_errno("asprintf");
8650 free(id);
8651 free(id_str);
8652 return err;
8654 free(id);
8655 free(id_str);
8656 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8657 got_ref_get_name(re->ref)) == -1)
8658 return got_error_from_errno("asprintf");
8660 /* use full line width to determine view->maxx */
8661 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8662 if (err) {
8663 free(line);
8664 return err;
8666 view->maxx = MAX(view->maxx, width);
8667 free(wline);
8668 wline = NULL;
8670 err = format_line(&wline, &width, &scrollx, line, view->x,
8671 view->ncols, 0, 0);
8672 if (err) {
8673 free(line);
8674 return err;
8676 if (n == s->selected) {
8677 if (view->focussed)
8678 wstandout(view->window);
8679 s->selected_entry = re;
8681 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8682 if (tc)
8683 wattr_on(view->window,
8684 COLOR_PAIR(tc->colorpair), NULL);
8685 waddwstr(view->window, &wline[scrollx]);
8686 if (tc)
8687 wattr_off(view->window,
8688 COLOR_PAIR(tc->colorpair), NULL);
8689 if (width < view->ncols)
8690 waddch(view->window, '\n');
8691 if (n == s->selected && view->focussed)
8692 wstandend(view->window);
8693 free(line);
8694 free(wline);
8695 wline = NULL;
8696 n++;
8697 s->ndisplayed++;
8698 s->last_displayed_entry = re;
8700 limit--;
8701 re = TAILQ_NEXT(re, entry);
8704 view_border(view);
8705 return err;
8708 static const struct got_error *
8709 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8710 struct tog_reflist_entry *re, struct got_repository *repo)
8712 const struct got_error *err = NULL;
8713 struct got_object_id *commit_id = NULL;
8714 struct tog_view *tree_view;
8716 *new_view = NULL;
8718 err = resolve_reflist_entry(&commit_id, re, repo);
8719 if (err) {
8720 if (err->code != GOT_ERR_OBJ_TYPE)
8721 return err;
8722 else
8723 return NULL;
8727 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8728 if (tree_view == NULL) {
8729 err = got_error_from_errno("view_open");
8730 goto done;
8733 err = open_tree_view(tree_view, commit_id,
8734 got_ref_get_name(re->ref), repo);
8735 if (err)
8736 goto done;
8738 *new_view = tree_view;
8739 done:
8740 free(commit_id);
8741 return err;
8744 static const struct got_error *
8745 ref_goto_line(struct tog_view *view, int nlines)
8747 const struct got_error *err = NULL;
8748 struct tog_ref_view_state *s = &view->state.ref;
8749 int g, idx = s->selected_entry->idx;
8751 g = view->gline;
8752 view->gline = 0;
8754 if (g == 0)
8755 g = 1;
8756 else if (g > s->nrefs)
8757 g = s->nrefs;
8759 if (g >= s->first_displayed_entry->idx + 1 &&
8760 g <= s->last_displayed_entry->idx + 1 &&
8761 g - s->first_displayed_entry->idx - 1 < nlines) {
8762 s->selected = g - s->first_displayed_entry->idx - 1;
8763 return NULL;
8766 if (idx + 1 < g) {
8767 err = ref_scroll_down(view, g - idx - 1);
8768 if (err)
8769 return err;
8770 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8771 s->first_displayed_entry->idx + s->selected < g &&
8772 s->selected < s->ndisplayed - 1)
8773 s->selected = g - s->first_displayed_entry->idx - 1;
8774 } else if (idx + 1 > g)
8775 ref_scroll_up(s, idx - g + 1);
8777 if (g < nlines && s->first_displayed_entry->idx == 0)
8778 s->selected = g - 1;
8780 return NULL;
8784 static const struct got_error *
8785 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8787 const struct got_error *err = NULL;
8788 struct tog_ref_view_state *s = &view->state.ref;
8789 struct tog_reflist_entry *re;
8790 int n, nscroll = view->nlines - 1;
8792 if (view->gline)
8793 return ref_goto_line(view, nscroll);
8795 switch (ch) {
8796 case '0':
8797 case '$':
8798 case KEY_RIGHT:
8799 case 'l':
8800 case KEY_LEFT:
8801 case 'h':
8802 horizontal_scroll_input(view, ch);
8803 break;
8804 case 'i':
8805 s->show_ids = !s->show_ids;
8806 view->count = 0;
8807 break;
8808 case 'm':
8809 s->show_date = !s->show_date;
8810 view->count = 0;
8811 break;
8812 case 'o':
8813 s->sort_by_date = !s->sort_by_date;
8814 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8815 view->count = 0;
8816 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8817 got_ref_cmp_by_commit_timestamp_descending :
8818 tog_ref_cmp_by_name, s->repo);
8819 if (err)
8820 break;
8821 got_reflist_object_id_map_free(tog_refs_idmap);
8822 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8823 &tog_refs, s->repo);
8824 if (err)
8825 break;
8826 ref_view_free_refs(s);
8827 err = ref_view_load_refs(s);
8828 break;
8829 case KEY_ENTER:
8830 case '\r':
8831 view->count = 0;
8832 if (!s->selected_entry)
8833 break;
8834 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8835 break;
8836 case 'T':
8837 view->count = 0;
8838 if (!s->selected_entry)
8839 break;
8840 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8841 break;
8842 case 'g':
8843 case '=':
8844 case KEY_HOME:
8845 s->selected = 0;
8846 view->count = 0;
8847 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8848 break;
8849 case 'G':
8850 case '*':
8851 case KEY_END: {
8852 int eos = view->nlines - 1;
8854 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8855 --eos; /* border */
8856 s->selected = 0;
8857 view->count = 0;
8858 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8859 for (n = 0; n < eos; n++) {
8860 if (re == NULL)
8861 break;
8862 s->first_displayed_entry = re;
8863 re = TAILQ_PREV(re, tog_reflist_head, entry);
8865 if (n > 0)
8866 s->selected = n - 1;
8867 break;
8869 case 'k':
8870 case KEY_UP:
8871 case CTRL('p'):
8872 if (s->selected > 0) {
8873 s->selected--;
8874 break;
8876 ref_scroll_up(s, 1);
8877 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8878 view->count = 0;
8879 break;
8880 case CTRL('u'):
8881 case 'u':
8882 nscroll /= 2;
8883 /* FALL THROUGH */
8884 case KEY_PPAGE:
8885 case CTRL('b'):
8886 case 'b':
8887 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8888 s->selected -= MIN(nscroll, s->selected);
8889 ref_scroll_up(s, MAX(0, nscroll));
8890 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8891 view->count = 0;
8892 break;
8893 case 'j':
8894 case KEY_DOWN:
8895 case CTRL('n'):
8896 if (s->selected < s->ndisplayed - 1) {
8897 s->selected++;
8898 break;
8900 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8901 /* can't scroll any further */
8902 view->count = 0;
8903 break;
8905 ref_scroll_down(view, 1);
8906 break;
8907 case CTRL('d'):
8908 case 'd':
8909 nscroll /= 2;
8910 /* FALL THROUGH */
8911 case KEY_NPAGE:
8912 case CTRL('f'):
8913 case 'f':
8914 case ' ':
8915 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8916 /* can't scroll any further; move cursor down */
8917 if (s->selected < s->ndisplayed - 1)
8918 s->selected += MIN(nscroll,
8919 s->ndisplayed - s->selected - 1);
8920 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8921 s->selected += s->ndisplayed - s->selected - 1;
8922 view->count = 0;
8923 break;
8925 ref_scroll_down(view, nscroll);
8926 break;
8927 case CTRL('l'):
8928 view->count = 0;
8929 tog_free_refs();
8930 err = tog_load_refs(s->repo, s->sort_by_date);
8931 if (err)
8932 break;
8933 ref_view_free_refs(s);
8934 err = ref_view_load_refs(s);
8935 break;
8936 case KEY_RESIZE:
8937 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8938 s->selected = view->nlines - 2;
8939 break;
8940 default:
8941 view->count = 0;
8942 break;
8945 return err;
8948 __dead static void
8949 usage_ref(void)
8951 endwin();
8952 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8953 getprogname());
8954 exit(1);
8957 static const struct got_error *
8958 cmd_ref(int argc, char *argv[])
8960 const struct got_error *error;
8961 struct got_repository *repo = NULL;
8962 struct got_worktree *worktree = NULL;
8963 char *cwd = NULL, *repo_path = NULL;
8964 int ch;
8965 struct tog_view *view;
8966 int *pack_fds = NULL;
8968 while ((ch = getopt(argc, argv, "r:")) != -1) {
8969 switch (ch) {
8970 case 'r':
8971 repo_path = realpath(optarg, NULL);
8972 if (repo_path == NULL)
8973 return got_error_from_errno2("realpath",
8974 optarg);
8975 break;
8976 default:
8977 usage_ref();
8978 /* NOTREACHED */
8982 argc -= optind;
8983 argv += optind;
8985 if (argc > 1)
8986 usage_ref();
8988 error = got_repo_pack_fds_open(&pack_fds);
8989 if (error != NULL)
8990 goto done;
8992 if (repo_path == NULL) {
8993 cwd = getcwd(NULL, 0);
8994 if (cwd == NULL)
8995 return got_error_from_errno("getcwd");
8996 error = got_worktree_open(&worktree, cwd, NULL);
8997 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8998 goto done;
8999 if (worktree)
9000 repo_path =
9001 strdup(got_worktree_get_repo_path(worktree));
9002 else
9003 repo_path = strdup(cwd);
9004 if (repo_path == NULL) {
9005 error = got_error_from_errno("strdup");
9006 goto done;
9010 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9011 if (error != NULL)
9012 goto done;
9014 init_curses();
9016 error = apply_unveil(got_repo_get_path(repo), NULL);
9017 if (error)
9018 goto done;
9020 error = tog_load_refs(repo, 0);
9021 if (error)
9022 goto done;
9024 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
9025 if (view == NULL) {
9026 error = got_error_from_errno("view_open");
9027 goto done;
9030 error = open_ref_view(view, repo);
9031 if (error)
9032 goto done;
9034 if (worktree) {
9035 /* Release work tree lock. */
9036 got_worktree_close(worktree);
9037 worktree = NULL;
9039 error = view_loop(view);
9040 done:
9041 free(repo_path);
9042 free(cwd);
9043 if (repo) {
9044 const struct got_error *close_err = got_repo_close(repo);
9045 if (close_err)
9046 error = close_err;
9048 if (pack_fds) {
9049 const struct got_error *pack_err =
9050 got_repo_pack_fds_close(pack_fds);
9051 if (error == NULL)
9052 error = pack_err;
9054 tog_free_refs();
9055 return error;
9058 static const struct got_error*
9059 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
9060 const char *str)
9062 size_t len;
9064 if (win == NULL)
9065 win = stdscr;
9067 len = strlen(str);
9068 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
9070 if (focus)
9071 wstandout(win);
9072 if (mvwprintw(win, y, x, "%s", str) == ERR)
9073 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
9074 if (focus)
9075 wstandend(win);
9077 return NULL;
9080 static const struct got_error *
9081 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
9083 off_t *p;
9085 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
9086 if (p == NULL) {
9087 free(*line_offsets);
9088 *line_offsets = NULL;
9089 return got_error_from_errno("reallocarray");
9092 *line_offsets = p;
9093 (*line_offsets)[*nlines] = off;
9094 ++(*nlines);
9095 return NULL;
9098 static const struct got_error *
9099 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
9101 *ret = 0;
9103 for (;n > 0; --n, ++km) {
9104 char *t0, *t, *k;
9105 size_t len = 1;
9107 if (km->keys == NULL)
9108 continue;
9110 t = t0 = strdup(km->keys);
9111 if (t0 == NULL)
9112 return got_error_from_errno("strdup");
9114 len += strlen(t);
9115 while ((k = strsep(&t, " ")) != NULL)
9116 len += strlen(k) > 1 ? 2 : 0;
9117 free(t0);
9118 *ret = MAX(*ret, len);
9121 return NULL;
9125 * Write keymap section headers, keys, and key info in km to f.
9126 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9127 * wrap control and symbolic keys in guillemets, else use <>.
9129 static const struct got_error *
9130 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9132 int n, len = width;
9134 if (km->keys) {
9135 static const char *u8_glyph[] = {
9136 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9137 "\xe2\x80\xba" /* U+203A (utf8 >) */
9139 char *t0, *t, *k;
9140 int cs, s, first = 1;
9142 cs = got_locale_is_utf8();
9144 t = t0 = strdup(km->keys);
9145 if (t0 == NULL)
9146 return got_error_from_errno("strdup");
9148 len = strlen(km->keys);
9149 while ((k = strsep(&t, " ")) != NULL) {
9150 s = strlen(k) > 1; /* control or symbolic key */
9151 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9152 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9153 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9154 if (n < 0) {
9155 free(t0);
9156 return got_error_from_errno("fprintf");
9158 first = 0;
9159 len += s ? 2 : 0;
9160 *off += n;
9162 free(t0);
9164 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9165 if (n < 0)
9166 return got_error_from_errno("fprintf");
9167 *off += n;
9169 return NULL;
9172 static const struct got_error *
9173 format_help(struct tog_help_view_state *s)
9175 const struct got_error *err = NULL;
9176 off_t off = 0;
9177 int i, max, n, show = s->all;
9178 static const struct tog_key_map km[] = {
9179 #define KEYMAP_(info, type) { NULL, (info), type }
9180 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9181 GENERATE_HELP
9182 #undef KEYMAP_
9183 #undef KEY_
9186 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9187 if (err)
9188 return err;
9190 n = nitems(km);
9191 err = max_key_str(&max, km, n);
9192 if (err)
9193 return err;
9195 for (i = 0; i < n; ++i) {
9196 if (km[i].keys == NULL) {
9197 show = s->all;
9198 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9199 km[i].type == s->type || s->all)
9200 show = 1;
9202 if (show) {
9203 err = format_help_line(&off, s->f, &km[i], max);
9204 if (err)
9205 return err;
9206 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9207 if (err)
9208 return err;
9211 fputc('\n', s->f);
9212 ++off;
9213 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9214 return err;
9217 static const struct got_error *
9218 create_help(struct tog_help_view_state *s)
9220 FILE *f;
9221 const struct got_error *err;
9223 free(s->line_offsets);
9224 s->line_offsets = NULL;
9225 s->nlines = 0;
9227 f = got_opentemp();
9228 if (f == NULL)
9229 return got_error_from_errno("got_opentemp");
9230 s->f = f;
9232 err = format_help(s);
9233 if (err)
9234 return err;
9236 if (s->f && fflush(s->f) != 0)
9237 return got_error_from_errno("fflush");
9239 return NULL;
9242 static const struct got_error *
9243 search_start_help_view(struct tog_view *view)
9245 view->state.help.matched_line = 0;
9246 return NULL;
9249 static void
9250 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9251 size_t *nlines, int **first, int **last, int **match, int **selected)
9253 struct tog_help_view_state *s = &view->state.help;
9255 *f = s->f;
9256 *nlines = s->nlines;
9257 *line_offsets = s->line_offsets;
9258 *match = &s->matched_line;
9259 *first = &s->first_displayed_line;
9260 *last = &s->last_displayed_line;
9261 *selected = &s->selected_line;
9264 static const struct got_error *
9265 show_help_view(struct tog_view *view)
9267 struct tog_help_view_state *s = &view->state.help;
9268 const struct got_error *err;
9269 regmatch_t *regmatch = &view->regmatch;
9270 wchar_t *wline;
9271 char *line;
9272 ssize_t linelen;
9273 size_t linesz = 0;
9274 int width, nprinted = 0, rc = 0;
9275 int eos = view->nlines;
9277 if (view_is_hsplit_top(view))
9278 --eos; /* account for border */
9280 s->lineno = 0;
9281 rewind(s->f);
9282 werase(view->window);
9284 if (view->gline > s->nlines - 1)
9285 view->gline = s->nlines - 1;
9287 err = win_draw_center(view->window, 0, 0, view->ncols,
9288 view_needs_focus_indication(view),
9289 "tog help (press q to return to tog)");
9290 if (err)
9291 return err;
9292 if (eos <= 1)
9293 return NULL;
9294 waddstr(view->window, "\n\n");
9295 eos -= 2;
9297 s->eof = 0;
9298 view->maxx = 0;
9299 line = NULL;
9300 while (eos > 0 && nprinted < eos) {
9301 attr_t attr = 0;
9303 linelen = getline(&line, &linesz, s->f);
9304 if (linelen == -1) {
9305 if (!feof(s->f)) {
9306 free(line);
9307 return got_ferror(s->f, GOT_ERR_IO);
9309 s->eof = 1;
9310 break;
9312 if (++s->lineno < s->first_displayed_line)
9313 continue;
9314 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9315 continue;
9316 if (s->lineno == view->hiline)
9317 attr = A_STANDOUT;
9319 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9320 view->x ? 1 : 0);
9321 if (err) {
9322 free(line);
9323 return err;
9325 view->maxx = MAX(view->maxx, width);
9326 free(wline);
9327 wline = NULL;
9329 if (attr)
9330 wattron(view->window, attr);
9331 if (s->first_displayed_line + nprinted == s->matched_line &&
9332 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9333 err = add_matched_line(&width, line, view->ncols - 1, 0,
9334 view->window, view->x, regmatch);
9335 if (err) {
9336 free(line);
9337 return err;
9339 } else {
9340 int skip;
9342 err = format_line(&wline, &width, &skip, line,
9343 view->x, view->ncols, 0, view->x ? 1 : 0);
9344 if (err) {
9345 free(line);
9346 return err;
9348 waddwstr(view->window, &wline[skip]);
9349 free(wline);
9350 wline = NULL;
9352 if (s->lineno == view->hiline) {
9353 while (width++ < view->ncols)
9354 waddch(view->window, ' ');
9355 } else {
9356 if (width < view->ncols)
9357 waddch(view->window, '\n');
9359 if (attr)
9360 wattroff(view->window, attr);
9361 if (++nprinted == 1)
9362 s->first_displayed_line = s->lineno;
9364 free(line);
9365 if (nprinted > 0)
9366 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9367 else
9368 s->last_displayed_line = s->first_displayed_line;
9370 view_border(view);
9372 if (s->eof) {
9373 rc = waddnstr(view->window,
9374 "See the tog(1) manual page for full documentation",
9375 view->ncols - 1);
9376 if (rc == ERR)
9377 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9378 } else {
9379 wmove(view->window, view->nlines - 1, 0);
9380 wclrtoeol(view->window);
9381 wstandout(view->window);
9382 rc = waddnstr(view->window, "scroll down for more...",
9383 view->ncols - 1);
9384 if (rc == ERR)
9385 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9386 if (getcurx(view->window) < view->ncols - 6) {
9387 rc = wprintw(view->window, "[%.0f%%]",
9388 100.00 * s->last_displayed_line / s->nlines);
9389 if (rc == ERR)
9390 return got_error_msg(GOT_ERR_IO, "wprintw");
9392 wstandend(view->window);
9395 return NULL;
9398 static const struct got_error *
9399 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9401 struct tog_help_view_state *s = &view->state.help;
9402 const struct got_error *err = NULL;
9403 char *line = NULL;
9404 ssize_t linelen;
9405 size_t linesz = 0;
9406 int eos, nscroll;
9408 eos = nscroll = view->nlines;
9409 if (view_is_hsplit_top(view))
9410 --eos; /* border */
9412 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9414 switch (ch) {
9415 case '0':
9416 case '$':
9417 case KEY_RIGHT:
9418 case 'l':
9419 case KEY_LEFT:
9420 case 'h':
9421 horizontal_scroll_input(view, ch);
9422 break;
9423 case 'g':
9424 case KEY_HOME:
9425 s->first_displayed_line = 1;
9426 view->count = 0;
9427 break;
9428 case 'G':
9429 case KEY_END:
9430 view->count = 0;
9431 if (s->eof)
9432 break;
9433 s->first_displayed_line = (s->nlines - eos) + 3;
9434 s->eof = 1;
9435 break;
9436 case 'k':
9437 case KEY_UP:
9438 if (s->first_displayed_line > 1)
9439 --s->first_displayed_line;
9440 else
9441 view->count = 0;
9442 break;
9443 case CTRL('u'):
9444 case 'u':
9445 nscroll /= 2;
9446 /* FALL THROUGH */
9447 case KEY_PPAGE:
9448 case CTRL('b'):
9449 case 'b':
9450 if (s->first_displayed_line == 1) {
9451 view->count = 0;
9452 break;
9454 while (--nscroll > 0 && s->first_displayed_line > 1)
9455 s->first_displayed_line--;
9456 break;
9457 case 'j':
9458 case KEY_DOWN:
9459 case CTRL('n'):
9460 if (!s->eof)
9461 ++s->first_displayed_line;
9462 else
9463 view->count = 0;
9464 break;
9465 case CTRL('d'):
9466 case 'd':
9467 nscroll /= 2;
9468 /* FALL THROUGH */
9469 case KEY_NPAGE:
9470 case CTRL('f'):
9471 case 'f':
9472 case ' ':
9473 if (s->eof) {
9474 view->count = 0;
9475 break;
9477 while (!s->eof && --nscroll > 0) {
9478 linelen = getline(&line, &linesz, s->f);
9479 s->first_displayed_line++;
9480 if (linelen == -1) {
9481 if (feof(s->f))
9482 s->eof = 1;
9483 else
9484 err = got_ferror(s->f, GOT_ERR_IO);
9485 break;
9488 free(line);
9489 break;
9490 default:
9491 view->count = 0;
9492 break;
9495 return err;
9498 static const struct got_error *
9499 close_help_view(struct tog_view *view)
9501 struct tog_help_view_state *s = &view->state.help;
9503 free(s->line_offsets);
9504 s->line_offsets = NULL;
9505 if (fclose(s->f) == EOF)
9506 return got_error_from_errno("fclose");
9508 return NULL;
9511 static const struct got_error *
9512 reset_help_view(struct tog_view *view)
9514 struct tog_help_view_state *s = &view->state.help;
9517 if (s->f && fclose(s->f) == EOF)
9518 return got_error_from_errno("fclose");
9520 wclear(view->window);
9521 view->count = 0;
9522 view->x = 0;
9523 s->all = !s->all;
9524 s->first_displayed_line = 1;
9525 s->last_displayed_line = view->nlines;
9526 s->matched_line = 0;
9528 return create_help(s);
9531 static const struct got_error *
9532 open_help_view(struct tog_view *view, struct tog_view *parent)
9534 const struct got_error *err = NULL;
9535 struct tog_help_view_state *s = &view->state.help;
9537 s->type = (enum tog_keymap_type)parent->type;
9538 s->first_displayed_line = 1;
9539 s->last_displayed_line = view->nlines;
9540 s->selected_line = 1;
9542 view->show = show_help_view;
9543 view->input = input_help_view;
9544 view->reset = reset_help_view;
9545 view->close = close_help_view;
9546 view->search_start = search_start_help_view;
9547 view->search_setup = search_setup_help_view;
9548 view->search_next = search_next_view_match;
9550 err = create_help(s);
9551 return err;
9554 static const struct got_error *
9555 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9556 enum tog_view_type request, int y, int x)
9558 const struct got_error *err = NULL;
9560 *new_view = NULL;
9562 switch (request) {
9563 case TOG_VIEW_DIFF:
9564 if (view->type == TOG_VIEW_LOG) {
9565 struct tog_log_view_state *s = &view->state.log;
9567 err = open_diff_view_for_commit(new_view, y, x,
9568 s->selected_entry->commit, s->selected_entry->id,
9569 view, s->repo);
9570 } else
9571 return got_error_msg(GOT_ERR_NOT_IMPL,
9572 "parent/child view pair not supported");
9573 break;
9574 case TOG_VIEW_BLAME:
9575 if (view->type == TOG_VIEW_TREE) {
9576 struct tog_tree_view_state *s = &view->state.tree;
9578 err = blame_tree_entry(new_view, y, x,
9579 s->selected_entry, &s->parents, s->commit_id,
9580 s->repo);
9581 } else
9582 return got_error_msg(GOT_ERR_NOT_IMPL,
9583 "parent/child view pair not supported");
9584 break;
9585 case TOG_VIEW_LOG:
9586 if (view->type == TOG_VIEW_BLAME)
9587 err = log_annotated_line(new_view, y, x,
9588 view->state.blame.repo, view->state.blame.id_to_log);
9589 else if (view->type == TOG_VIEW_TREE)
9590 err = log_selected_tree_entry(new_view, y, x,
9591 &view->state.tree);
9592 else if (view->type == TOG_VIEW_REF)
9593 err = log_ref_entry(new_view, y, x,
9594 view->state.ref.selected_entry,
9595 view->state.ref.repo);
9596 else
9597 return got_error_msg(GOT_ERR_NOT_IMPL,
9598 "parent/child view pair not supported");
9599 break;
9600 case TOG_VIEW_TREE:
9601 if (view->type == TOG_VIEW_LOG)
9602 err = browse_commit_tree(new_view, y, x,
9603 view->state.log.selected_entry,
9604 view->state.log.in_repo_path,
9605 view->state.log.head_ref_name,
9606 view->state.log.repo);
9607 else if (view->type == TOG_VIEW_REF)
9608 err = browse_ref_tree(new_view, y, x,
9609 view->state.ref.selected_entry,
9610 view->state.ref.repo);
9611 else
9612 return got_error_msg(GOT_ERR_NOT_IMPL,
9613 "parent/child view pair not supported");
9614 break;
9615 case TOG_VIEW_REF:
9616 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9617 if (*new_view == NULL)
9618 return got_error_from_errno("view_open");
9619 if (view->type == TOG_VIEW_LOG)
9620 err = open_ref_view(*new_view, view->state.log.repo);
9621 else if (view->type == TOG_VIEW_TREE)
9622 err = open_ref_view(*new_view, view->state.tree.repo);
9623 else
9624 err = got_error_msg(GOT_ERR_NOT_IMPL,
9625 "parent/child view pair not supported");
9626 if (err)
9627 view_close(*new_view);
9628 break;
9629 case TOG_VIEW_HELP:
9630 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9631 if (*new_view == NULL)
9632 return got_error_from_errno("view_open");
9633 err = open_help_view(*new_view, view);
9634 if (err)
9635 view_close(*new_view);
9636 break;
9637 default:
9638 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9641 return err;
9645 * If view was scrolled down to move the selected line into view when opening a
9646 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9648 static void
9649 offset_selection_up(struct tog_view *view)
9651 switch (view->type) {
9652 case TOG_VIEW_BLAME: {
9653 struct tog_blame_view_state *s = &view->state.blame;
9654 if (s->first_displayed_line == 1) {
9655 s->selected_line = MAX(s->selected_line - view->offset,
9656 1);
9657 break;
9659 if (s->first_displayed_line > view->offset)
9660 s->first_displayed_line -= view->offset;
9661 else
9662 s->first_displayed_line = 1;
9663 s->selected_line += view->offset;
9664 break;
9666 case TOG_VIEW_LOG:
9667 log_scroll_up(&view->state.log, view->offset);
9668 view->state.log.selected += view->offset;
9669 break;
9670 case TOG_VIEW_REF:
9671 ref_scroll_up(&view->state.ref, view->offset);
9672 view->state.ref.selected += view->offset;
9673 break;
9674 case TOG_VIEW_TREE:
9675 tree_scroll_up(&view->state.tree, view->offset);
9676 view->state.tree.selected += view->offset;
9677 break;
9678 default:
9679 break;
9682 view->offset = 0;
9686 * If the selected line is in the section of screen covered by the bottom split,
9687 * scroll down offset lines to move it into view and index its new position.
9689 static const struct got_error *
9690 offset_selection_down(struct tog_view *view)
9692 const struct got_error *err = NULL;
9693 const struct got_error *(*scrolld)(struct tog_view *, int);
9694 int *selected = NULL;
9695 int header, offset;
9697 switch (view->type) {
9698 case TOG_VIEW_BLAME: {
9699 struct tog_blame_view_state *s = &view->state.blame;
9700 header = 3;
9701 scrolld = NULL;
9702 if (s->selected_line > view->nlines - header) {
9703 offset = abs(view->nlines - s->selected_line - header);
9704 s->first_displayed_line += offset;
9705 s->selected_line -= offset;
9706 view->offset = offset;
9708 break;
9710 case TOG_VIEW_LOG: {
9711 struct tog_log_view_state *s = &view->state.log;
9712 scrolld = &log_scroll_down;
9713 header = view_is_parent_view(view) ? 3 : 2;
9714 selected = &s->selected;
9715 break;
9717 case TOG_VIEW_REF: {
9718 struct tog_ref_view_state *s = &view->state.ref;
9719 scrolld = &ref_scroll_down;
9720 header = 3;
9721 selected = &s->selected;
9722 break;
9724 case TOG_VIEW_TREE: {
9725 struct tog_tree_view_state *s = &view->state.tree;
9726 scrolld = &tree_scroll_down;
9727 header = 5;
9728 selected = &s->selected;
9729 break;
9731 default:
9732 selected = NULL;
9733 scrolld = NULL;
9734 header = 0;
9735 break;
9738 if (selected && *selected > view->nlines - header) {
9739 offset = abs(view->nlines - *selected - header);
9740 view->offset = offset;
9741 if (scrolld && offset) {
9742 err = scrolld(view, offset);
9743 *selected -= offset;
9747 return err;
9750 static void
9751 list_commands(FILE *fp)
9753 size_t i;
9755 fprintf(fp, "commands:");
9756 for (i = 0; i < nitems(tog_commands); i++) {
9757 const struct tog_cmd *cmd = &tog_commands[i];
9758 fprintf(fp, " %s", cmd->name);
9760 fputc('\n', fp);
9763 __dead static void
9764 usage(int hflag, int status)
9766 FILE *fp = (status == 0) ? stdout : stderr;
9768 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9769 getprogname());
9770 if (hflag) {
9771 fprintf(fp, "lazy usage: %s path\n", getprogname());
9772 list_commands(fp);
9774 exit(status);
9777 static char **
9778 make_argv(int argc, ...)
9780 va_list ap;
9781 char **argv;
9782 int i;
9784 va_start(ap, argc);
9786 argv = calloc(argc, sizeof(char *));
9787 if (argv == NULL)
9788 err(1, "calloc");
9789 for (i = 0; i < argc; i++) {
9790 argv[i] = strdup(va_arg(ap, char *));
9791 if (argv[i] == NULL)
9792 err(1, "strdup");
9795 va_end(ap);
9796 return argv;
9800 * Try to convert 'tog path' into a 'tog log path' command.
9801 * The user could simply have mistyped the command rather than knowingly
9802 * provided a path. So check whether argv[0] can in fact be resolved
9803 * to a path in the HEAD commit and print a special error if not.
9804 * This hack is for mpi@ <3
9806 static const struct got_error *
9807 tog_log_with_path(int argc, char *argv[])
9809 const struct got_error *error = NULL, *close_err;
9810 const struct tog_cmd *cmd = NULL;
9811 struct got_repository *repo = NULL;
9812 struct got_worktree *worktree = NULL;
9813 struct got_object_id *commit_id = NULL, *id = NULL;
9814 struct got_commit_object *commit = NULL;
9815 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9816 char *commit_id_str = NULL, **cmd_argv = NULL;
9817 int *pack_fds = NULL;
9819 cwd = getcwd(NULL, 0);
9820 if (cwd == NULL)
9821 return got_error_from_errno("getcwd");
9823 error = got_repo_pack_fds_open(&pack_fds);
9824 if (error != NULL)
9825 goto done;
9827 error = got_worktree_open(&worktree, cwd, NULL);
9828 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9829 goto done;
9831 if (worktree)
9832 repo_path = strdup(got_worktree_get_repo_path(worktree));
9833 else
9834 repo_path = strdup(cwd);
9835 if (repo_path == NULL) {
9836 error = got_error_from_errno("strdup");
9837 goto done;
9840 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9841 if (error != NULL)
9842 goto done;
9844 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9845 repo, worktree);
9846 if (error)
9847 goto done;
9849 error = tog_load_refs(repo, 0);
9850 if (error)
9851 goto done;
9852 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9853 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9854 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9855 if (error)
9856 goto done;
9858 if (worktree) {
9859 got_worktree_close(worktree);
9860 worktree = NULL;
9863 error = got_object_open_as_commit(&commit, repo, commit_id);
9864 if (error)
9865 goto done;
9867 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9868 if (error) {
9869 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9870 goto done;
9871 fprintf(stderr, "%s: '%s' is no known command or path\n",
9872 getprogname(), argv[0]);
9873 usage(1, 1);
9874 /* not reached */
9877 error = got_object_id_str(&commit_id_str, commit_id);
9878 if (error)
9879 goto done;
9881 cmd = &tog_commands[0]; /* log */
9882 argc = 4;
9883 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9884 error = cmd->cmd_main(argc, cmd_argv);
9885 done:
9886 if (repo) {
9887 close_err = got_repo_close(repo);
9888 if (error == NULL)
9889 error = close_err;
9891 if (commit)
9892 got_object_commit_close(commit);
9893 if (worktree)
9894 got_worktree_close(worktree);
9895 if (pack_fds) {
9896 const struct got_error *pack_err =
9897 got_repo_pack_fds_close(pack_fds);
9898 if (error == NULL)
9899 error = pack_err;
9901 free(id);
9902 free(commit_id_str);
9903 free(commit_id);
9904 free(cwd);
9905 free(repo_path);
9906 free(in_repo_path);
9907 if (cmd_argv) {
9908 int i;
9909 for (i = 0; i < argc; i++)
9910 free(cmd_argv[i]);
9911 free(cmd_argv);
9913 tog_free_refs();
9914 return error;
9917 int
9918 main(int argc, char *argv[])
9920 const struct got_error *io_err, *error = NULL;
9921 const struct tog_cmd *cmd = NULL;
9922 int ch, hflag = 0, Vflag = 0;
9923 char **cmd_argv = NULL;
9924 static const struct option longopts[] = {
9925 { "version", no_argument, NULL, 'V' },
9926 { NULL, 0, NULL, 0}
9928 char *diff_algo_str = NULL;
9929 const char *test_script_path;
9931 setlocale(LC_CTYPE, "");
9934 * Test mode init must happen before pledge() because "tty" will
9935 * not allow TTY-related ioctls to occur via regular files.
9937 test_script_path = getenv("TOG_TEST_SCRIPT");
9938 if (test_script_path != NULL) {
9939 error = init_mock_term(test_script_path);
9940 if (error) {
9941 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9942 return 1;
9944 } else if (!isatty(STDIN_FILENO))
9945 errx(1, "standard input is not a tty");
9947 #if !defined(PROFILE)
9948 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9949 NULL) == -1)
9950 err(1, "pledge");
9951 #endif
9953 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9954 switch (ch) {
9955 case 'h':
9956 hflag = 1;
9957 break;
9958 case 'V':
9959 Vflag = 1;
9960 break;
9961 default:
9962 usage(hflag, 1);
9963 /* NOTREACHED */
9967 argc -= optind;
9968 argv += optind;
9969 optind = 1;
9970 optreset = 1;
9972 if (Vflag) {
9973 got_version_print_str();
9974 return 0;
9977 if (argc == 0) {
9978 if (hflag)
9979 usage(hflag, 0);
9980 /* Build an argument vector which runs a default command. */
9981 cmd = &tog_commands[0];
9982 argc = 1;
9983 cmd_argv = make_argv(argc, cmd->name);
9984 } else {
9985 size_t i;
9987 /* Did the user specify a command? */
9988 for (i = 0; i < nitems(tog_commands); i++) {
9989 if (strncmp(tog_commands[i].name, argv[0],
9990 strlen(argv[0])) == 0) {
9991 cmd = &tog_commands[i];
9992 break;
9997 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9998 if (diff_algo_str) {
9999 if (strcasecmp(diff_algo_str, "patience") == 0)
10000 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
10001 if (strcasecmp(diff_algo_str, "myers") == 0)
10002 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
10005 if (cmd == NULL) {
10006 if (argc != 1)
10007 usage(0, 1);
10008 /* No command specified; try log with a path */
10009 error = tog_log_with_path(argc, argv);
10010 } else {
10011 if (hflag)
10012 cmd->cmd_usage();
10013 else
10014 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
10017 if (using_mock_io) {
10018 io_err = tog_io_close();
10019 if (error == NULL)
10020 error = io_err;
10022 endwin();
10023 if (cmd_argv) {
10024 int i;
10025 for (i = 0; i < argc; i++)
10026 free(cmd_argv[i]);
10027 free(cmd_argv);
10030 if (error && error->code != GOT_ERR_CANCELLED &&
10031 error->code != GOT_ERR_EOF &&
10032 error->code != GOT_ERR_PRIVSEP_EXIT &&
10033 error->code != GOT_ERR_PRIVSEP_PIPE &&
10034 !(error->code == GOT_ERR_ERRNO && errno == EINTR)) {
10035 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10036 return 1;
10038 return 0;