Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include "got_compat.h"
19 #include <sys/queue.h>
20 #include <sys/stat.h>
21 #include <sys/ioctl.h>
23 #include <ctype.h>
24 #include <errno.h>
25 #if defined(__FreeBSD__) || defined(__APPLE__)
26 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
27 #endif
28 #include <curses.h>
29 #include <panel.h>
30 #include <locale.h>
31 #include <signal.h>
32 #include <stdlib.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <getopt.h>
36 #include <string.h>
37 #include <err.h>
38 #include <unistd.h>
39 #include <limits.h>
40 #include <wchar.h>
41 #include <time.h>
42 #include <pthread.h>
43 #include <libgen.h>
44 #include <regex.h>
46 #include "got_version.h"
47 #include "got_error.h"
48 #include "got_object.h"
49 #include "got_reference.h"
50 #include "got_repository.h"
51 #include "got_diff.h"
52 #include "got_opentemp.h"
53 #include "got_utf8.h"
54 #include "got_cancel.h"
55 #include "got_commit_graph.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_path.h"
59 #include "got_worktree.h"
60 #include "got_keyword.h"
62 #ifndef MIN
63 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
64 #endif
66 #ifndef MAX
67 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
68 #endif
70 #ifndef CTRL
71 #define CTRL(x) ((x) & 0x1f)
72 #endif
74 #ifndef nitems
75 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
76 #endif
78 struct tog_cmd {
79 const char *name;
80 const struct got_error *(*cmd_main)(int, char *[]);
81 void (*cmd_usage)(void);
82 };
84 __dead static void usage(int, int);
85 __dead static void usage_log(void);
86 __dead static void usage_diff(void);
87 __dead static void usage_blame(void);
88 __dead static void usage_tree(void);
89 __dead static void usage_ref(void);
91 static const struct got_error* cmd_log(int, char *[]);
92 static const struct got_error* cmd_diff(int, char *[]);
93 static const struct got_error* cmd_blame(int, char *[]);
94 static const struct got_error* cmd_tree(int, char *[]);
95 static const struct got_error* cmd_ref(int, char *[]);
97 static const struct tog_cmd tog_commands[] = {
98 { "log", cmd_log, usage_log },
99 { "diff", cmd_diff, usage_diff },
100 { "blame", cmd_blame, usage_blame },
101 { "tree", cmd_tree, usage_tree },
102 { "ref", cmd_ref, usage_ref },
103 };
105 enum tog_view_type {
106 TOG_VIEW_DIFF,
107 TOG_VIEW_LOG,
108 TOG_VIEW_BLAME,
109 TOG_VIEW_TREE,
110 TOG_VIEW_REF,
111 TOG_VIEW_HELP
112 };
114 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
115 enum tog_keymap_type {
116 TOG_KEYMAP_KEYS = -2,
117 TOG_KEYMAP_GLOBAL,
118 TOG_KEYMAP_DIFF,
119 TOG_KEYMAP_LOG,
120 TOG_KEYMAP_BLAME,
121 TOG_KEYMAP_TREE,
122 TOG_KEYMAP_REF,
123 TOG_KEYMAP_HELP
124 };
126 enum tog_view_mode {
127 TOG_VIEW_SPLIT_NONE,
128 TOG_VIEW_SPLIT_VERT,
129 TOG_VIEW_SPLIT_HRZN
130 };
132 #define HSPLIT_SCALE 0.3f /* default horizontal split scale */
134 #define TOG_EOF_STRING "(END)"
136 struct commit_queue_entry {
137 TAILQ_ENTRY(commit_queue_entry) entry;
138 struct got_object_id *id;
139 struct got_commit_object *commit;
140 int idx;
141 };
142 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
143 struct commit_queue {
144 int ncommits;
145 struct commit_queue_head head;
146 };
148 struct tog_color {
149 STAILQ_ENTRY(tog_color) entry;
150 regex_t regex;
151 short colorpair;
152 };
153 STAILQ_HEAD(tog_colors, tog_color);
155 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
156 static struct got_reflist_object_id_map *tog_refs_idmap;
157 static struct {
158 struct got_object_id *id;
159 int idx;
160 char marker;
161 } tog_base_commit;
162 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
164 static const struct got_error *
165 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
166 struct got_reference* re2)
168 const char *name1 = got_ref_get_name(re1);
169 const char *name2 = got_ref_get_name(re2);
170 int isbackup1, isbackup2;
172 /* Sort backup refs towards the bottom of the list. */
173 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
174 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
175 if (!isbackup1 && isbackup2) {
176 *cmp = -1;
177 return NULL;
178 } else if (isbackup1 && !isbackup2) {
179 *cmp = 1;
180 return NULL;
183 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
184 return NULL;
187 static const struct got_error *
188 tog_load_refs(struct got_repository *repo, int sort_by_date)
190 const struct got_error *err;
192 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
193 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
194 repo);
195 if (err)
196 return err;
198 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
199 repo);
202 static void
203 tog_free_refs(void)
205 if (tog_refs_idmap) {
206 got_reflist_object_id_map_free(tog_refs_idmap);
207 tog_refs_idmap = NULL;
209 got_ref_list_free(&tog_refs);
212 static const struct got_error *
213 add_color(struct tog_colors *colors, const char *pattern,
214 int idx, short color)
216 const struct got_error *err = NULL;
217 struct tog_color *tc;
218 int regerr = 0;
220 if (idx < 1 || idx > COLOR_PAIRS - 1)
221 return NULL;
223 init_pair(idx, color, -1);
225 tc = calloc(1, sizeof(*tc));
226 if (tc == NULL)
227 return got_error_from_errno("calloc");
228 regerr = regcomp(&tc->regex, pattern,
229 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
230 if (regerr) {
231 static char regerr_msg[512];
232 static char err_msg[512];
233 regerror(regerr, &tc->regex, regerr_msg,
234 sizeof(regerr_msg));
235 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
236 regerr_msg);
237 err = got_error_msg(GOT_ERR_REGEX, err_msg);
238 free(tc);
239 return err;
241 tc->colorpair = idx;
242 STAILQ_INSERT_HEAD(colors, tc, entry);
243 return NULL;
246 static void
247 free_colors(struct tog_colors *colors)
249 struct tog_color *tc;
251 while (!STAILQ_EMPTY(colors)) {
252 tc = STAILQ_FIRST(colors);
253 STAILQ_REMOVE_HEAD(colors, entry);
254 regfree(&tc->regex);
255 free(tc);
259 static struct tog_color *
260 get_color(struct tog_colors *colors, int colorpair)
262 struct tog_color *tc = NULL;
264 STAILQ_FOREACH(tc, colors, entry) {
265 if (tc->colorpair == colorpair)
266 return tc;
269 return NULL;
272 static int
273 default_color_value(const char *envvar)
275 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
276 return COLOR_MAGENTA;
277 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
278 return COLOR_CYAN;
279 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
280 return COLOR_YELLOW;
281 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
282 return COLOR_GREEN;
283 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
284 return COLOR_MAGENTA;
285 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
286 return COLOR_MAGENTA;
287 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
288 return COLOR_CYAN;
289 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
290 return COLOR_GREEN;
291 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
292 return COLOR_GREEN;
293 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
294 return COLOR_CYAN;
295 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
296 return COLOR_YELLOW;
297 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
298 return COLOR_GREEN;
299 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
300 return COLOR_MAGENTA;
301 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
302 return COLOR_YELLOW;
303 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
304 return COLOR_CYAN;
306 return -1;
309 static int
310 get_color_value(const char *envvar)
312 const char *val = getenv(envvar);
314 if (val == NULL)
315 return default_color_value(envvar);
317 if (strcasecmp(val, "black") == 0)
318 return COLOR_BLACK;
319 if (strcasecmp(val, "red") == 0)
320 return COLOR_RED;
321 if (strcasecmp(val, "green") == 0)
322 return COLOR_GREEN;
323 if (strcasecmp(val, "yellow") == 0)
324 return COLOR_YELLOW;
325 if (strcasecmp(val, "blue") == 0)
326 return COLOR_BLUE;
327 if (strcasecmp(val, "magenta") == 0)
328 return COLOR_MAGENTA;
329 if (strcasecmp(val, "cyan") == 0)
330 return COLOR_CYAN;
331 if (strcasecmp(val, "white") == 0)
332 return COLOR_WHITE;
333 if (strcasecmp(val, "default") == 0)
334 return -1;
336 return default_color_value(envvar);
339 struct tog_diff_view_state {
340 struct got_object_id *id1, *id2;
341 const char *label1, *label2;
342 FILE *f, *f1, *f2;
343 int fd1, fd2;
344 int lineno;
345 int first_displayed_line;
346 int last_displayed_line;
347 int eof;
348 int diff_context;
349 int ignore_whitespace;
350 int force_text_diff;
351 struct got_repository *repo;
352 struct got_diff_line *lines;
353 size_t nlines;
354 int matched_line;
355 int selected_line;
357 /* passed from log or blame view; may be NULL */
358 struct tog_view *parent_view;
359 };
361 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
362 static volatile sig_atomic_t tog_thread_error;
364 struct tog_log_thread_args {
365 pthread_cond_t need_commits;
366 pthread_cond_t commit_loaded;
367 int commits_needed;
368 int load_all;
369 struct got_commit_graph *graph;
370 struct commit_queue *real_commits;
371 const char *in_repo_path;
372 struct got_object_id *start_id;
373 struct got_repository *repo;
374 int *pack_fds;
375 int log_complete;
376 pthread_cond_t log_loaded;
377 sig_atomic_t *quit;
378 struct commit_queue_entry **first_displayed_entry;
379 struct commit_queue_entry **selected_entry;
380 int *searching;
381 int *search_next_done;
382 regex_t *regex;
383 int *limiting;
384 int limit_match;
385 regex_t *limit_regex;
386 struct commit_queue *limit_commits;
387 struct got_worktree *worktree;
388 int need_commit_marker;
389 };
391 struct tog_log_view_state {
392 struct commit_queue *commits;
393 struct commit_queue_entry *first_displayed_entry;
394 struct commit_queue_entry *last_displayed_entry;
395 struct commit_queue_entry *selected_entry;
396 struct commit_queue real_commits;
397 int selected;
398 char *in_repo_path;
399 char *head_ref_name;
400 int log_branches;
401 struct got_repository *repo;
402 struct got_object_id *start_id;
403 sig_atomic_t quit;
404 pthread_t thread;
405 struct tog_log_thread_args thread_args;
406 struct commit_queue_entry *matched_entry;
407 struct commit_queue_entry *search_entry;
408 struct tog_colors colors;
409 int use_committer;
410 int limit_view;
411 regex_t limit_regex;
412 struct commit_queue limit_commits;
413 };
415 #define TOG_COLOR_DIFF_MINUS 1
416 #define TOG_COLOR_DIFF_PLUS 2
417 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
418 #define TOG_COLOR_DIFF_META 4
419 #define TOG_COLOR_TREE_SUBMODULE 5
420 #define TOG_COLOR_TREE_SYMLINK 6
421 #define TOG_COLOR_TREE_DIRECTORY 7
422 #define TOG_COLOR_TREE_EXECUTABLE 8
423 #define TOG_COLOR_COMMIT 9
424 #define TOG_COLOR_AUTHOR 10
425 #define TOG_COLOR_DATE 11
426 #define TOG_COLOR_REFS_HEADS 12
427 #define TOG_COLOR_REFS_TAGS 13
428 #define TOG_COLOR_REFS_REMOTES 14
429 #define TOG_COLOR_REFS_BACKUP 15
431 struct tog_blame_cb_args {
432 struct tog_blame_line *lines; /* one per line */
433 int nlines;
435 struct tog_view *view;
436 struct got_object_id *commit_id;
437 int *quit;
438 };
440 struct tog_blame_thread_args {
441 const char *path;
442 struct got_repository *repo;
443 struct tog_blame_cb_args *cb_args;
444 int *complete;
445 got_cancel_cb cancel_cb;
446 void *cancel_arg;
447 pthread_cond_t blame_complete;
448 };
450 struct tog_blame {
451 FILE *f;
452 off_t filesize;
453 struct tog_blame_line *lines;
454 int nlines;
455 off_t *line_offsets;
456 pthread_t thread;
457 struct tog_blame_thread_args thread_args;
458 struct tog_blame_cb_args cb_args;
459 const char *path;
460 int *pack_fds;
461 };
463 struct tog_blame_view_state {
464 int first_displayed_line;
465 int last_displayed_line;
466 int selected_line;
467 int last_diffed_line;
468 int blame_complete;
469 int eof;
470 int done;
471 struct got_object_id_queue blamed_commits;
472 struct got_object_qid *blamed_commit;
473 char *path;
474 struct got_repository *repo;
475 struct got_object_id *commit_id;
476 struct got_object_id *id_to_log;
477 struct tog_blame blame;
478 int matched_line;
479 struct tog_colors colors;
480 };
482 struct tog_parent_tree {
483 TAILQ_ENTRY(tog_parent_tree) entry;
484 struct got_tree_object *tree;
485 struct got_tree_entry *first_displayed_entry;
486 struct got_tree_entry *selected_entry;
487 int selected;
488 };
490 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
492 struct tog_tree_view_state {
493 char *tree_label;
494 struct got_object_id *commit_id;/* commit which this tree belongs to */
495 struct got_tree_object *root; /* the commit's root tree entry */
496 struct got_tree_object *tree; /* currently displayed (sub-)tree */
497 struct got_tree_entry *first_displayed_entry;
498 struct got_tree_entry *last_displayed_entry;
499 struct got_tree_entry *selected_entry;
500 int ndisplayed, selected, show_ids;
501 struct tog_parent_trees parents; /* parent trees of current sub-tree */
502 char *head_ref_name;
503 struct got_repository *repo;
504 struct got_tree_entry *matched_entry;
505 struct tog_colors colors;
506 };
508 struct tog_reflist_entry {
509 TAILQ_ENTRY(tog_reflist_entry) entry;
510 struct got_reference *ref;
511 int idx;
512 };
514 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
516 struct tog_ref_view_state {
517 struct tog_reflist_head refs;
518 struct tog_reflist_entry *first_displayed_entry;
519 struct tog_reflist_entry *last_displayed_entry;
520 struct tog_reflist_entry *selected_entry;
521 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
522 struct got_repository *repo;
523 struct tog_reflist_entry *matched_entry;
524 struct tog_colors colors;
525 };
527 struct tog_help_view_state {
528 FILE *f;
529 off_t *line_offsets;
530 size_t nlines;
531 int lineno;
532 int first_displayed_line;
533 int last_displayed_line;
534 int eof;
535 int matched_line;
536 int selected_line;
537 int all;
538 enum tog_keymap_type type;
539 };
541 #define GENERATE_HELP \
542 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
543 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
544 KEY_("k C-p Up", "Move cursor or page up one line"), \
545 KEY_("j C-n Down", "Move cursor or page down one line"), \
546 KEY_("C-b b PgUp", "Scroll the view up one page"), \
547 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
548 KEY_("C-u u", "Scroll the view up one half page"), \
549 KEY_("C-d d", "Scroll the view down one half page"), \
550 KEY_("g", "Go to line N (default: first line)"), \
551 KEY_("Home =", "Go to the first line"), \
552 KEY_("G", "Go to line N (default: last line)"), \
553 KEY_("End *", "Go to the last line"), \
554 KEY_("l Right", "Scroll the view right"), \
555 KEY_("h Left", "Scroll the view left"), \
556 KEY_("$", "Scroll view to the rightmost position"), \
557 KEY_("0", "Scroll view to the leftmost position"), \
558 KEY_("-", "Decrease size of the focussed split"), \
559 KEY_("+", "Increase size of the focussed split"), \
560 KEY_("Tab", "Switch focus between views"), \
561 KEY_("F", "Toggle fullscreen mode"), \
562 KEY_("S", "Switch split-screen layout"), \
563 KEY_("/", "Open prompt to enter search term"), \
564 KEY_("n", "Find next line/token matching the current search term"), \
565 KEY_("N", "Find previous line/token matching the current search term"),\
566 KEY_("q", "Quit the focussed view; Quit help screen"), \
567 KEY_("Q", "Quit tog"), \
569 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
570 KEY_("< ,", "Move cursor up one commit"), \
571 KEY_("> .", "Move cursor down one commit"), \
572 KEY_("Enter", "Open diff view of the selected commit"), \
573 KEY_("B", "Reload the log view and toggle display of merged commits"), \
574 KEY_("R", "Open ref view of all repository references"), \
575 KEY_("T", "Display tree view of the repository from the selected" \
576 " commit"), \
577 KEY_("@", "Toggle between displaying author and committer name"), \
578 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
579 KEY_("C-g Backspace", "Cancel current search or log operation"), \
580 KEY_("C-l", "Reload the log view with new commits in the repository"), \
582 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
583 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
584 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
585 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
586 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
587 " data"), \
588 KEY_("(", "Go to the previous file in the diff"), \
589 KEY_(")", "Go to the next file in the diff"), \
590 KEY_("{", "Go to the previous hunk in the diff"), \
591 KEY_("}", "Go to the next hunk in the diff"), \
592 KEY_("[", "Decrease the number of context lines"), \
593 KEY_("]", "Increase the number of context lines"), \
594 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
596 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
597 KEY_("Enter", "Display diff view of the selected line's commit"), \
598 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
599 KEY_("L", "Open log view for the currently selected annotated line"), \
600 KEY_("C", "Reload view with the previously blamed commit"), \
601 KEY_("c", "Reload view with the version of the file found in the" \
602 " selected line's commit"), \
603 KEY_("p", "Reload view with the version of the file found in the" \
604 " selected line's parent commit"), \
606 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
607 KEY_("Enter", "Enter selected directory or open blame view of the" \
608 " selected file"), \
609 KEY_("L", "Open log view for the selected entry"), \
610 KEY_("R", "Open ref view of all repository references"), \
611 KEY_("i", "Show object IDs for all tree entries"), \
612 KEY_("Backspace", "Return to the parent directory"), \
614 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
615 KEY_("Enter", "Display log view of the selected reference"), \
616 KEY_("T", "Display tree view of the selected reference"), \
617 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
618 KEY_("m", "Toggle display of last modified date for each reference"), \
619 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
620 KEY_("C-l", "Reload view with all repository references")
622 struct tog_key_map {
623 const char *keys;
624 const char *info;
625 enum tog_keymap_type type;
626 };
628 /* curses io for tog regress */
629 struct tog_io {
630 FILE *cin;
631 FILE *cout;
632 FILE *f;
633 FILE *sdump;
634 char *input_str;
635 int wait_for_ui;
636 } tog_io;
637 static int using_mock_io;
639 #define TOG_KEY_SCRDUMP SHRT_MIN
641 /*
642 * We implement two types of views: parent views and child views.
644 * The 'Tab' key switches focus between a parent view and its child view.
645 * Child views are shown side-by-side to their parent view, provided
646 * there is enough screen estate.
648 * When a new view is opened from within a parent view, this new view
649 * becomes a child view of the parent view, replacing any existing child.
651 * When a new view is opened from within a child view, this new view
652 * becomes a parent view which will obscure the views below until the
653 * user quits the new parent view by typing 'q'.
655 * This list of views contains parent views only.
656 * Child views are only pointed to by their parent view.
657 */
658 TAILQ_HEAD(tog_view_list_head, tog_view);
660 struct tog_view {
661 TAILQ_ENTRY(tog_view) entry;
662 WINDOW *window;
663 PANEL *panel;
664 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
665 int resized_y, resized_x; /* begin_y/x based on user resizing */
666 int maxx, x; /* max column and current start column */
667 int lines, cols; /* copies of LINES and COLS */
668 int nscrolled, offset; /* lines scrolled and hsplit line offset */
669 int gline, hiline; /* navigate to and highlight this nG line */
670 int ch, count; /* current keymap and count prefix */
671 int resized; /* set when in a resize event */
672 int focussed; /* Only set on one parent or child view at a time. */
673 int dying;
674 struct tog_view *parent;
675 struct tog_view *child;
677 /*
678 * This flag is initially set on parent views when a new child view
679 * is created. It gets toggled when the 'Tab' key switches focus
680 * between parent and child.
681 * The flag indicates whether focus should be passed on to our child
682 * view if this parent view gets picked for focus after another parent
683 * view was closed. This prevents child views from losing focus in such
684 * situations.
685 */
686 int focus_child;
688 enum tog_view_mode mode;
689 /* type-specific state */
690 enum tog_view_type type;
691 union {
692 struct tog_diff_view_state diff;
693 struct tog_log_view_state log;
694 struct tog_blame_view_state blame;
695 struct tog_tree_view_state tree;
696 struct tog_ref_view_state ref;
697 struct tog_help_view_state help;
698 } state;
700 const struct got_error *(*show)(struct tog_view *);
701 const struct got_error *(*input)(struct tog_view **,
702 struct tog_view *, int);
703 const struct got_error *(*reset)(struct tog_view *);
704 const struct got_error *(*resize)(struct tog_view *, int);
705 const struct got_error *(*close)(struct tog_view *);
707 const struct got_error *(*search_start)(struct tog_view *);
708 const struct got_error *(*search_next)(struct tog_view *);
709 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
710 int **, int **, int **, int **);
711 int search_started;
712 int searching;
713 #define TOG_SEARCH_FORWARD 1
714 #define TOG_SEARCH_BACKWARD 2
715 int search_next_done;
716 #define TOG_SEARCH_HAVE_MORE 1
717 #define TOG_SEARCH_NO_MORE 2
718 #define TOG_SEARCH_HAVE_NONE 3
719 regex_t regex;
720 regmatch_t regmatch;
721 const char *action;
722 };
724 static const struct got_error *open_diff_view(struct tog_view *,
725 struct got_object_id *, struct got_object_id *,
726 const char *, const char *, int, int, int, struct tog_view *,
727 struct got_repository *);
728 static const struct got_error *show_diff_view(struct tog_view *);
729 static const struct got_error *input_diff_view(struct tog_view **,
730 struct tog_view *, int);
731 static const struct got_error *reset_diff_view(struct tog_view *);
732 static const struct got_error* close_diff_view(struct tog_view *);
733 static const struct got_error *search_start_diff_view(struct tog_view *);
734 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
735 size_t *, int **, int **, int **, int **);
736 static const struct got_error *search_next_view_match(struct tog_view *);
738 static const struct got_error *open_log_view(struct tog_view *,
739 struct got_object_id *, struct got_repository *,
740 const char *, const char *, int, struct got_worktree *);
741 static const struct got_error * show_log_view(struct tog_view *);
742 static const struct got_error *input_log_view(struct tog_view **,
743 struct tog_view *, int);
744 static const struct got_error *resize_log_view(struct tog_view *, int);
745 static const struct got_error *close_log_view(struct tog_view *);
746 static const struct got_error *search_start_log_view(struct tog_view *);
747 static const struct got_error *search_next_log_view(struct tog_view *);
749 static const struct got_error *open_blame_view(struct tog_view *, char *,
750 struct got_object_id *, struct got_repository *);
751 static const struct got_error *show_blame_view(struct tog_view *);
752 static const struct got_error *input_blame_view(struct tog_view **,
753 struct tog_view *, int);
754 static const struct got_error *reset_blame_view(struct tog_view *);
755 static const struct got_error *close_blame_view(struct tog_view *);
756 static const struct got_error *search_start_blame_view(struct tog_view *);
757 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
758 size_t *, int **, int **, int **, int **);
760 static const struct got_error *open_tree_view(struct tog_view *,
761 struct got_object_id *, const char *, struct got_repository *);
762 static const struct got_error *show_tree_view(struct tog_view *);
763 static const struct got_error *input_tree_view(struct tog_view **,
764 struct tog_view *, int);
765 static const struct got_error *close_tree_view(struct tog_view *);
766 static const struct got_error *search_start_tree_view(struct tog_view *);
767 static const struct got_error *search_next_tree_view(struct tog_view *);
769 static const struct got_error *open_ref_view(struct tog_view *,
770 struct got_repository *);
771 static const struct got_error *show_ref_view(struct tog_view *);
772 static const struct got_error *input_ref_view(struct tog_view **,
773 struct tog_view *, int);
774 static const struct got_error *close_ref_view(struct tog_view *);
775 static const struct got_error *search_start_ref_view(struct tog_view *);
776 static const struct got_error *search_next_ref_view(struct tog_view *);
778 static const struct got_error *open_help_view(struct tog_view *,
779 struct tog_view *);
780 static const struct got_error *show_help_view(struct tog_view *);
781 static const struct got_error *input_help_view(struct tog_view **,
782 struct tog_view *, int);
783 static const struct got_error *reset_help_view(struct tog_view *);
784 static const struct got_error* close_help_view(struct tog_view *);
785 static const struct got_error *search_start_help_view(struct tog_view *);
786 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
787 size_t *, int **, int **, int **, int **);
789 static volatile sig_atomic_t tog_sigwinch_received;
790 static volatile sig_atomic_t tog_sigpipe_received;
791 static volatile sig_atomic_t tog_sigcont_received;
792 static volatile sig_atomic_t tog_sigint_received;
793 static volatile sig_atomic_t tog_sigterm_received;
795 static void
796 tog_sigwinch(int signo)
798 tog_sigwinch_received = 1;
801 static void
802 tog_sigpipe(int signo)
804 tog_sigpipe_received = 1;
807 static void
808 tog_sigcont(int signo)
810 tog_sigcont_received = 1;
813 static void
814 tog_sigint(int signo)
816 tog_sigint_received = 1;
819 static void
820 tog_sigterm(int signo)
822 tog_sigterm_received = 1;
825 static int
826 tog_fatal_signal_received(void)
828 return (tog_sigpipe_received ||
829 tog_sigint_received || tog_sigterm_received);
832 static const struct got_error *
833 view_close(struct tog_view *view)
835 const struct got_error *err = NULL, *child_err = NULL;
837 if (view->child) {
838 child_err = view_close(view->child);
839 view->child = NULL;
841 if (view->close)
842 err = view->close(view);
843 if (view->panel)
844 del_panel(view->panel);
845 if (view->window)
846 delwin(view->window);
847 free(view);
848 return err ? err : child_err;
851 static struct tog_view *
852 view_open(int nlines, int ncols, int begin_y, int begin_x,
853 enum tog_view_type type)
855 struct tog_view *view = calloc(1, sizeof(*view));
857 if (view == NULL)
858 return NULL;
860 view->type = type;
861 view->lines = LINES;
862 view->cols = COLS;
863 view->nlines = nlines ? nlines : LINES - begin_y;
864 view->ncols = ncols ? ncols : COLS - begin_x;
865 view->begin_y = begin_y;
866 view->begin_x = begin_x;
867 view->window = newwin(nlines, ncols, begin_y, begin_x);
868 if (view->window == NULL) {
869 view_close(view);
870 return NULL;
872 view->panel = new_panel(view->window);
873 if (view->panel == NULL ||
874 set_panel_userptr(view->panel, view) != OK) {
875 view_close(view);
876 return NULL;
879 keypad(view->window, TRUE);
880 return view;
883 static int
884 view_split_begin_x(int begin_x)
886 if (begin_x > 0 || COLS < 120)
887 return 0;
888 return (COLS - MAX(COLS / 2, 80));
891 /* XXX Stub till we decide what to do. */
892 static int
893 view_split_begin_y(int lines)
895 return lines * HSPLIT_SCALE;
898 static const struct got_error *view_resize(struct tog_view *);
900 static const struct got_error *
901 view_splitscreen(struct tog_view *view)
903 const struct got_error *err = NULL;
905 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
906 if (view->resized_y && view->resized_y < view->lines)
907 view->begin_y = view->resized_y;
908 else
909 view->begin_y = view_split_begin_y(view->nlines);
910 view->begin_x = 0;
911 } else if (!view->resized) {
912 if (view->resized_x && view->resized_x < view->cols - 1 &&
913 view->cols > 119)
914 view->begin_x = view->resized_x;
915 else
916 view->begin_x = view_split_begin_x(0);
917 view->begin_y = 0;
919 view->nlines = LINES - view->begin_y;
920 view->ncols = COLS - view->begin_x;
921 view->lines = LINES;
922 view->cols = COLS;
923 err = view_resize(view);
924 if (err)
925 return err;
927 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
928 view->parent->nlines = view->begin_y;
930 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
931 return got_error_from_errno("mvwin");
933 return NULL;
936 static const struct got_error *
937 view_fullscreen(struct tog_view *view)
939 const struct got_error *err = NULL;
941 view->begin_x = 0;
942 view->begin_y = view->resized ? view->begin_y : 0;
943 view->nlines = view->resized ? view->nlines : LINES;
944 view->ncols = COLS;
945 view->lines = LINES;
946 view->cols = COLS;
947 err = view_resize(view);
948 if (err)
949 return err;
951 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
952 return got_error_from_errno("mvwin");
954 return NULL;
957 static int
958 view_is_parent_view(struct tog_view *view)
960 return view->parent == NULL;
963 static int
964 view_is_splitscreen(struct tog_view *view)
966 return view->begin_x > 0 || view->begin_y > 0;
969 static int
970 view_is_fullscreen(struct tog_view *view)
972 return view->nlines == LINES && view->ncols == COLS;
975 static int
976 view_is_hsplit_top(struct tog_view *view)
978 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
979 view_is_splitscreen(view->child);
982 static void
983 view_border(struct tog_view *view)
985 PANEL *panel;
986 const struct tog_view *view_above;
988 if (view->parent)
989 return view_border(view->parent);
991 panel = panel_above(view->panel);
992 if (panel == NULL)
993 return;
995 view_above = panel_userptr(panel);
996 if (view->mode == TOG_VIEW_SPLIT_HRZN)
997 mvwhline(view->window, view_above->begin_y - 1,
998 view->begin_x, ACS_HLINE, view->ncols);
999 else
1000 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
1001 ACS_VLINE, view->nlines);
1004 static const struct got_error *view_init_hsplit(struct tog_view *, int);
1005 static const struct got_error *request_log_commits(struct tog_view *);
1006 static const struct got_error *offset_selection_down(struct tog_view *);
1007 static void offset_selection_up(struct tog_view *);
1008 static void view_get_split(struct tog_view *, int *, int *);
1010 static const struct got_error *
1011 view_resize(struct tog_view *view)
1013 const struct got_error *err = NULL;
1014 int dif, nlines, ncols;
1016 dif = LINES - view->lines; /* line difference */
1018 if (view->lines > LINES)
1019 nlines = view->nlines - (view->lines - LINES);
1020 else
1021 nlines = view->nlines + (LINES - view->lines);
1022 if (view->cols > COLS)
1023 ncols = view->ncols - (view->cols - COLS);
1024 else
1025 ncols = view->ncols + (COLS - view->cols);
1027 if (view->child) {
1028 int hs = view->child->begin_y;
1030 if (!view_is_fullscreen(view))
1031 view->child->begin_x = view_split_begin_x(view->begin_x);
1032 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1033 view->child->begin_x == 0) {
1034 ncols = COLS;
1036 view_fullscreen(view->child);
1037 if (view->child->focussed)
1038 show_panel(view->child->panel);
1039 else
1040 show_panel(view->panel);
1041 } else {
1042 ncols = view->child->begin_x;
1044 view_splitscreen(view->child);
1045 show_panel(view->child->panel);
1048 * XXX This is ugly and needs to be moved into the above
1049 * logic but "works" for now and my attempts at moving it
1050 * break either 'tab' or 'F' key maps in horizontal splits.
1052 if (hs) {
1053 err = view_splitscreen(view->child);
1054 if (err)
1055 return err;
1056 if (dif < 0) { /* top split decreased */
1057 err = offset_selection_down(view);
1058 if (err)
1059 return err;
1061 view_border(view);
1062 update_panels();
1063 doupdate();
1064 show_panel(view->child->panel);
1065 nlines = view->nlines;
1067 } else if (view->parent == NULL)
1068 ncols = COLS;
1070 if (view->resize && dif > 0) {
1071 err = view->resize(view, dif);
1072 if (err)
1073 return err;
1076 if (wresize(view->window, nlines, ncols) == ERR)
1077 return got_error_from_errno("wresize");
1078 if (replace_panel(view->panel, view->window) == ERR)
1079 return got_error_from_errno("replace_panel");
1080 wclear(view->window);
1082 view->nlines = nlines;
1083 view->ncols = ncols;
1084 view->lines = LINES;
1085 view->cols = COLS;
1087 return NULL;
1090 static const struct got_error *
1091 resize_log_view(struct tog_view *view, int increase)
1093 struct tog_log_view_state *s = &view->state.log;
1094 const struct got_error *err = NULL;
1095 int n = 0;
1097 if (s->selected_entry)
1098 n = s->selected_entry->idx + view->lines - s->selected;
1101 * Request commits to account for the increased
1102 * height so we have enough to populate the view.
1104 if (s->commits->ncommits < n) {
1105 view->nscrolled = n - s->commits->ncommits + increase + 1;
1106 err = request_log_commits(view);
1109 return err;
1112 static void
1113 view_adjust_offset(struct tog_view *view, int n)
1115 if (n == 0)
1116 return;
1118 if (view->parent && view->parent->offset) {
1119 if (view->parent->offset + n >= 0)
1120 view->parent->offset += n;
1121 else
1122 view->parent->offset = 0;
1123 } else if (view->offset) {
1124 if (view->offset - n >= 0)
1125 view->offset -= n;
1126 else
1127 view->offset = 0;
1131 static const struct got_error *
1132 view_resize_split(struct tog_view *view, int resize)
1134 const struct got_error *err = NULL;
1135 struct tog_view *v = NULL;
1137 if (view->parent)
1138 v = view->parent;
1139 else
1140 v = view;
1142 if (!v->child || !view_is_splitscreen(v->child))
1143 return NULL;
1145 v->resized = v->child->resized = resize; /* lock for resize event */
1147 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1148 if (v->child->resized_y)
1149 v->child->begin_y = v->child->resized_y;
1150 if (view->parent)
1151 v->child->begin_y -= resize;
1152 else
1153 v->child->begin_y += resize;
1154 if (v->child->begin_y < 3) {
1155 view->count = 0;
1156 v->child->begin_y = 3;
1157 } else if (v->child->begin_y > LINES - 1) {
1158 view->count = 0;
1159 v->child->begin_y = LINES - 1;
1161 v->ncols = COLS;
1162 v->child->ncols = COLS;
1163 view_adjust_offset(view, resize);
1164 err = view_init_hsplit(v, v->child->begin_y);
1165 if (err)
1166 return err;
1167 v->child->resized_y = v->child->begin_y;
1168 } else {
1169 if (v->child->resized_x)
1170 v->child->begin_x = v->child->resized_x;
1171 if (view->parent)
1172 v->child->begin_x -= resize;
1173 else
1174 v->child->begin_x += resize;
1175 if (v->child->begin_x < 11) {
1176 view->count = 0;
1177 v->child->begin_x = 11;
1178 } else if (v->child->begin_x > COLS - 1) {
1179 view->count = 0;
1180 v->child->begin_x = COLS - 1;
1182 v->child->resized_x = v->child->begin_x;
1185 v->child->mode = v->mode;
1186 v->child->nlines = v->lines - v->child->begin_y;
1187 v->child->ncols = v->cols - v->child->begin_x;
1188 v->focus_child = 1;
1190 err = view_fullscreen(v);
1191 if (err)
1192 return err;
1193 err = view_splitscreen(v->child);
1194 if (err)
1195 return err;
1197 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1198 err = offset_selection_down(v->child);
1199 if (err)
1200 return err;
1203 if (v->resize)
1204 err = v->resize(v, 0);
1205 else if (v->child->resize)
1206 err = v->child->resize(v->child, 0);
1208 v->resized = v->child->resized = 0;
1210 return err;
1213 static void
1214 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1216 struct tog_view *v = src->child ? src->child : src;
1218 dst->resized_x = v->resized_x;
1219 dst->resized_y = v->resized_y;
1222 static const struct got_error *
1223 view_close_child(struct tog_view *view)
1225 const struct got_error *err = NULL;
1227 if (view->child == NULL)
1228 return NULL;
1230 err = view_close(view->child);
1231 view->child = NULL;
1232 return err;
1235 static const struct got_error *
1236 view_set_child(struct tog_view *view, struct tog_view *child)
1238 const struct got_error *err = NULL;
1240 view->child = child;
1241 child->parent = view;
1243 err = view_resize(view);
1244 if (err)
1245 return err;
1247 if (view->child->resized_x || view->child->resized_y)
1248 err = view_resize_split(view, 0);
1250 return err;
1253 static const struct got_error *view_dispatch_request(struct tog_view **,
1254 struct tog_view *, enum tog_view_type, int, int);
1256 static const struct got_error *
1257 view_request_new(struct tog_view **requested, struct tog_view *view,
1258 enum tog_view_type request)
1260 struct tog_view *new_view = NULL;
1261 const struct got_error *err;
1262 int y = 0, x = 0;
1264 *requested = NULL;
1266 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1267 view_get_split(view, &y, &x);
1269 err = view_dispatch_request(&new_view, view, request, y, x);
1270 if (err)
1271 return err;
1273 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1274 request != TOG_VIEW_HELP) {
1275 err = view_init_hsplit(view, y);
1276 if (err)
1277 return err;
1280 view->focussed = 0;
1281 new_view->focussed = 1;
1282 new_view->mode = view->mode;
1283 new_view->nlines = request == TOG_VIEW_HELP ?
1284 view->lines : view->lines - y;
1286 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1287 view_transfer_size(new_view, view);
1288 err = view_close_child(view);
1289 if (err)
1290 return err;
1291 err = view_set_child(view, new_view);
1292 if (err)
1293 return err;
1294 view->focus_child = 1;
1295 } else
1296 *requested = new_view;
1298 return NULL;
1301 static void
1302 tog_resizeterm(void)
1304 int cols, lines;
1305 struct winsize size;
1307 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1308 cols = 80; /* Default */
1309 lines = 24;
1310 } else {
1311 cols = size.ws_col;
1312 lines = size.ws_row;
1314 resize_term(lines, cols);
1317 static const struct got_error *
1318 view_search_start(struct tog_view *view, int fast_refresh)
1320 const struct got_error *err = NULL;
1321 struct tog_view *v = view;
1322 char pattern[1024];
1323 int ret;
1325 if (view->search_started) {
1326 regfree(&view->regex);
1327 view->searching = 0;
1328 memset(&view->regmatch, 0, sizeof(view->regmatch));
1330 view->search_started = 0;
1332 if (view->nlines < 1)
1333 return NULL;
1335 if (view_is_hsplit_top(view))
1336 v = view->child;
1337 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1338 v = view->parent;
1340 if (tog_io.input_str != NULL) {
1341 if (strlcpy(pattern, tog_io.input_str, sizeof(pattern)) >=
1342 sizeof(pattern))
1343 return got_error(GOT_ERR_NO_SPACE);
1344 } else {
1345 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1346 wclrtoeol(v->window);
1347 nodelay(v->window, FALSE); /* block for search term input */
1348 nocbreak();
1349 echo();
1350 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1351 wrefresh(v->window);
1352 cbreak();
1353 noecho();
1354 nodelay(v->window, TRUE);
1355 if (!fast_refresh && !using_mock_io)
1356 halfdelay(10);
1357 if (ret == ERR)
1358 return NULL;
1361 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1362 err = view->search_start(view);
1363 if (err) {
1364 regfree(&view->regex);
1365 return err;
1367 view->search_started = 1;
1368 view->searching = TOG_SEARCH_FORWARD;
1369 view->search_next_done = 0;
1370 view->search_next(view);
1373 return NULL;
1376 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1377 static const struct got_error *
1378 switch_split(struct tog_view *view)
1380 const struct got_error *err = NULL;
1381 struct tog_view *v = NULL;
1383 if (view->parent)
1384 v = view->parent;
1385 else
1386 v = view;
1388 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1389 v->mode = TOG_VIEW_SPLIT_VERT;
1390 else
1391 v->mode = TOG_VIEW_SPLIT_HRZN;
1393 if (!v->child)
1394 return NULL;
1395 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1396 v->mode = TOG_VIEW_SPLIT_NONE;
1398 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1399 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1400 v->child->begin_y = v->child->resized_y;
1401 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1402 v->child->begin_x = v->child->resized_x;
1405 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1406 v->ncols = COLS;
1407 v->child->ncols = COLS;
1408 v->child->nscrolled = LINES - v->child->nlines;
1410 err = view_init_hsplit(v, v->child->begin_y);
1411 if (err)
1412 return err;
1414 v->child->mode = v->mode;
1415 v->child->nlines = v->lines - v->child->begin_y;
1416 v->focus_child = 1;
1418 err = view_fullscreen(v);
1419 if (err)
1420 return err;
1421 err = view_splitscreen(v->child);
1422 if (err)
1423 return err;
1425 if (v->mode == TOG_VIEW_SPLIT_NONE)
1426 v->mode = TOG_VIEW_SPLIT_VERT;
1427 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1428 err = offset_selection_down(v);
1429 if (err)
1430 return err;
1431 err = offset_selection_down(v->child);
1432 if (err)
1433 return err;
1434 } else {
1435 offset_selection_up(v);
1436 offset_selection_up(v->child);
1438 if (v->resize)
1439 err = v->resize(v, 0);
1440 else if (v->child->resize)
1441 err = v->child->resize(v->child, 0);
1443 return err;
1447 * Strip trailing whitespace from str starting at byte *n;
1448 * if *n < 0, use strlen(str). Return new str length in *n.
1450 static void
1451 strip_trailing_ws(char *str, int *n)
1453 size_t x = *n;
1455 if (str == NULL || *str == '\0')
1456 return;
1458 if (x < 0)
1459 x = strlen(str);
1461 while (x-- > 0 && isspace((unsigned char)str[x]))
1462 str[x] = '\0';
1464 *n = x + 1;
1468 * Extract visible substring of line y from the curses screen
1469 * and strip trailing whitespace. If vline is set, overwrite
1470 * line[vline] with '|' because the ACS_VLINE character is
1471 * written out as 'x'. Write the line to file f.
1473 static const struct got_error *
1474 view_write_line(FILE *f, int y, int vline)
1476 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1477 int r, w;
1479 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1480 if (r == ERR)
1481 return got_error_fmt(GOT_ERR_RANGE,
1482 "failed to extract line %d", y);
1485 * In some views, lines are padded with blanks to COLS width.
1486 * Strip them so we can diff without the -b flag when testing.
1488 strip_trailing_ws(line, &r);
1490 if (vline > 0)
1491 line[vline] = '|';
1493 w = fprintf(f, "%s\n", line);
1494 if (w != r + 1) /* \n */
1495 return got_ferror(f, GOT_ERR_IO);
1497 return NULL;
1501 * Capture the visible curses screen by writing each line to the
1502 * file at the path set via the TOG_SCR_DUMP environment variable.
1504 static const struct got_error *
1505 screendump(struct tog_view *view)
1507 const struct got_error *err;
1508 int i;
1510 err = got_opentemp_truncate(tog_io.sdump);
1511 if (err)
1512 return err;
1514 if ((view->child && view->child->begin_x) ||
1515 (view->parent && view->begin_x)) {
1516 int ncols = view->child ? view->ncols : view->parent->ncols;
1518 /* vertical splitscreen */
1519 for (i = 0; i < view->nlines; ++i) {
1520 err = view_write_line(tog_io.sdump, i, ncols - 1);
1521 if (err)
1522 goto done;
1524 } else {
1525 int hline = 0;
1527 /* fullscreen or horizontal splitscreen */
1528 if ((view->child && view->child->begin_y) ||
1529 (view->parent && view->begin_y)) /* hsplit */
1530 hline = view->child ?
1531 view->child->begin_y : view->begin_y;
1533 for (i = 0; i < view->lines; i++) {
1534 if (hline && i == hline - 1) {
1535 int c;
1537 /* ACS_HLINE writes out as 'q', overwrite it */
1538 for (c = 0; c < view->cols; ++c)
1539 fputc('-', tog_io.sdump);
1540 fputc('\n', tog_io.sdump);
1541 continue;
1544 err = view_write_line(tog_io.sdump, i, 0);
1545 if (err)
1546 goto done;
1550 done:
1551 return err;
1555 * Compute view->count from numeric input. Assign total to view->count and
1556 * return first non-numeric key entered.
1558 static int
1559 get_compound_key(struct tog_view *view, int c)
1561 struct tog_view *v = view;
1562 int x, n = 0;
1564 if (view_is_hsplit_top(view))
1565 v = view->child;
1566 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1567 v = view->parent;
1569 view->count = 0;
1570 cbreak(); /* block for input */
1571 nodelay(view->window, FALSE);
1572 wmove(v->window, v->nlines - 1, 0);
1573 wclrtoeol(v->window);
1574 waddch(v->window, ':');
1576 do {
1577 x = getcurx(v->window);
1578 if (x != ERR && x < view->ncols) {
1579 waddch(v->window, c);
1580 wrefresh(v->window);
1584 * Don't overflow. Max valid request should be the greatest
1585 * between the longest and total lines; cap at 10 million.
1587 if (n >= 9999999)
1588 n = 9999999;
1589 else
1590 n = n * 10 + (c - '0');
1591 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1593 if (c == 'G' || c == 'g') { /* nG key map */
1594 view->gline = view->hiline = n;
1595 n = 0;
1596 c = 0;
1599 /* Massage excessive or inapplicable values at the input handler. */
1600 view->count = n;
1602 return c;
1605 static void
1606 action_report(struct tog_view *view)
1608 struct tog_view *v = view;
1610 if (view_is_hsplit_top(view))
1611 v = view->child;
1612 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1613 v = view->parent;
1615 wmove(v->window, v->nlines - 1, 0);
1616 wclrtoeol(v->window);
1617 wprintw(v->window, ":%s", view->action);
1618 wrefresh(v->window);
1621 * Clear action status report. Only clear in blame view
1622 * once annotating is complete, otherwise it's too fast.
1624 if (view->type == TOG_VIEW_BLAME) {
1625 if (view->state.blame.blame_complete)
1626 view->action = NULL;
1627 } else
1628 view->action = NULL;
1632 * Read the next line from the test script and assign
1633 * key instruction to *ch. If at EOF, set the *done flag.
1635 static const struct got_error *
1636 tog_read_script_key(FILE *script, struct tog_view *view, int *ch, int *done)
1638 const struct got_error *err = NULL;
1639 char *line = NULL;
1640 size_t linesz = 0;
1641 ssize_t n;
1644 if (view->count && --view->count) {
1645 *ch = view->ch;
1646 return NULL;
1647 } else
1648 *ch = -1;
1650 if ((n = getline(&line, &linesz, script)) == -1) {
1651 if (feof(script)) {
1652 *done = 1;
1653 goto done;
1654 } else {
1655 err = got_ferror(script, GOT_ERR_IO);
1656 goto done;
1660 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1661 tog_io.wait_for_ui = 1;
1662 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1663 *ch = KEY_ENTER;
1664 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1665 *ch = KEY_RIGHT;
1666 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1667 *ch = KEY_LEFT;
1668 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1669 *ch = KEY_DOWN;
1670 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1671 *ch = KEY_UP;
1672 else if (strncasecmp(line, "TAB", 3) == 0)
1673 *ch = '\t';
1674 else if (strncasecmp(line, "SCREENDUMP", 10) == 0)
1675 *ch = TOG_KEY_SCRDUMP;
1676 else if (isdigit((unsigned char)*line)) {
1677 char *t = line;
1679 while (isdigit((unsigned char)*t))
1680 ++t;
1681 view->ch = *ch = *t;
1682 *t = '\0';
1683 /* ignore error, view->count is 0 if instruction is invalid */
1684 view->count = strtonum(line, 0, INT_MAX, NULL);
1685 } else {
1686 *ch = *line;
1687 if (n > 2 && (*ch == '/' || *ch == '&')) {
1688 /* skip leading keymap and trim trailing newline */
1689 tog_io.input_str = strndup(line + 1, n - 2);
1690 if (tog_io.input_str == NULL) {
1691 err = got_error_from_errno("strndup");
1692 goto done;
1697 done:
1698 free(line);
1699 return err;
1702 static const struct got_error *
1703 view_input(struct tog_view **new, int *done, struct tog_view *view,
1704 struct tog_view_list_head *views, int fast_refresh)
1706 const struct got_error *err = NULL;
1707 struct tog_view *v;
1708 int ch, errcode;
1710 *new = NULL;
1712 if (view->action)
1713 action_report(view);
1715 /* Clear "no matches" indicator. */
1716 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1717 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1718 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1719 view->count = 0;
1722 if (view->searching && !view->search_next_done) {
1723 view->search_next(view);
1724 return NULL;
1727 /* Allow threads to make progress while we are waiting for input. */
1728 errcode = pthread_mutex_unlock(&tog_mutex);
1729 if (errcode)
1730 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1732 if (using_mock_io) {
1733 err = tog_read_script_key(tog_io.f, view, &ch, done);
1734 if (err) {
1735 errcode = pthread_mutex_lock(&tog_mutex);
1736 return err;
1738 } else if (view->count && --view->count) {
1739 cbreak();
1740 nodelay(view->window, TRUE);
1741 ch = wgetch(view->window);
1742 /* let C-g or backspace abort unfinished count */
1743 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1744 view->count = 0;
1745 else
1746 ch = view->ch;
1747 } else {
1748 ch = wgetch(view->window);
1749 if (ch >= '1' && ch <= '9')
1750 view->ch = ch = get_compound_key(view, ch);
1752 if (view->hiline && ch != ERR && ch != 0)
1753 view->hiline = 0; /* key pressed, clear line highlight */
1754 nodelay(view->window, TRUE);
1755 errcode = pthread_mutex_lock(&tog_mutex);
1756 if (errcode)
1757 return got_error_set_errno(errcode, "pthread_mutex_lock");
1759 if (tog_sigwinch_received || tog_sigcont_received) {
1760 tog_resizeterm();
1761 tog_sigwinch_received = 0;
1762 tog_sigcont_received = 0;
1763 TAILQ_FOREACH(v, views, entry) {
1764 err = view_resize(v);
1765 if (err)
1766 return err;
1767 err = v->input(new, v, KEY_RESIZE);
1768 if (err)
1769 return err;
1770 if (v->child) {
1771 err = view_resize(v->child);
1772 if (err)
1773 return err;
1774 err = v->child->input(new, v->child,
1775 KEY_RESIZE);
1776 if (err)
1777 return err;
1778 if (v->child->resized_x || v->child->resized_y) {
1779 err = view_resize_split(v, 0);
1780 if (err)
1781 return err;
1787 switch (ch) {
1788 case '?':
1789 case 'H':
1790 case KEY_F(1):
1791 if (view->type == TOG_VIEW_HELP)
1792 err = view->reset(view);
1793 else
1794 err = view_request_new(new, view, TOG_VIEW_HELP);
1795 break;
1796 case '\t':
1797 view->count = 0;
1798 if (view->child) {
1799 view->focussed = 0;
1800 view->child->focussed = 1;
1801 view->focus_child = 1;
1802 } else if (view->parent) {
1803 view->focussed = 0;
1804 view->parent->focussed = 1;
1805 view->parent->focus_child = 0;
1806 if (!view_is_splitscreen(view)) {
1807 if (view->parent->resize) {
1808 err = view->parent->resize(view->parent,
1809 0);
1810 if (err)
1811 return err;
1813 offset_selection_up(view->parent);
1814 err = view_fullscreen(view->parent);
1815 if (err)
1816 return err;
1819 break;
1820 case 'q':
1821 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1822 if (view->parent->resize) {
1823 /* might need more commits to fill fullscreen */
1824 err = view->parent->resize(view->parent, 0);
1825 if (err)
1826 break;
1828 offset_selection_up(view->parent);
1830 err = view->input(new, view, ch);
1831 view->dying = 1;
1832 break;
1833 case 'Q':
1834 *done = 1;
1835 break;
1836 case 'F':
1837 view->count = 0;
1838 if (view_is_parent_view(view)) {
1839 if (view->child == NULL)
1840 break;
1841 if (view_is_splitscreen(view->child)) {
1842 view->focussed = 0;
1843 view->child->focussed = 1;
1844 err = view_fullscreen(view->child);
1845 } else {
1846 err = view_splitscreen(view->child);
1847 if (!err)
1848 err = view_resize_split(view, 0);
1850 if (err)
1851 break;
1852 err = view->child->input(new, view->child,
1853 KEY_RESIZE);
1854 } else {
1855 if (view_is_splitscreen(view)) {
1856 view->parent->focussed = 0;
1857 view->focussed = 1;
1858 err = view_fullscreen(view);
1859 } else {
1860 err = view_splitscreen(view);
1861 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1862 err = view_resize(view->parent);
1863 if (!err)
1864 err = view_resize_split(view, 0);
1866 if (err)
1867 break;
1868 err = view->input(new, view, KEY_RESIZE);
1870 if (err)
1871 break;
1872 if (view->resize) {
1873 err = view->resize(view, 0);
1874 if (err)
1875 break;
1877 if (view->parent) {
1878 if (view->parent->resize) {
1879 err = view->parent->resize(view->parent, 0);
1880 if (err != NULL)
1881 break;
1883 err = offset_selection_down(view->parent);
1884 if (err != NULL)
1885 break;
1887 err = offset_selection_down(view);
1888 break;
1889 case 'S':
1890 view->count = 0;
1891 err = switch_split(view);
1892 break;
1893 case '-':
1894 err = view_resize_split(view, -1);
1895 break;
1896 case '+':
1897 err = view_resize_split(view, 1);
1898 break;
1899 case KEY_RESIZE:
1900 break;
1901 case '/':
1902 view->count = 0;
1903 if (view->search_start)
1904 view_search_start(view, fast_refresh);
1905 else
1906 err = view->input(new, view, ch);
1907 break;
1908 case 'N':
1909 case 'n':
1910 if (view->search_started && view->search_next) {
1911 view->searching = (ch == 'n' ?
1912 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1913 view->search_next_done = 0;
1914 view->search_next(view);
1915 } else
1916 err = view->input(new, view, ch);
1917 break;
1918 case 'A':
1919 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1920 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1921 view->action = "Patience diff algorithm";
1922 } else {
1923 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1924 view->action = "Myers diff algorithm";
1926 TAILQ_FOREACH(v, views, entry) {
1927 if (v->reset) {
1928 err = v->reset(v);
1929 if (err)
1930 return err;
1932 if (v->child && v->child->reset) {
1933 err = v->child->reset(v->child);
1934 if (err)
1935 return err;
1938 break;
1939 case TOG_KEY_SCRDUMP:
1940 err = screendump(view);
1941 break;
1942 default:
1943 err = view->input(new, view, ch);
1944 break;
1947 return err;
1950 static int
1951 view_needs_focus_indication(struct tog_view *view)
1953 if (view_is_parent_view(view)) {
1954 if (view->child == NULL || view->child->focussed)
1955 return 0;
1956 if (!view_is_splitscreen(view->child))
1957 return 0;
1958 } else if (!view_is_splitscreen(view))
1959 return 0;
1961 return view->focussed;
1964 static const struct got_error *
1965 tog_io_close(void)
1967 const struct got_error *err = NULL;
1969 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1970 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1971 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1972 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1973 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1974 err = got_ferror(tog_io.f, GOT_ERR_IO);
1975 if (tog_io.sdump && fclose(tog_io.sdump) == EOF && err == NULL)
1976 err = got_ferror(tog_io.sdump, GOT_ERR_IO);
1977 if (tog_io.input_str != NULL)
1978 free(tog_io.input_str);
1980 return err;
1983 static const struct got_error *
1984 view_loop(struct tog_view *view)
1986 const struct got_error *err = NULL;
1987 struct tog_view_list_head views;
1988 struct tog_view *new_view;
1989 char *mode;
1990 int fast_refresh = 10;
1991 int done = 0, errcode;
1993 mode = getenv("TOG_VIEW_SPLIT_MODE");
1994 if (!mode || !(*mode == 'h' || *mode == 'H'))
1995 view->mode = TOG_VIEW_SPLIT_VERT;
1996 else
1997 view->mode = TOG_VIEW_SPLIT_HRZN;
1999 errcode = pthread_mutex_lock(&tog_mutex);
2000 if (errcode)
2001 return got_error_set_errno(errcode, "pthread_mutex_lock");
2003 TAILQ_INIT(&views);
2004 TAILQ_INSERT_HEAD(&views, view, entry);
2006 view->focussed = 1;
2007 err = view->show(view);
2008 if (err)
2009 return err;
2010 update_panels();
2011 doupdate();
2012 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
2013 !tog_fatal_signal_received()) {
2014 /* Refresh fast during initialization, then become slower. */
2015 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
2016 halfdelay(10); /* switch to once per second */
2018 err = view_input(&new_view, &done, view, &views, fast_refresh);
2019 if (err)
2020 break;
2022 if (view->dying && view == TAILQ_FIRST(&views) &&
2023 TAILQ_NEXT(view, entry) == NULL)
2024 done = 1;
2025 if (done) {
2026 struct tog_view *v;
2029 * When we quit, scroll the screen up a single line
2030 * so we don't lose any information.
2032 TAILQ_FOREACH(v, &views, entry) {
2033 wmove(v->window, 0, 0);
2034 wdeleteln(v->window);
2035 wnoutrefresh(v->window);
2036 if (v->child && !view_is_fullscreen(v)) {
2037 wmove(v->child->window, 0, 0);
2038 wdeleteln(v->child->window);
2039 wnoutrefresh(v->child->window);
2042 doupdate();
2045 if (view->dying) {
2046 struct tog_view *v, *prev = NULL;
2048 if (view_is_parent_view(view))
2049 prev = TAILQ_PREV(view, tog_view_list_head,
2050 entry);
2051 else if (view->parent)
2052 prev = view->parent;
2054 if (view->parent) {
2055 view->parent->child = NULL;
2056 view->parent->focus_child = 0;
2057 /* Restore fullscreen line height. */
2058 view->parent->nlines = view->parent->lines;
2059 err = view_resize(view->parent);
2060 if (err)
2061 break;
2062 /* Make resized splits persist. */
2063 view_transfer_size(view->parent, view);
2064 } else
2065 TAILQ_REMOVE(&views, view, entry);
2067 err = view_close(view);
2068 if (err)
2069 goto done;
2071 view = NULL;
2072 TAILQ_FOREACH(v, &views, entry) {
2073 if (v->focussed)
2074 break;
2076 if (view == NULL && new_view == NULL) {
2077 /* No view has focus. Try to pick one. */
2078 if (prev)
2079 view = prev;
2080 else if (!TAILQ_EMPTY(&views)) {
2081 view = TAILQ_LAST(&views,
2082 tog_view_list_head);
2084 if (view) {
2085 if (view->focus_child) {
2086 view->child->focussed = 1;
2087 view = view->child;
2088 } else
2089 view->focussed = 1;
2093 if (new_view) {
2094 struct tog_view *v, *t;
2095 /* Only allow one parent view per type. */
2096 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2097 if (v->type != new_view->type)
2098 continue;
2099 TAILQ_REMOVE(&views, v, entry);
2100 err = view_close(v);
2101 if (err)
2102 goto done;
2103 break;
2105 TAILQ_INSERT_TAIL(&views, new_view, entry);
2106 view = new_view;
2108 if (view && !done) {
2109 if (view_is_parent_view(view)) {
2110 if (view->child && view->child->focussed)
2111 view = view->child;
2112 } else {
2113 if (view->parent && view->parent->focussed)
2114 view = view->parent;
2116 show_panel(view->panel);
2117 if (view->child && view_is_splitscreen(view->child))
2118 show_panel(view->child->panel);
2119 if (view->parent && view_is_splitscreen(view)) {
2120 err = view->parent->show(view->parent);
2121 if (err)
2122 goto done;
2124 err = view->show(view);
2125 if (err)
2126 goto done;
2127 if (view->child) {
2128 err = view->child->show(view->child);
2129 if (err)
2130 goto done;
2132 update_panels();
2133 doupdate();
2136 done:
2137 while (!TAILQ_EMPTY(&views)) {
2138 const struct got_error *close_err;
2139 view = TAILQ_FIRST(&views);
2140 TAILQ_REMOVE(&views, view, entry);
2141 close_err = view_close(view);
2142 if (close_err && err == NULL)
2143 err = close_err;
2146 errcode = pthread_mutex_unlock(&tog_mutex);
2147 if (errcode && err == NULL)
2148 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2150 return err;
2153 __dead static void
2154 usage_log(void)
2156 endwin();
2157 fprintf(stderr,
2158 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2159 getprogname());
2160 exit(1);
2163 /* Create newly allocated wide-character string equivalent to a byte string. */
2164 static const struct got_error *
2165 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2167 char *vis = NULL;
2168 const struct got_error *err = NULL;
2170 *ws = NULL;
2171 *wlen = mbstowcs(NULL, s, 0);
2172 if (*wlen == (size_t)-1) {
2173 int vislen;
2174 if (errno != EILSEQ)
2175 return got_error_from_errno("mbstowcs");
2177 /* byte string invalid in current encoding; try to "fix" it */
2178 err = got_mbsavis(&vis, &vislen, s);
2179 if (err)
2180 return err;
2181 *wlen = mbstowcs(NULL, vis, 0);
2182 if (*wlen == (size_t)-1) {
2183 err = got_error_from_errno("mbstowcs"); /* give up */
2184 goto done;
2188 *ws = calloc(*wlen + 1, sizeof(**ws));
2189 if (*ws == NULL) {
2190 err = got_error_from_errno("calloc");
2191 goto done;
2194 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2195 err = got_error_from_errno("mbstowcs");
2196 done:
2197 free(vis);
2198 if (err) {
2199 free(*ws);
2200 *ws = NULL;
2201 *wlen = 0;
2203 return err;
2206 static const struct got_error *
2207 expand_tab(char **ptr, const char *src)
2209 char *dst;
2210 size_t len, n, idx = 0, sz = 0;
2212 *ptr = NULL;
2213 n = len = strlen(src);
2214 dst = malloc(n + 1);
2215 if (dst == NULL)
2216 return got_error_from_errno("malloc");
2218 while (idx < len && src[idx]) {
2219 const char c = src[idx];
2221 if (c == '\t') {
2222 size_t nb = TABSIZE - sz % TABSIZE;
2223 char *p;
2225 p = realloc(dst, n + nb);
2226 if (p == NULL) {
2227 free(dst);
2228 return got_error_from_errno("realloc");
2231 dst = p;
2232 n += nb;
2233 memset(dst + sz, ' ', nb);
2234 sz += nb;
2235 } else
2236 dst[sz++] = src[idx];
2237 ++idx;
2240 dst[sz] = '\0';
2241 *ptr = dst;
2242 return NULL;
2246 * Advance at most n columns from wline starting at offset off.
2247 * Return the index to the first character after the span operation.
2248 * Return the combined column width of all spanned wide characters in
2249 * *rcol.
2251 static int
2252 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2254 int width, i, cols = 0;
2256 if (n == 0) {
2257 *rcol = cols;
2258 return off;
2261 for (i = off; wline[i] != L'\0'; ++i) {
2262 if (wline[i] == L'\t')
2263 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2264 else
2265 width = wcwidth(wline[i]);
2267 if (width == -1) {
2268 width = 1;
2269 wline[i] = L'.';
2272 if (cols + width > n)
2273 break;
2274 cols += width;
2277 *rcol = cols;
2278 return i;
2282 * Format a line for display, ensuring that it won't overflow a width limit.
2283 * With scrolling, the width returned refers to the scrolled version of the
2284 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2286 static const struct got_error *
2287 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2288 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2290 const struct got_error *err = NULL;
2291 int cols;
2292 wchar_t *wline = NULL;
2293 char *exstr = NULL;
2294 size_t wlen;
2295 int i, scrollx;
2297 *wlinep = NULL;
2298 *widthp = 0;
2300 if (expand) {
2301 err = expand_tab(&exstr, line);
2302 if (err)
2303 return err;
2306 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2307 free(exstr);
2308 if (err)
2309 return err;
2311 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2313 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2314 wline[wlen - 1] = L'\0';
2315 wlen--;
2317 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2318 wline[wlen - 1] = L'\0';
2319 wlen--;
2322 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2323 wline[i] = L'\0';
2325 if (widthp)
2326 *widthp = cols;
2327 if (scrollxp)
2328 *scrollxp = scrollx;
2329 if (err)
2330 free(wline);
2331 else
2332 *wlinep = wline;
2333 return err;
2336 static const struct got_error*
2337 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2338 struct got_object_id *id, struct got_repository *repo)
2340 static const struct got_error *err = NULL;
2341 struct got_reflist_entry *re;
2342 char *s;
2343 const char *name;
2345 *refs_str = NULL;
2347 if (refs == NULL)
2348 return NULL;
2350 TAILQ_FOREACH(re, refs, entry) {
2351 struct got_tag_object *tag = NULL;
2352 struct got_object_id *ref_id;
2353 int cmp;
2355 name = got_ref_get_name(re->ref);
2356 if (strcmp(name, GOT_REF_HEAD) == 0)
2357 continue;
2358 if (strncmp(name, "refs/", 5) == 0)
2359 name += 5;
2360 if (strncmp(name, "got/", 4) == 0)
2361 continue;
2362 if (strncmp(name, "heads/", 6) == 0)
2363 name += 6;
2364 if (strncmp(name, "remotes/", 8) == 0) {
2365 name += 8;
2366 s = strstr(name, "/" GOT_REF_HEAD);
2367 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
2368 continue;
2370 err = got_ref_resolve(&ref_id, repo, re->ref);
2371 if (err)
2372 break;
2373 if (strncmp(name, "tags/", 5) == 0) {
2374 err = got_object_open_as_tag(&tag, repo, ref_id);
2375 if (err) {
2376 if (err->code != GOT_ERR_OBJ_TYPE) {
2377 free(ref_id);
2378 break;
2380 /* Ref points at something other than a tag. */
2381 err = NULL;
2382 tag = NULL;
2385 cmp = got_object_id_cmp(tag ?
2386 got_object_tag_get_object_id(tag) : ref_id, id);
2387 free(ref_id);
2388 if (tag)
2389 got_object_tag_close(tag);
2390 if (cmp != 0)
2391 continue;
2392 s = *refs_str;
2393 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2394 s ? ", " : "", name) == -1) {
2395 err = got_error_from_errno("asprintf");
2396 free(s);
2397 *refs_str = NULL;
2398 break;
2400 free(s);
2403 return err;
2406 static const struct got_error *
2407 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2408 int col_tab_align)
2410 char *smallerthan;
2412 smallerthan = strchr(author, '<');
2413 if (smallerthan && smallerthan[1] != '\0')
2414 author = smallerthan + 1;
2415 author[strcspn(author, "@>")] = '\0';
2416 return format_line(wauthor, author_width, NULL, author, 0, limit,
2417 col_tab_align, 0);
2420 static const struct got_error *
2421 draw_commit(struct tog_view *view, struct commit_queue_entry *entry,
2422 const size_t date_display_cols, int author_display_cols)
2424 struct tog_log_view_state *s = &view->state.log;
2425 const struct got_error *err = NULL;
2426 struct got_commit_object *commit = entry->commit;
2427 struct got_object_id *id = entry->id;
2428 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2429 char *refs_str = NULL;
2430 char *logmsg0 = NULL, *logmsg = NULL;
2431 char *author = NULL;
2432 wchar_t *wrefstr = NULL, *wlogmsg = NULL, *wauthor = NULL;
2433 int author_width, refstr_width, logmsg_width;
2434 char *newline, *line = NULL;
2435 int col, limit, scrollx, logmsg_x;
2436 const int avail = view->ncols, marker_column = author_display_cols + 1;
2437 struct tm tm;
2438 time_t committer_time;
2439 struct tog_color *tc;
2440 struct got_reflist_head *refs;
2442 if (tog_base_commit.id != NULL && tog_base_commit.idx == -1 &&
2443 got_object_id_cmp(id, tog_base_commit.id) == 0)
2444 tog_base_commit.idx = entry->idx;
2445 if (tog_io.wait_for_ui && s->thread_args.need_commit_marker) {
2446 int rc;
2448 rc = pthread_cond_wait(&s->thread_args.log_loaded, &tog_mutex);
2449 if (rc)
2450 return got_error_set_errno(rc, "pthread_cond_wait");
2453 committer_time = got_object_commit_get_committer_time(commit);
2454 if (gmtime_r(&committer_time, &tm) == NULL)
2455 return got_error_from_errno("gmtime_r");
2456 if (strftime(datebuf, sizeof(datebuf), "%F ", &tm) == 0)
2457 return got_error(GOT_ERR_NO_SPACE);
2459 if (avail <= date_display_cols)
2460 limit = MIN(sizeof(datebuf) - 1, avail);
2461 else
2462 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2463 tc = get_color(&s->colors, TOG_COLOR_DATE);
2464 if (tc)
2465 wattr_on(view->window,
2466 COLOR_PAIR(tc->colorpair), NULL);
2467 waddnstr(view->window, datebuf, limit);
2468 if (tc)
2469 wattr_off(view->window,
2470 COLOR_PAIR(tc->colorpair), NULL);
2471 col = limit;
2472 if (col > avail)
2473 goto done;
2475 if (avail >= 120) {
2476 char *id_str;
2477 err = got_object_id_str(&id_str, id);
2478 if (err)
2479 goto done;
2480 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2481 if (tc)
2482 wattr_on(view->window,
2483 COLOR_PAIR(tc->colorpair), NULL);
2484 wprintw(view->window, "%.8s ", id_str);
2485 if (tc)
2486 wattr_off(view->window,
2487 COLOR_PAIR(tc->colorpair), NULL);
2488 free(id_str);
2489 col += 9;
2490 if (col > avail)
2491 goto done;
2494 if (s->use_committer)
2495 author = strdup(got_object_commit_get_committer(commit));
2496 else
2497 author = strdup(got_object_commit_get_author(commit));
2498 if (author == NULL) {
2499 err = got_error_from_errno("strdup");
2500 goto done;
2502 err = format_author(&wauthor, &author_width, author, avail - col, col);
2503 if (err)
2504 goto done;
2505 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2506 if (tc)
2507 wattr_on(view->window,
2508 COLOR_PAIR(tc->colorpair), NULL);
2509 waddwstr(view->window, wauthor);
2510 col += author_width;
2511 while (col < avail && author_width < author_display_cols + 2) {
2512 if (tog_base_commit.marker != GOT_WORKTREE_STATE_UNKNOWN &&
2513 author_width == marker_column &&
2514 entry->idx == tog_base_commit.idx && !s->limit_view) {
2515 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2516 if (tc)
2517 wattr_on(view->window,
2518 COLOR_PAIR(tc->colorpair), NULL);
2519 waddch(view->window, tog_base_commit.marker);
2520 if (tc)
2521 wattr_off(view->window,
2522 COLOR_PAIR(tc->colorpair), NULL);
2523 } else
2524 waddch(view->window, ' ');
2525 col++;
2526 author_width++;
2528 if (tc)
2529 wattr_off(view->window,
2530 COLOR_PAIR(tc->colorpair), NULL);
2531 if (col > avail)
2532 goto done;
2534 err = got_object_commit_get_logmsg(&logmsg0, commit);
2535 if (err)
2536 goto done;
2537 logmsg = logmsg0;
2538 while (*logmsg == '\n')
2539 logmsg++;
2540 newline = strchr(logmsg, '\n');
2541 if (newline)
2542 *newline = '\0';
2544 limit = avail - col;
2545 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2546 limit--; /* for the border */
2548 /* Prepend reference labels to log message if possible .*/
2549 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, id);
2550 err = build_refs_str(&refs_str, refs, id, s->repo);
2551 if (err)
2552 goto done;
2553 if (refs_str) {
2554 char *rs;
2556 if (asprintf(&rs, "[%s]", refs_str) == -1) {
2557 err = got_error_from_errno("asprintf");
2558 goto done;
2560 err = format_line(&wrefstr, &refstr_width,
2561 &scrollx, rs, view->x, limit, col, 1);
2562 free(rs);
2563 if (err)
2564 goto done;
2565 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2566 if (tc)
2567 wattr_on(view->window,
2568 COLOR_PAIR(tc->colorpair), NULL);
2569 waddwstr(view->window, &wrefstr[scrollx]);
2570 if (tc)
2571 wattr_off(view->window,
2572 COLOR_PAIR(tc->colorpair), NULL);
2573 col += MAX(refstr_width, 0);
2574 if (col > avail)
2575 goto done;
2577 if (col < avail) {
2578 waddch(view->window, ' ');
2579 col++;
2582 if (refstr_width > 0)
2583 logmsg_x = 0;
2584 else {
2585 int unscrolled_refstr_width;
2586 size_t len = wcslen(wrefstr);
2589 * No need to check for -1 return value here since
2590 * unprintables have been replaced by span_wline().
2592 unscrolled_refstr_width = wcswidth(wrefstr, len);
2593 unscrolled_refstr_width += 1; /* trailing space */
2594 logmsg_x = view->x - unscrolled_refstr_width;
2597 limit = avail - col;
2598 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2599 limit--; /* for the border */
2600 } else
2601 logmsg_x = view->x;
2603 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, logmsg_x,
2604 limit, col, 1);
2605 if (err)
2606 goto done;
2607 waddwstr(view->window, &wlogmsg[scrollx]);
2608 col += MAX(logmsg_width, 0);
2609 while (col < avail) {
2610 waddch(view->window, ' ');
2611 col++;
2613 done:
2614 free(logmsg0);
2615 free(wlogmsg);
2616 free(wrefstr);
2617 free(refs_str);
2618 free(author);
2619 free(wauthor);
2620 free(line);
2621 return err;
2624 static struct commit_queue_entry *
2625 alloc_commit_queue_entry(struct got_commit_object *commit,
2626 struct got_object_id *id)
2628 struct commit_queue_entry *entry;
2629 struct got_object_id *dup;
2631 entry = calloc(1, sizeof(*entry));
2632 if (entry == NULL)
2633 return NULL;
2635 dup = got_object_id_dup(id);
2636 if (dup == NULL) {
2637 free(entry);
2638 return NULL;
2641 entry->id = dup;
2642 entry->commit = commit;
2643 return entry;
2646 static void
2647 pop_commit(struct commit_queue *commits)
2649 struct commit_queue_entry *entry;
2651 entry = TAILQ_FIRST(&commits->head);
2652 TAILQ_REMOVE(&commits->head, entry, entry);
2653 got_object_commit_close(entry->commit);
2654 commits->ncommits--;
2655 free(entry->id);
2656 free(entry);
2659 static void
2660 free_commits(struct commit_queue *commits)
2662 while (!TAILQ_EMPTY(&commits->head))
2663 pop_commit(commits);
2666 static const struct got_error *
2667 match_commit(int *have_match, struct got_object_id *id,
2668 struct got_commit_object *commit, regex_t *regex)
2670 const struct got_error *err = NULL;
2671 regmatch_t regmatch;
2672 char *id_str = NULL, *logmsg = NULL;
2674 *have_match = 0;
2676 err = got_object_id_str(&id_str, id);
2677 if (err)
2678 return err;
2680 err = got_object_commit_get_logmsg(&logmsg, commit);
2681 if (err)
2682 goto done;
2684 if (regexec(regex, got_object_commit_get_author(commit), 1,
2685 &regmatch, 0) == 0 ||
2686 regexec(regex, got_object_commit_get_committer(commit), 1,
2687 &regmatch, 0) == 0 ||
2688 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2689 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2690 *have_match = 1;
2691 done:
2692 free(id_str);
2693 free(logmsg);
2694 return err;
2697 static const struct got_error *
2698 queue_commits(struct tog_log_thread_args *a)
2700 const struct got_error *err = NULL;
2703 * We keep all commits open throughout the lifetime of the log
2704 * view in order to avoid having to re-fetch commits from disk
2705 * while updating the display.
2707 do {
2708 struct got_object_id id;
2709 struct got_commit_object *commit;
2710 struct commit_queue_entry *entry;
2711 int limit_match = 0;
2712 int errcode;
2714 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2715 NULL, NULL);
2716 if (err)
2717 break;
2719 err = got_object_open_as_commit(&commit, a->repo, &id);
2720 if (err)
2721 break;
2722 entry = alloc_commit_queue_entry(commit, &id);
2723 if (entry == NULL) {
2724 err = got_error_from_errno("alloc_commit_queue_entry");
2725 break;
2728 errcode = pthread_mutex_lock(&tog_mutex);
2729 if (errcode) {
2730 err = got_error_set_errno(errcode,
2731 "pthread_mutex_lock");
2732 break;
2735 entry->idx = a->real_commits->ncommits;
2736 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2737 a->real_commits->ncommits++;
2739 if (*a->limiting) {
2740 err = match_commit(&limit_match, &id, commit,
2741 a->limit_regex);
2742 if (err)
2743 break;
2745 if (limit_match) {
2746 struct commit_queue_entry *matched;
2748 matched = alloc_commit_queue_entry(
2749 entry->commit, entry->id);
2750 if (matched == NULL) {
2751 err = got_error_from_errno(
2752 "alloc_commit_queue_entry");
2753 break;
2755 matched->commit = entry->commit;
2756 got_object_commit_retain(entry->commit);
2758 matched->idx = a->limit_commits->ncommits;
2759 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2760 matched, entry);
2761 a->limit_commits->ncommits++;
2765 * This is how we signal log_thread() that we
2766 * have found a match, and that it should be
2767 * counted as a new entry for the view.
2769 a->limit_match = limit_match;
2772 if (*a->searching == TOG_SEARCH_FORWARD &&
2773 !*a->search_next_done) {
2774 int have_match;
2775 err = match_commit(&have_match, &id, commit, a->regex);
2776 if (err)
2777 break;
2779 if (*a->limiting) {
2780 if (limit_match && have_match)
2781 *a->search_next_done =
2782 TOG_SEARCH_HAVE_MORE;
2783 } else if (have_match)
2784 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2787 errcode = pthread_mutex_unlock(&tog_mutex);
2788 if (errcode && err == NULL)
2789 err = got_error_set_errno(errcode,
2790 "pthread_mutex_unlock");
2791 if (err)
2792 break;
2793 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2795 return err;
2798 static void
2799 select_commit(struct tog_log_view_state *s)
2801 struct commit_queue_entry *entry;
2802 int ncommits = 0;
2804 entry = s->first_displayed_entry;
2805 while (entry) {
2806 if (ncommits == s->selected) {
2807 s->selected_entry = entry;
2808 break;
2810 entry = TAILQ_NEXT(entry, entry);
2811 ncommits++;
2815 static const struct got_error *
2816 draw_commits(struct tog_view *view)
2818 const struct got_error *err = NULL;
2819 struct tog_log_view_state *s = &view->state.log;
2820 struct commit_queue_entry *entry = s->selected_entry;
2821 int limit = view->nlines;
2822 int width;
2823 int ncommits, author_cols = 4, refstr_cols;
2824 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2825 char *refs_str = NULL;
2826 wchar_t *wline;
2827 struct tog_color *tc;
2828 static const size_t date_display_cols = 12;
2829 struct got_reflist_head *refs;
2831 if (view_is_hsplit_top(view))
2832 --limit; /* account for border */
2834 if (s->selected_entry &&
2835 !(view->searching && view->search_next_done == 0)) {
2836 err = got_object_id_str(&id_str, s->selected_entry->id);
2837 if (err)
2838 return err;
2839 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2840 s->selected_entry->id);
2841 err = build_refs_str(&refs_str, refs, s->selected_entry->id,
2842 s->repo);
2843 if (err)
2844 goto done;
2847 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2848 halfdelay(10); /* disable fast refresh */
2850 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2851 if (asprintf(&ncommits_str, " [%d/%d] %s",
2852 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2853 (view->searching && !view->search_next_done) ?
2854 "searching..." : "loading...") == -1) {
2855 err = got_error_from_errno("asprintf");
2856 goto done;
2858 } else {
2859 const char *search_str = NULL;
2860 const char *limit_str = NULL;
2862 if (view->searching) {
2863 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2864 search_str = "no more matches";
2865 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2866 search_str = "no matches found";
2867 else if (!view->search_next_done)
2868 search_str = "searching...";
2871 if (s->limit_view && s->commits->ncommits == 0)
2872 limit_str = "no matches found";
2874 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2875 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2876 search_str ? search_str : (refs_str ? refs_str : ""),
2877 limit_str ? limit_str : "") == -1) {
2878 err = got_error_from_errno("asprintf");
2879 goto done;
2883 free(refs_str);
2884 refs_str = NULL;
2886 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2887 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2888 "........................................",
2889 s->in_repo_path, ncommits_str) == -1) {
2890 err = got_error_from_errno("asprintf");
2891 header = NULL;
2892 goto done;
2894 } else if (asprintf(&header, "commit %s%s",
2895 id_str ? id_str : "........................................",
2896 ncommits_str) == -1) {
2897 err = got_error_from_errno("asprintf");
2898 header = NULL;
2899 goto done;
2901 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2902 if (err)
2903 goto done;
2905 werase(view->window);
2907 if (view_needs_focus_indication(view))
2908 wstandout(view->window);
2909 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2910 if (tc)
2911 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2912 waddwstr(view->window, wline);
2913 while (width < view->ncols) {
2914 waddch(view->window, ' ');
2915 width++;
2917 if (tc)
2918 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2919 if (view_needs_focus_indication(view))
2920 wstandend(view->window);
2921 free(wline);
2922 if (limit <= 1)
2923 goto done;
2925 /* Grow author column size if necessary, and set view->maxx. */
2926 entry = s->first_displayed_entry;
2927 ncommits = 0;
2928 view->maxx = 0;
2929 while (entry) {
2930 struct got_commit_object *c = entry->commit;
2931 char *author, *eol, *msg, *msg0;
2932 wchar_t *wauthor, *wmsg;
2933 int width;
2934 if (ncommits >= limit - 1)
2935 break;
2936 if (s->use_committer)
2937 author = strdup(got_object_commit_get_committer(c));
2938 else
2939 author = strdup(got_object_commit_get_author(c));
2940 if (author == NULL) {
2941 err = got_error_from_errno("strdup");
2942 goto done;
2944 err = format_author(&wauthor, &width, author, COLS,
2945 date_display_cols);
2946 if (author_cols < width)
2947 author_cols = width;
2948 free(wauthor);
2949 free(author);
2950 if (err)
2951 goto done;
2952 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2953 entry->id);
2954 err = build_refs_str(&refs_str, refs, entry->id, s->repo);
2955 if (err)
2956 goto done;
2957 if (refs_str) {
2958 wchar_t *ws;
2959 err = format_line(&ws, &width, NULL, refs_str,
2960 0, INT_MAX, date_display_cols + author_cols, 0);
2961 free(ws);
2962 free(refs_str);
2963 refs_str = NULL;
2964 if (err)
2965 goto done;
2966 refstr_cols = width + 3; /* account for [ ] + space */
2967 } else
2968 refstr_cols = 0;
2969 err = got_object_commit_get_logmsg(&msg0, c);
2970 if (err)
2971 goto done;
2972 msg = msg0;
2973 while (*msg == '\n')
2974 ++msg;
2975 if ((eol = strchr(msg, '\n')))
2976 *eol = '\0';
2977 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2978 date_display_cols + author_cols + refstr_cols, 0);
2979 if (err)
2980 goto done;
2981 view->maxx = MAX(view->maxx, width + refstr_cols);
2982 free(msg0);
2983 free(wmsg);
2984 ncommits++;
2985 entry = TAILQ_NEXT(entry, entry);
2988 entry = s->first_displayed_entry;
2989 s->last_displayed_entry = s->first_displayed_entry;
2990 ncommits = 0;
2991 while (entry) {
2992 if (ncommits >= limit - 1)
2993 break;
2994 if (ncommits == s->selected)
2995 wstandout(view->window);
2996 err = draw_commit(view, entry, date_display_cols, author_cols);
2997 if (ncommits == s->selected)
2998 wstandend(view->window);
2999 if (err)
3000 goto done;
3001 ncommits++;
3002 s->last_displayed_entry = entry;
3003 entry = TAILQ_NEXT(entry, entry);
3006 view_border(view);
3007 done:
3008 free(id_str);
3009 free(refs_str);
3010 free(ncommits_str);
3011 free(header);
3012 return err;
3015 static void
3016 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
3018 struct commit_queue_entry *entry;
3019 int nscrolled = 0;
3021 entry = TAILQ_FIRST(&s->commits->head);
3022 if (s->first_displayed_entry == entry)
3023 return;
3025 entry = s->first_displayed_entry;
3026 while (entry && nscrolled < maxscroll) {
3027 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3028 if (entry) {
3029 s->first_displayed_entry = entry;
3030 nscrolled++;
3035 static const struct got_error *
3036 trigger_log_thread(struct tog_view *view, int wait)
3038 struct tog_log_thread_args *ta = &view->state.log.thread_args;
3039 int errcode;
3041 if (!using_mock_io)
3042 halfdelay(1); /* fast refresh while loading commits */
3044 while (!ta->log_complete && !tog_thread_error &&
3045 (ta->commits_needed > 0 || ta->load_all)) {
3046 /* Wake the log thread. */
3047 errcode = pthread_cond_signal(&ta->need_commits);
3048 if (errcode)
3049 return got_error_set_errno(errcode,
3050 "pthread_cond_signal");
3053 * The mutex will be released while the view loop waits
3054 * in wgetch(), at which time the log thread will run.
3056 if (!wait)
3057 break;
3059 /* Display progress update in log view. */
3060 show_log_view(view);
3061 update_panels();
3062 doupdate();
3064 /* Wait right here while next commit is being loaded. */
3065 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
3066 if (errcode)
3067 return got_error_set_errno(errcode,
3068 "pthread_cond_wait");
3070 /* Display progress update in log view. */
3071 show_log_view(view);
3072 update_panels();
3073 doupdate();
3076 return NULL;
3079 static const struct got_error *
3080 request_log_commits(struct tog_view *view)
3082 struct tog_log_view_state *state = &view->state.log;
3083 const struct got_error *err = NULL;
3085 if (state->thread_args.log_complete)
3086 return NULL;
3088 state->thread_args.commits_needed += view->nscrolled;
3089 err = trigger_log_thread(view, 1);
3090 view->nscrolled = 0;
3092 return err;
3095 static const struct got_error *
3096 log_scroll_down(struct tog_view *view, int maxscroll)
3098 struct tog_log_view_state *s = &view->state.log;
3099 const struct got_error *err = NULL;
3100 struct commit_queue_entry *pentry;
3101 int nscrolled = 0, ncommits_needed;
3103 if (s->last_displayed_entry == NULL)
3104 return NULL;
3106 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
3107 if (s->commits->ncommits < ncommits_needed &&
3108 !s->thread_args.log_complete) {
3110 * Ask the log thread for required amount of commits.
3112 s->thread_args.commits_needed +=
3113 ncommits_needed - s->commits->ncommits;
3114 err = trigger_log_thread(view, 1);
3115 if (err)
3116 return err;
3119 do {
3120 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
3121 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
3122 break;
3124 s->last_displayed_entry = pentry ?
3125 pentry : s->last_displayed_entry;
3127 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3128 if (pentry == NULL)
3129 break;
3130 s->first_displayed_entry = pentry;
3131 } while (++nscrolled < maxscroll);
3133 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3134 view->nscrolled += nscrolled;
3135 else
3136 view->nscrolled = 0;
3138 return err;
3141 static const struct got_error *
3142 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3143 struct got_commit_object *commit, struct got_object_id *commit_id,
3144 struct tog_view *log_view, struct got_repository *repo)
3146 const struct got_error *err;
3147 struct got_object_qid *parent_id;
3148 struct tog_view *diff_view;
3150 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3151 if (diff_view == NULL)
3152 return got_error_from_errno("view_open");
3154 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3155 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3156 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3157 if (err == NULL)
3158 *new_view = diff_view;
3159 return err;
3162 static const struct got_error *
3163 tree_view_visit_subtree(struct tog_tree_view_state *s,
3164 struct got_tree_object *subtree)
3166 struct tog_parent_tree *parent;
3168 parent = calloc(1, sizeof(*parent));
3169 if (parent == NULL)
3170 return got_error_from_errno("calloc");
3172 parent->tree = s->tree;
3173 parent->first_displayed_entry = s->first_displayed_entry;
3174 parent->selected_entry = s->selected_entry;
3175 parent->selected = s->selected;
3176 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3177 s->tree = subtree;
3178 s->selected = 0;
3179 s->first_displayed_entry = NULL;
3180 return NULL;
3183 static const struct got_error *
3184 tree_view_walk_path(struct tog_tree_view_state *s,
3185 struct got_commit_object *commit, const char *path)
3187 const struct got_error *err = NULL;
3188 struct got_tree_object *tree = NULL;
3189 const char *p;
3190 char *slash, *subpath = NULL;
3192 /* Walk the path and open corresponding tree objects. */
3193 p = path;
3194 while (*p) {
3195 struct got_tree_entry *te;
3196 struct got_object_id *tree_id;
3197 char *te_name;
3199 while (p[0] == '/')
3200 p++;
3202 /* Ensure the correct subtree entry is selected. */
3203 slash = strchr(p, '/');
3204 if (slash == NULL)
3205 te_name = strdup(p);
3206 else
3207 te_name = strndup(p, slash - p);
3208 if (te_name == NULL) {
3209 err = got_error_from_errno("strndup");
3210 break;
3212 te = got_object_tree_find_entry(s->tree, te_name);
3213 if (te == NULL) {
3214 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3215 free(te_name);
3216 break;
3218 free(te_name);
3219 s->first_displayed_entry = s->selected_entry = te;
3221 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3222 break; /* jump to this file's entry */
3224 slash = strchr(p, '/');
3225 if (slash)
3226 subpath = strndup(path, slash - path);
3227 else
3228 subpath = strdup(path);
3229 if (subpath == NULL) {
3230 err = got_error_from_errno("strdup");
3231 break;
3234 err = got_object_id_by_path(&tree_id, s->repo, commit,
3235 subpath);
3236 if (err)
3237 break;
3239 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3240 free(tree_id);
3241 if (err)
3242 break;
3244 err = tree_view_visit_subtree(s, tree);
3245 if (err) {
3246 got_object_tree_close(tree);
3247 break;
3249 if (slash == NULL)
3250 break;
3251 free(subpath);
3252 subpath = NULL;
3253 p = slash;
3256 free(subpath);
3257 return err;
3260 static const struct got_error *
3261 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3262 struct commit_queue_entry *entry, const char *path,
3263 const char *head_ref_name, struct got_repository *repo)
3265 const struct got_error *err = NULL;
3266 struct tog_tree_view_state *s;
3267 struct tog_view *tree_view;
3269 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3270 if (tree_view == NULL)
3271 return got_error_from_errno("view_open");
3273 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3274 if (err)
3275 return err;
3276 s = &tree_view->state.tree;
3278 *new_view = tree_view;
3280 if (got_path_is_root_dir(path))
3281 return NULL;
3283 return tree_view_walk_path(s, entry->commit, path);
3286 static const struct got_error *
3287 block_signals_used_by_main_thread(void)
3289 sigset_t sigset;
3290 int errcode;
3292 if (sigemptyset(&sigset) == -1)
3293 return got_error_from_errno("sigemptyset");
3295 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3296 if (sigaddset(&sigset, SIGWINCH) == -1)
3297 return got_error_from_errno("sigaddset");
3298 if (sigaddset(&sigset, SIGCONT) == -1)
3299 return got_error_from_errno("sigaddset");
3300 if (sigaddset(&sigset, SIGINT) == -1)
3301 return got_error_from_errno("sigaddset");
3302 if (sigaddset(&sigset, SIGTERM) == -1)
3303 return got_error_from_errno("sigaddset");
3305 /* ncurses handles SIGTSTP */
3306 if (sigaddset(&sigset, SIGTSTP) == -1)
3307 return got_error_from_errno("sigaddset");
3309 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3310 if (errcode)
3311 return got_error_set_errno(errcode, "pthread_sigmask");
3313 return NULL;
3316 static void *
3317 log_thread(void *arg)
3319 const struct got_error *err = NULL;
3320 int errcode = 0;
3321 struct tog_log_thread_args *a = arg;
3322 int done = 0;
3325 * Sync startup with main thread such that we begin our
3326 * work once view_input() has released the mutex.
3328 errcode = pthread_mutex_lock(&tog_mutex);
3329 if (errcode) {
3330 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3331 return (void *)err;
3334 err = block_signals_used_by_main_thread();
3335 if (err) {
3336 pthread_mutex_unlock(&tog_mutex);
3337 goto done;
3340 while (!done && !err && !tog_fatal_signal_received()) {
3341 errcode = pthread_mutex_unlock(&tog_mutex);
3342 if (errcode) {
3343 err = got_error_set_errno(errcode,
3344 "pthread_mutex_unlock");
3345 goto done;
3347 err = queue_commits(a);
3348 if (err) {
3349 if (err->code != GOT_ERR_ITER_COMPLETED)
3350 goto done;
3351 err = NULL;
3352 done = 1;
3353 a->commits_needed = 0;
3354 } else if (a->commits_needed > 0 && !a->load_all) {
3355 if (*a->limiting) {
3356 if (a->limit_match)
3357 a->commits_needed--;
3358 } else
3359 a->commits_needed--;
3362 errcode = pthread_mutex_lock(&tog_mutex);
3363 if (errcode) {
3364 err = got_error_set_errno(errcode,
3365 "pthread_mutex_lock");
3366 goto done;
3367 } else if (*a->quit)
3368 done = 1;
3369 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3370 *a->first_displayed_entry =
3371 TAILQ_FIRST(&a->limit_commits->head);
3372 *a->selected_entry = *a->first_displayed_entry;
3373 } else if (*a->first_displayed_entry == NULL) {
3374 *a->first_displayed_entry =
3375 TAILQ_FIRST(&a->real_commits->head);
3376 *a->selected_entry = *a->first_displayed_entry;
3379 errcode = pthread_cond_signal(&a->commit_loaded);
3380 if (errcode) {
3381 err = got_error_set_errno(errcode,
3382 "pthread_cond_signal");
3383 pthread_mutex_unlock(&tog_mutex);
3384 goto done;
3387 if (a->commits_needed == 0 &&
3388 a->need_commit_marker && a->worktree) {
3389 errcode = pthread_mutex_unlock(&tog_mutex);
3390 if (errcode) {
3391 err = got_error_set_errno(errcode,
3392 "pthread_mutex_unlock");
3393 goto done;
3395 err = got_worktree_get_state(&tog_base_commit.marker,
3396 a->repo, a->worktree, NULL, NULL);
3397 if (err)
3398 goto done;
3399 errcode = pthread_mutex_lock(&tog_mutex);
3400 if (errcode) {
3401 err = got_error_set_errno(errcode,
3402 "pthread_mutex_lock");
3403 goto done;
3405 a->need_commit_marker = 0;
3407 * The main thread did not close this
3408 * work tree yet. Close it now.
3410 got_worktree_close(a->worktree);
3411 a->worktree = NULL;
3413 if (*a->quit)
3414 done = 1;
3417 if (done)
3418 a->commits_needed = 0;
3419 else {
3420 if (a->commits_needed == 0 && !a->load_all) {
3421 if (tog_io.wait_for_ui) {
3422 errcode = pthread_cond_signal(
3423 &a->log_loaded);
3424 if (errcode && err == NULL)
3425 err = got_error_set_errno(
3426 errcode,
3427 "pthread_cond_signal");
3430 errcode = pthread_cond_wait(&a->need_commits,
3431 &tog_mutex);
3432 if (errcode) {
3433 err = got_error_set_errno(errcode,
3434 "pthread_cond_wait");
3435 pthread_mutex_unlock(&tog_mutex);
3436 goto done;
3438 if (*a->quit)
3439 done = 1;
3443 a->log_complete = 1;
3444 if (tog_io.wait_for_ui) {
3445 errcode = pthread_cond_signal(&a->log_loaded);
3446 if (errcode && err == NULL)
3447 err = got_error_set_errno(errcode,
3448 "pthread_cond_signal");
3451 errcode = pthread_mutex_unlock(&tog_mutex);
3452 if (errcode)
3453 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3454 done:
3455 if (err) {
3456 tog_thread_error = 1;
3457 pthread_cond_signal(&a->commit_loaded);
3458 if (a->worktree) {
3459 got_worktree_close(a->worktree);
3460 a->worktree = NULL;
3463 return (void *)err;
3466 static const struct got_error *
3467 stop_log_thread(struct tog_log_view_state *s)
3469 const struct got_error *err = NULL, *thread_err = NULL;
3470 int errcode;
3472 if (s->thread) {
3473 s->quit = 1;
3474 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3475 if (errcode)
3476 return got_error_set_errno(errcode,
3477 "pthread_cond_signal");
3478 errcode = pthread_mutex_unlock(&tog_mutex);
3479 if (errcode)
3480 return got_error_set_errno(errcode,
3481 "pthread_mutex_unlock");
3482 errcode = pthread_join(s->thread, (void **)&thread_err);
3483 if (errcode)
3484 return got_error_set_errno(errcode, "pthread_join");
3485 errcode = pthread_mutex_lock(&tog_mutex);
3486 if (errcode)
3487 return got_error_set_errno(errcode,
3488 "pthread_mutex_lock");
3489 s->thread = 0; //NULL;
3492 if (s->thread_args.repo) {
3493 err = got_repo_close(s->thread_args.repo);
3494 s->thread_args.repo = NULL;
3497 if (s->thread_args.pack_fds) {
3498 const struct got_error *pack_err =
3499 got_repo_pack_fds_close(s->thread_args.pack_fds);
3500 if (err == NULL)
3501 err = pack_err;
3502 s->thread_args.pack_fds = NULL;
3505 if (s->thread_args.graph) {
3506 got_commit_graph_close(s->thread_args.graph);
3507 s->thread_args.graph = NULL;
3510 return err ? err : thread_err;
3513 static const struct got_error *
3514 close_log_view(struct tog_view *view)
3516 const struct got_error *err = NULL;
3517 struct tog_log_view_state *s = &view->state.log;
3518 int errcode;
3520 err = stop_log_thread(s);
3522 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3523 if (errcode && err == NULL)
3524 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3526 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3527 if (errcode && err == NULL)
3528 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3530 free_commits(&s->limit_commits);
3531 free_commits(&s->real_commits);
3532 free_colors(&s->colors);
3533 free(s->in_repo_path);
3534 s->in_repo_path = NULL;
3535 free(s->start_id);
3536 s->start_id = NULL;
3537 free(s->head_ref_name);
3538 s->head_ref_name = NULL;
3539 return err;
3543 * We use two queues to implement the limit feature: first consists of
3544 * commits matching the current limit_regex; second is the real queue
3545 * of all known commits (real_commits). When the user starts limiting,
3546 * we swap queues such that all movement and displaying functionality
3547 * works with very slight change.
3549 static const struct got_error *
3550 limit_log_view(struct tog_view *view)
3552 struct tog_log_view_state *s = &view->state.log;
3553 struct commit_queue_entry *entry;
3554 struct tog_view *v = view;
3555 const struct got_error *err = NULL;
3556 char pattern[1024];
3557 int ret;
3559 if (view_is_hsplit_top(view))
3560 v = view->child;
3561 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3562 v = view->parent;
3564 if (tog_io.input_str != NULL) {
3565 if (strlcpy(pattern, tog_io.input_str, sizeof(pattern)) >=
3566 sizeof(pattern))
3567 return got_error(GOT_ERR_NO_SPACE);
3568 } else {
3569 wmove(v->window, v->nlines - 1, 0);
3570 wclrtoeol(v->window);
3571 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3572 nodelay(v->window, FALSE);
3573 nocbreak();
3574 echo();
3575 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3576 cbreak();
3577 noecho();
3578 nodelay(v->window, TRUE);
3579 if (ret == ERR)
3580 return NULL;
3583 if (*pattern == '\0') {
3585 * Safety measure for the situation where the user
3586 * resets limit without previously limiting anything.
3588 if (!s->limit_view)
3589 return NULL;
3592 * User could have pressed Ctrl+L, which refreshed the
3593 * commit queues, it means we can't save previously
3594 * (before limit took place) displayed entries,
3595 * because they would point to already free'ed memory,
3596 * so we are forced to always select first entry of
3597 * the queue.
3599 s->commits = &s->real_commits;
3600 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3601 s->selected_entry = s->first_displayed_entry;
3602 s->selected = 0;
3603 s->limit_view = 0;
3605 return NULL;
3608 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3609 return NULL;
3611 s->limit_view = 1;
3613 /* Clear the screen while loading limit view */
3614 s->first_displayed_entry = NULL;
3615 s->last_displayed_entry = NULL;
3616 s->selected_entry = NULL;
3617 s->commits = &s->limit_commits;
3619 /* Prepare limit queue for new search */
3620 free_commits(&s->limit_commits);
3621 s->limit_commits.ncommits = 0;
3623 /* First process commits, which are in queue already */
3624 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3625 int have_match = 0;
3627 err = match_commit(&have_match, entry->id,
3628 entry->commit, &s->limit_regex);
3629 if (err)
3630 return err;
3632 if (have_match) {
3633 struct commit_queue_entry *matched;
3635 matched = alloc_commit_queue_entry(entry->commit,
3636 entry->id);
3637 if (matched == NULL) {
3638 err = got_error_from_errno(
3639 "alloc_commit_queue_entry");
3640 break;
3642 matched->commit = entry->commit;
3643 got_object_commit_retain(entry->commit);
3645 matched->idx = s->limit_commits.ncommits;
3646 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3647 matched, entry);
3648 s->limit_commits.ncommits++;
3652 /* Second process all the commits, until we fill the screen */
3653 if (s->limit_commits.ncommits < view->nlines - 1 &&
3654 !s->thread_args.log_complete) {
3655 s->thread_args.commits_needed +=
3656 view->nlines - s->limit_commits.ncommits - 1;
3657 err = trigger_log_thread(view, 1);
3658 if (err)
3659 return err;
3662 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3663 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3664 s->selected = 0;
3666 return NULL;
3669 static const struct got_error *
3670 search_start_log_view(struct tog_view *view)
3672 struct tog_log_view_state *s = &view->state.log;
3674 s->matched_entry = NULL;
3675 s->search_entry = NULL;
3676 return NULL;
3679 static const struct got_error *
3680 search_next_log_view(struct tog_view *view)
3682 const struct got_error *err = NULL;
3683 struct tog_log_view_state *s = &view->state.log;
3684 struct commit_queue_entry *entry;
3686 /* Display progress update in log view. */
3687 show_log_view(view);
3688 update_panels();
3689 doupdate();
3691 if (s->search_entry) {
3692 if (!using_mock_io) {
3693 int errcode, ch;
3695 errcode = pthread_mutex_unlock(&tog_mutex);
3696 if (errcode)
3697 return got_error_set_errno(errcode,
3698 "pthread_mutex_unlock");
3699 ch = wgetch(view->window);
3700 errcode = pthread_mutex_lock(&tog_mutex);
3701 if (errcode)
3702 return got_error_set_errno(errcode,
3703 "pthread_mutex_lock");
3704 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3705 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3706 return NULL;
3709 if (view->searching == TOG_SEARCH_FORWARD)
3710 entry = TAILQ_NEXT(s->search_entry, entry);
3711 else
3712 entry = TAILQ_PREV(s->search_entry,
3713 commit_queue_head, entry);
3714 } else if (s->matched_entry) {
3716 * If the user has moved the cursor after we hit a match,
3717 * the position from where we should continue searching
3718 * might have changed.
3720 if (view->searching == TOG_SEARCH_FORWARD)
3721 entry = TAILQ_NEXT(s->selected_entry, entry);
3722 else
3723 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3724 entry);
3725 } else {
3726 entry = s->selected_entry;
3729 while (1) {
3730 int have_match = 0;
3732 if (entry == NULL) {
3733 if (s->thread_args.log_complete ||
3734 view->searching == TOG_SEARCH_BACKWARD) {
3735 view->search_next_done =
3736 (s->matched_entry == NULL ?
3737 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3738 s->search_entry = NULL;
3739 return NULL;
3742 * Poke the log thread for more commits and return,
3743 * allowing the main loop to make progress. Search
3744 * will resume at s->search_entry once we come back.
3746 s->search_entry = s->selected_entry;
3747 s->thread_args.commits_needed++;
3748 return trigger_log_thread(view, 0);
3751 err = match_commit(&have_match, entry->id, entry->commit,
3752 &view->regex);
3753 if (err)
3754 break;
3755 if (have_match) {
3756 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3757 s->matched_entry = entry;
3758 break;
3761 s->search_entry = entry;
3762 if (view->searching == TOG_SEARCH_FORWARD)
3763 entry = TAILQ_NEXT(entry, entry);
3764 else
3765 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3768 if (s->matched_entry) {
3769 int cur = s->selected_entry->idx;
3770 while (cur < s->matched_entry->idx) {
3771 err = input_log_view(NULL, view, KEY_DOWN);
3772 if (err)
3773 return err;
3774 cur++;
3776 while (cur > s->matched_entry->idx) {
3777 err = input_log_view(NULL, view, KEY_UP);
3778 if (err)
3779 return err;
3780 cur--;
3784 s->search_entry = NULL;
3786 return NULL;
3789 static const struct got_error *
3790 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3791 struct got_repository *repo, const char *head_ref_name,
3792 const char *in_repo_path, int log_branches,
3793 struct got_worktree *worktree)
3795 const struct got_error *err = NULL;
3796 struct tog_log_view_state *s = &view->state.log;
3797 struct got_repository *thread_repo = NULL;
3798 struct got_commit_graph *thread_graph = NULL;
3799 int errcode;
3801 if (in_repo_path != s->in_repo_path) {
3802 free(s->in_repo_path);
3803 s->in_repo_path = strdup(in_repo_path);
3804 if (s->in_repo_path == NULL) {
3805 err = got_error_from_errno("strdup");
3806 goto done;
3810 /* The commit queue only contains commits being displayed. */
3811 TAILQ_INIT(&s->real_commits.head);
3812 s->real_commits.ncommits = 0;
3813 s->commits = &s->real_commits;
3815 TAILQ_INIT(&s->limit_commits.head);
3816 s->limit_view = 0;
3817 s->limit_commits.ncommits = 0;
3819 s->repo = repo;
3820 if (head_ref_name) {
3821 s->head_ref_name = strdup(head_ref_name);
3822 if (s->head_ref_name == NULL) {
3823 err = got_error_from_errno("strdup");
3824 goto done;
3827 s->start_id = got_object_id_dup(start_id);
3828 if (s->start_id == NULL) {
3829 err = got_error_from_errno("got_object_id_dup");
3830 goto done;
3832 s->log_branches = log_branches;
3833 s->use_committer = 1;
3835 STAILQ_INIT(&s->colors);
3836 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3837 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3838 get_color_value("TOG_COLOR_COMMIT"));
3839 if (err)
3840 goto done;
3841 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3842 get_color_value("TOG_COLOR_AUTHOR"));
3843 if (err)
3844 goto done;
3845 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3846 get_color_value("TOG_COLOR_DATE"));
3847 if (err)
3848 goto done;
3851 view->show = show_log_view;
3852 view->input = input_log_view;
3853 view->resize = resize_log_view;
3854 view->close = close_log_view;
3855 view->search_start = search_start_log_view;
3856 view->search_next = search_next_log_view;
3858 if (s->thread_args.pack_fds == NULL) {
3859 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3860 if (err)
3861 goto done;
3863 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3864 s->thread_args.pack_fds);
3865 if (err)
3866 goto done;
3867 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3868 !s->log_branches);
3869 if (err)
3870 goto done;
3871 err = got_commit_graph_bfsort(thread_graph, s->start_id,
3872 s->repo, NULL, NULL);
3873 if (err)
3874 goto done;
3876 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3877 if (errcode) {
3878 err = got_error_set_errno(errcode, "pthread_cond_init");
3879 goto done;
3881 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3882 if (errcode) {
3883 err = got_error_set_errno(errcode, "pthread_cond_init");
3884 goto done;
3887 if (using_mock_io) {
3888 int rc;
3890 rc = pthread_cond_init(&s->thread_args.log_loaded, NULL);
3891 if (rc)
3892 return got_error_set_errno(rc, "pthread_cond_init");
3895 s->thread_args.commits_needed = view->nlines;
3896 s->thread_args.graph = thread_graph;
3897 s->thread_args.real_commits = &s->real_commits;
3898 s->thread_args.limit_commits = &s->limit_commits;
3899 s->thread_args.in_repo_path = s->in_repo_path;
3900 s->thread_args.start_id = s->start_id;
3901 s->thread_args.repo = thread_repo;
3902 s->thread_args.log_complete = 0;
3903 s->thread_args.quit = &s->quit;
3904 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3905 s->thread_args.selected_entry = &s->selected_entry;
3906 s->thread_args.searching = &view->searching;
3907 s->thread_args.search_next_done = &view->search_next_done;
3908 s->thread_args.regex = &view->regex;
3909 s->thread_args.limiting = &s->limit_view;
3910 s->thread_args.limit_regex = &s->limit_regex;
3911 s->thread_args.limit_commits = &s->limit_commits;
3912 s->thread_args.worktree = worktree;
3913 if (worktree)
3914 s->thread_args.need_commit_marker = 1;
3915 done:
3916 if (err) {
3917 if (view->close == NULL)
3918 close_log_view(view);
3919 view_close(view);
3921 return err;
3924 static const struct got_error *
3925 show_log_view(struct tog_view *view)
3927 const struct got_error *err;
3928 struct tog_log_view_state *s = &view->state.log;
3930 if (s->thread == 0) { //NULL) {
3931 int errcode = pthread_create(&s->thread, NULL, log_thread,
3932 &s->thread_args);
3933 if (errcode)
3934 return got_error_set_errno(errcode, "pthread_create");
3935 if (s->thread_args.commits_needed > 0) {
3936 err = trigger_log_thread(view, 1);
3937 if (err)
3938 return err;
3942 return draw_commits(view);
3945 static void
3946 log_move_cursor_up(struct tog_view *view, int page, int home)
3948 struct tog_log_view_state *s = &view->state.log;
3950 if (s->first_displayed_entry == NULL)
3951 return;
3952 if (s->selected_entry->idx == 0)
3953 view->count = 0;
3955 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3956 || home)
3957 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3959 if (!page && !home && s->selected > 0)
3960 --s->selected;
3961 else
3962 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3964 select_commit(s);
3965 return;
3968 static const struct got_error *
3969 log_move_cursor_down(struct tog_view *view, int page)
3971 struct tog_log_view_state *s = &view->state.log;
3972 const struct got_error *err = NULL;
3973 int eos = view->nlines - 2;
3975 if (s->first_displayed_entry == NULL)
3976 return NULL;
3978 if (s->thread_args.log_complete &&
3979 s->selected_entry->idx >= s->commits->ncommits - 1)
3980 return NULL;
3982 if (view_is_hsplit_top(view))
3983 --eos; /* border consumes the last line */
3985 if (!page) {
3986 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3987 ++s->selected;
3988 else
3989 err = log_scroll_down(view, 1);
3990 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3991 struct commit_queue_entry *entry;
3992 int n;
3994 s->selected = 0;
3995 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3996 s->last_displayed_entry = entry;
3997 for (n = 0; n <= eos; n++) {
3998 if (entry == NULL)
3999 break;
4000 s->first_displayed_entry = entry;
4001 entry = TAILQ_PREV(entry, commit_queue_head, entry);
4003 if (n > 0)
4004 s->selected = n - 1;
4005 } else {
4006 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
4007 s->thread_args.log_complete)
4008 s->selected += MIN(page,
4009 s->commits->ncommits - s->selected_entry->idx - 1);
4010 else
4011 err = log_scroll_down(view, page);
4013 if (err)
4014 return err;
4017 * We might necessarily overshoot in horizontal
4018 * splits; if so, select the last displayed commit.
4020 if (s->first_displayed_entry && s->last_displayed_entry) {
4021 s->selected = MIN(s->selected,
4022 s->last_displayed_entry->idx -
4023 s->first_displayed_entry->idx);
4026 select_commit(s);
4028 if (s->thread_args.log_complete &&
4029 s->selected_entry->idx == s->commits->ncommits - 1)
4030 view->count = 0;
4032 return NULL;
4035 static void
4036 view_get_split(struct tog_view *view, int *y, int *x)
4038 *x = 0;
4039 *y = 0;
4041 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
4042 if (view->child && view->child->resized_y)
4043 *y = view->child->resized_y;
4044 else if (view->resized_y)
4045 *y = view->resized_y;
4046 else
4047 *y = view_split_begin_y(view->lines);
4048 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
4049 if (view->child && view->child->resized_x)
4050 *x = view->child->resized_x;
4051 else if (view->resized_x)
4052 *x = view->resized_x;
4053 else
4054 *x = view_split_begin_x(view->begin_x);
4058 /* Split view horizontally at y and offset view->state->selected line. */
4059 static const struct got_error *
4060 view_init_hsplit(struct tog_view *view, int y)
4062 const struct got_error *err = NULL;
4064 view->nlines = y;
4065 view->ncols = COLS;
4066 err = view_resize(view);
4067 if (err)
4068 return err;
4070 err = offset_selection_down(view);
4072 return err;
4075 static const struct got_error *
4076 log_goto_line(struct tog_view *view, int nlines)
4078 const struct got_error *err = NULL;
4079 struct tog_log_view_state *s = &view->state.log;
4080 int g, idx = s->selected_entry->idx;
4082 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
4083 return NULL;
4085 g = view->gline;
4086 view->gline = 0;
4088 if (g >= s->first_displayed_entry->idx + 1 &&
4089 g <= s->last_displayed_entry->idx + 1 &&
4090 g - s->first_displayed_entry->idx - 1 < nlines) {
4091 s->selected = g - s->first_displayed_entry->idx - 1;
4092 select_commit(s);
4093 return NULL;
4096 if (idx + 1 < g) {
4097 err = log_move_cursor_down(view, g - idx - 1);
4098 if (!err && g > s->selected_entry->idx + 1)
4099 err = log_move_cursor_down(view,
4100 g - s->first_displayed_entry->idx - 1);
4101 if (err)
4102 return err;
4103 } else if (idx + 1 > g)
4104 log_move_cursor_up(view, idx - g + 1, 0);
4106 if (g < nlines && s->first_displayed_entry->idx == 0)
4107 s->selected = g - 1;
4109 select_commit(s);
4110 return NULL;
4114 static void
4115 horizontal_scroll_input(struct tog_view *view, int ch)
4118 switch (ch) {
4119 case KEY_LEFT:
4120 case 'h':
4121 view->x -= MIN(view->x, 2);
4122 if (view->x <= 0)
4123 view->count = 0;
4124 break;
4125 case KEY_RIGHT:
4126 case 'l':
4127 if (view->x + view->ncols / 2 < view->maxx)
4128 view->x += 2;
4129 else
4130 view->count = 0;
4131 break;
4132 case '0':
4133 view->x = 0;
4134 break;
4135 case '$':
4136 view->x = MAX(view->maxx - view->ncols / 2, 0);
4137 view->count = 0;
4138 break;
4139 default:
4140 break;
4144 static const struct got_error *
4145 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
4147 const struct got_error *err = NULL;
4148 struct tog_log_view_state *s = &view->state.log;
4149 int eos, nscroll;
4151 if (s->thread_args.load_all) {
4152 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
4153 s->thread_args.load_all = 0;
4154 else if (s->thread_args.log_complete) {
4155 err = log_move_cursor_down(view, s->commits->ncommits);
4156 s->thread_args.load_all = 0;
4158 if (err)
4159 return err;
4162 eos = nscroll = view->nlines - 1;
4163 if (view_is_hsplit_top(view))
4164 --eos; /* border */
4166 if (view->gline)
4167 return log_goto_line(view, eos);
4169 switch (ch) {
4170 case '&':
4171 err = limit_log_view(view);
4172 break;
4173 case 'q':
4174 s->quit = 1;
4175 break;
4176 case '0':
4177 case '$':
4178 case KEY_RIGHT:
4179 case 'l':
4180 case KEY_LEFT:
4181 case 'h':
4182 horizontal_scroll_input(view, ch);
4183 break;
4184 case 'k':
4185 case KEY_UP:
4186 case '<':
4187 case ',':
4188 case CTRL('p'):
4189 log_move_cursor_up(view, 0, 0);
4190 break;
4191 case 'g':
4192 case '=':
4193 case KEY_HOME:
4194 log_move_cursor_up(view, 0, 1);
4195 view->count = 0;
4196 break;
4197 case CTRL('u'):
4198 case 'u':
4199 nscroll /= 2;
4200 /* FALL THROUGH */
4201 case KEY_PPAGE:
4202 case CTRL('b'):
4203 case 'b':
4204 log_move_cursor_up(view, nscroll, 0);
4205 break;
4206 case 'j':
4207 case KEY_DOWN:
4208 case '>':
4209 case '.':
4210 case CTRL('n'):
4211 err = log_move_cursor_down(view, 0);
4212 break;
4213 case '@':
4214 s->use_committer = !s->use_committer;
4215 view->action = s->use_committer ?
4216 "show committer" : "show commit author";
4217 break;
4218 case 'G':
4219 case '*':
4220 case KEY_END: {
4221 /* We don't know yet how many commits, so we're forced to
4222 * traverse them all. */
4223 view->count = 0;
4224 s->thread_args.load_all = 1;
4225 if (!s->thread_args.log_complete)
4226 return trigger_log_thread(view, 0);
4227 err = log_move_cursor_down(view, s->commits->ncommits);
4228 s->thread_args.load_all = 0;
4229 break;
4231 case CTRL('d'):
4232 case 'd':
4233 nscroll /= 2;
4234 /* FALL THROUGH */
4235 case KEY_NPAGE:
4236 case CTRL('f'):
4237 case 'f':
4238 case ' ':
4239 err = log_move_cursor_down(view, nscroll);
4240 break;
4241 case KEY_RESIZE:
4242 if (s->selected > view->nlines - 2)
4243 s->selected = view->nlines - 2;
4244 if (s->selected > s->commits->ncommits - 1)
4245 s->selected = s->commits->ncommits - 1;
4246 select_commit(s);
4247 if (s->commits->ncommits < view->nlines - 1 &&
4248 !s->thread_args.log_complete) {
4249 s->thread_args.commits_needed += (view->nlines - 1) -
4250 s->commits->ncommits;
4251 err = trigger_log_thread(view, 1);
4253 break;
4254 case KEY_ENTER:
4255 case '\r':
4256 view->count = 0;
4257 if (s->selected_entry == NULL)
4258 break;
4259 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4260 break;
4261 case 'T':
4262 view->count = 0;
4263 if (s->selected_entry == NULL)
4264 break;
4265 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4266 break;
4267 case KEY_BACKSPACE:
4268 case CTRL('l'):
4269 case 'B':
4270 view->count = 0;
4271 if (ch == KEY_BACKSPACE &&
4272 got_path_is_root_dir(s->in_repo_path))
4273 break;
4274 err = stop_log_thread(s);
4275 if (err)
4276 return err;
4277 if (ch == KEY_BACKSPACE) {
4278 char *parent_path;
4279 err = got_path_dirname(&parent_path, s->in_repo_path);
4280 if (err)
4281 return err;
4282 free(s->in_repo_path);
4283 s->in_repo_path = parent_path;
4284 s->thread_args.in_repo_path = s->in_repo_path;
4285 } else if (ch == CTRL('l')) {
4286 struct got_object_id *start_id;
4287 err = got_repo_match_object_id(&start_id, NULL,
4288 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4289 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4290 if (err) {
4291 if (s->head_ref_name == NULL ||
4292 err->code != GOT_ERR_NOT_REF)
4293 return err;
4294 /* Try to cope with deleted references. */
4295 free(s->head_ref_name);
4296 s->head_ref_name = NULL;
4297 err = got_repo_match_object_id(&start_id,
4298 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4299 &tog_refs, s->repo);
4300 if (err)
4301 return err;
4303 free(s->start_id);
4304 s->start_id = start_id;
4305 s->thread_args.start_id = s->start_id;
4306 } else /* 'B' */
4307 s->log_branches = !s->log_branches;
4309 if (s->thread_args.pack_fds == NULL) {
4310 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4311 if (err)
4312 return err;
4314 err = got_repo_open(&s->thread_args.repo,
4315 got_repo_get_path(s->repo), NULL,
4316 s->thread_args.pack_fds);
4317 if (err)
4318 return err;
4319 tog_free_refs();
4320 err = tog_load_refs(s->repo, 0);
4321 if (err)
4322 return err;
4323 err = got_commit_graph_open(&s->thread_args.graph,
4324 s->in_repo_path, !s->log_branches);
4325 if (err)
4326 return err;
4327 err = got_commit_graph_bfsort(s->thread_args.graph,
4328 s->start_id, s->repo, NULL, NULL);
4329 if (err)
4330 return err;
4331 free_commits(&s->real_commits);
4332 free_commits(&s->limit_commits);
4333 s->first_displayed_entry = NULL;
4334 s->last_displayed_entry = NULL;
4335 s->selected_entry = NULL;
4336 s->selected = 0;
4337 s->thread_args.log_complete = 0;
4338 s->quit = 0;
4339 s->thread_args.commits_needed = view->lines;
4340 s->matched_entry = NULL;
4341 s->search_entry = NULL;
4342 view->offset = 0;
4343 break;
4344 case 'R':
4345 view->count = 0;
4346 err = view_request_new(new_view, view, TOG_VIEW_REF);
4347 break;
4348 default:
4349 view->count = 0;
4350 break;
4353 return err;
4356 static const struct got_error *
4357 apply_unveil(const char *repo_path, const char *worktree_path)
4359 const struct got_error *error;
4361 #ifdef PROFILE
4362 if (unveil("gmon.out", "rwc") != 0)
4363 return got_error_from_errno2("unveil", "gmon.out");
4364 #endif
4365 if (repo_path && unveil(repo_path, "r") != 0)
4366 return got_error_from_errno2("unveil", repo_path);
4368 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4369 return got_error_from_errno2("unveil", worktree_path);
4371 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4372 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4374 error = got_privsep_unveil_exec_helpers();
4375 if (error != NULL)
4376 return error;
4378 if (unveil(NULL, NULL) != 0)
4379 return got_error_from_errno("unveil");
4381 return NULL;
4384 static const struct got_error *
4385 init_mock_term(const char *test_script_path)
4387 const struct got_error *err = NULL;
4388 const char *screen_dump_path;
4389 int in;
4391 if (test_script_path == NULL || *test_script_path == '\0')
4392 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4394 tog_io.f = fopen(test_script_path, "re");
4395 if (tog_io.f == NULL) {
4396 err = got_error_from_errno_fmt("fopen: %s",
4397 test_script_path);
4398 goto done;
4401 /* test mode, we don't want any output */
4402 tog_io.cout = fopen("/dev/null", "w+");
4403 if (tog_io.cout == NULL) {
4404 err = got_error_from_errno2("fopen", "/dev/null");
4405 goto done;
4408 in = dup(fileno(tog_io.cout));
4409 if (in == -1) {
4410 err = got_error_from_errno("dup");
4411 goto done;
4413 tog_io.cin = fdopen(in, "r");
4414 if (tog_io.cin == NULL) {
4415 err = got_error_from_errno("fdopen");
4416 close(in);
4417 goto done;
4420 screen_dump_path = getenv("TOG_SCR_DUMP");
4421 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4422 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4423 tog_io.sdump = fopen(screen_dump_path, "we");
4424 if (tog_io.sdump == NULL) {
4425 err = got_error_from_errno2("fopen", screen_dump_path);
4426 goto done;
4429 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4430 err = got_error_from_errno("fseeko");
4431 goto done;
4434 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4435 err = got_error_msg(GOT_ERR_IO,
4436 "newterm: failed to initialise curses");
4438 using_mock_io = 1;
4440 done:
4441 if (err)
4442 tog_io_close();
4443 return err;
4446 static void
4447 init_curses(void)
4449 if (using_mock_io) /* In test mode we use a fake terminal */
4450 return;
4452 initscr();
4454 cbreak();
4455 halfdelay(1); /* Fast refresh while initial view is loading. */
4456 noecho();
4457 nonl();
4458 intrflush(stdscr, FALSE);
4459 keypad(stdscr, TRUE);
4460 curs_set(0);
4461 if (getenv("TOG_COLORS") != NULL) {
4462 start_color();
4463 use_default_colors();
4466 return;
4469 static const struct got_error *
4470 set_tog_base_commit(struct got_repository *repo, struct got_worktree *worktree)
4472 tog_base_commit.id = got_object_id_dup(
4473 got_worktree_get_base_commit_id(worktree));
4474 if (tog_base_commit.id == NULL)
4475 return got_error_from_errno( "got_object_id_dup");
4477 return NULL;
4480 static const struct got_error *
4481 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4482 struct got_repository *repo, struct got_worktree *worktree)
4484 const struct got_error *err = NULL;
4486 if (argc == 0) {
4487 *in_repo_path = strdup("/");
4488 if (*in_repo_path == NULL)
4489 return got_error_from_errno("strdup");
4490 return NULL;
4493 if (worktree) {
4494 const char *prefix = got_worktree_get_path_prefix(worktree);
4495 char *p;
4497 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4498 if (err)
4499 return err;
4500 if (asprintf(in_repo_path, "%s%s%s", prefix,
4501 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4502 p) == -1) {
4503 err = got_error_from_errno("asprintf");
4504 *in_repo_path = NULL;
4506 free(p);
4507 } else
4508 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4510 return err;
4513 static const struct got_error *
4514 cmd_log(int argc, char *argv[])
4516 const struct got_error *error;
4517 struct got_repository *repo = NULL;
4518 struct got_worktree *worktree = NULL;
4519 struct got_object_id *start_id = NULL;
4520 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4521 char *keyword_idstr = NULL, *start_commit = NULL, *label = NULL;
4522 struct got_reference *ref = NULL;
4523 const char *head_ref_name = NULL;
4524 int ch, log_branches = 0;
4525 struct tog_view *view;
4526 int *pack_fds = NULL;
4528 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4529 switch (ch) {
4530 case 'b':
4531 log_branches = 1;
4532 break;
4533 case 'c':
4534 start_commit = optarg;
4535 break;
4536 case 'r':
4537 repo_path = realpath(optarg, NULL);
4538 if (repo_path == NULL)
4539 return got_error_from_errno2("realpath",
4540 optarg);
4541 break;
4542 default:
4543 usage_log();
4544 /* NOTREACHED */
4548 argc -= optind;
4549 argv += optind;
4551 if (argc > 1)
4552 usage_log();
4554 error = got_repo_pack_fds_open(&pack_fds);
4555 if (error != NULL)
4556 goto done;
4558 if (repo_path == NULL) {
4559 cwd = getcwd(NULL, 0);
4560 if (cwd == NULL) {
4561 error = got_error_from_errno("getcwd");
4562 goto done;
4564 error = got_worktree_open(&worktree, cwd, NULL);
4565 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4566 goto done;
4567 if (worktree)
4568 repo_path =
4569 strdup(got_worktree_get_repo_path(worktree));
4570 else
4571 repo_path = strdup(cwd);
4572 if (repo_path == NULL) {
4573 error = got_error_from_errno("strdup");
4574 goto done;
4578 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4579 if (error != NULL)
4580 goto done;
4582 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4583 repo, worktree);
4584 if (error)
4585 goto done;
4587 init_curses();
4589 error = apply_unveil(got_repo_get_path(repo),
4590 worktree ? got_worktree_get_root_path(worktree) : NULL);
4591 if (error)
4592 goto done;
4594 /* already loaded by tog_log_with_path()? */
4595 if (TAILQ_EMPTY(&tog_refs)) {
4596 error = tog_load_refs(repo, 0);
4597 if (error)
4598 goto done;
4601 if (start_commit == NULL) {
4602 error = got_repo_match_object_id(&start_id, &label,
4603 worktree ? got_worktree_get_head_ref_name(worktree) :
4604 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4605 if (error)
4606 goto done;
4607 head_ref_name = label;
4608 } else {
4609 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4610 repo, worktree);
4611 if (error != NULL)
4612 goto done;
4613 if (keyword_idstr != NULL)
4614 start_commit = keyword_idstr;
4616 error = got_ref_open(&ref, repo, start_commit, 0);
4617 if (error == NULL)
4618 head_ref_name = got_ref_get_name(ref);
4619 else if (error->code != GOT_ERR_NOT_REF)
4620 goto done;
4621 error = got_repo_match_object_id(&start_id, NULL,
4622 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4623 if (error)
4624 goto done;
4627 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4628 if (view == NULL) {
4629 error = got_error_from_errno("view_open");
4630 goto done;
4633 if (worktree) {
4634 error = set_tog_base_commit(repo, worktree);
4635 if (error != NULL)
4636 goto done;
4639 error = open_log_view(view, start_id, repo, head_ref_name,
4640 in_repo_path, log_branches, worktree);
4641 if (error)
4642 goto done;
4644 if (worktree) {
4645 /* The work tree will be closed by the log thread. */
4646 worktree = NULL;
4649 error = view_loop(view);
4651 done:
4652 free(tog_base_commit.id);
4653 free(keyword_idstr);
4654 free(in_repo_path);
4655 free(repo_path);
4656 free(cwd);
4657 free(start_id);
4658 free(label);
4659 if (ref)
4660 got_ref_close(ref);
4661 if (repo) {
4662 const struct got_error *close_err = got_repo_close(repo);
4663 if (error == NULL)
4664 error = close_err;
4666 if (worktree)
4667 got_worktree_close(worktree);
4668 if (pack_fds) {
4669 const struct got_error *pack_err =
4670 got_repo_pack_fds_close(pack_fds);
4671 if (error == NULL)
4672 error = pack_err;
4674 tog_free_refs();
4675 return error;
4678 __dead static void
4679 usage_diff(void)
4681 endwin();
4682 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4683 "object1 object2\n", getprogname());
4684 exit(1);
4687 static int
4688 match_line(const char *line, regex_t *regex, size_t nmatch,
4689 regmatch_t *regmatch)
4691 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4694 static struct tog_color *
4695 match_color(struct tog_colors *colors, const char *line)
4697 struct tog_color *tc = NULL;
4699 STAILQ_FOREACH(tc, colors, entry) {
4700 if (match_line(line, &tc->regex, 0, NULL))
4701 return tc;
4704 return NULL;
4707 static const struct got_error *
4708 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4709 WINDOW *window, int skipcol, regmatch_t *regmatch)
4711 const struct got_error *err = NULL;
4712 char *exstr = NULL;
4713 wchar_t *wline = NULL;
4714 int rme, rms, n, width, scrollx;
4715 int width0 = 0, width1 = 0, width2 = 0;
4716 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4718 *wtotal = 0;
4720 rms = regmatch->rm_so;
4721 rme = regmatch->rm_eo;
4723 err = expand_tab(&exstr, line);
4724 if (err)
4725 return err;
4727 /* Split the line into 3 segments, according to match offsets. */
4728 seg0 = strndup(exstr, rms);
4729 if (seg0 == NULL) {
4730 err = got_error_from_errno("strndup");
4731 goto done;
4733 seg1 = strndup(exstr + rms, rme - rms);
4734 if (seg1 == NULL) {
4735 err = got_error_from_errno("strndup");
4736 goto done;
4738 seg2 = strdup(exstr + rme);
4739 if (seg2 == NULL) {
4740 err = got_error_from_errno("strndup");
4741 goto done;
4744 /* draw up to matched token if we haven't scrolled past it */
4745 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4746 col_tab_align, 1);
4747 if (err)
4748 goto done;
4749 n = MAX(width0 - skipcol, 0);
4750 if (n) {
4751 free(wline);
4752 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4753 wlimit, col_tab_align, 1);
4754 if (err)
4755 goto done;
4756 waddwstr(window, &wline[scrollx]);
4757 wlimit -= width;
4758 *wtotal += width;
4761 if (wlimit > 0) {
4762 int i = 0, w = 0;
4763 size_t wlen;
4765 free(wline);
4766 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4767 col_tab_align, 1);
4768 if (err)
4769 goto done;
4770 wlen = wcslen(wline);
4771 while (i < wlen) {
4772 width = wcwidth(wline[i]);
4773 if (width == -1) {
4774 /* should not happen, tabs are expanded */
4775 err = got_error(GOT_ERR_RANGE);
4776 goto done;
4778 if (width0 + w + width > skipcol)
4779 break;
4780 w += width;
4781 i++;
4783 /* draw (visible part of) matched token (if scrolled into it) */
4784 if (width1 - w > 0) {
4785 wattron(window, A_STANDOUT);
4786 waddwstr(window, &wline[i]);
4787 wattroff(window, A_STANDOUT);
4788 wlimit -= (width1 - w);
4789 *wtotal += (width1 - w);
4793 if (wlimit > 0) { /* draw rest of line */
4794 free(wline);
4795 if (skipcol > width0 + width1) {
4796 err = format_line(&wline, &width2, &scrollx, seg2,
4797 skipcol - (width0 + width1), wlimit,
4798 col_tab_align, 1);
4799 if (err)
4800 goto done;
4801 waddwstr(window, &wline[scrollx]);
4802 } else {
4803 err = format_line(&wline, &width2, NULL, seg2, 0,
4804 wlimit, col_tab_align, 1);
4805 if (err)
4806 goto done;
4807 waddwstr(window, wline);
4809 *wtotal += width2;
4811 done:
4812 free(wline);
4813 free(exstr);
4814 free(seg0);
4815 free(seg1);
4816 free(seg2);
4817 return err;
4820 static int
4821 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4823 FILE *f = NULL;
4824 int *eof, *first, *selected;
4826 if (view->type == TOG_VIEW_DIFF) {
4827 struct tog_diff_view_state *s = &view->state.diff;
4829 first = &s->first_displayed_line;
4830 selected = first;
4831 eof = &s->eof;
4832 f = s->f;
4833 } else if (view->type == TOG_VIEW_HELP) {
4834 struct tog_help_view_state *s = &view->state.help;
4836 first = &s->first_displayed_line;
4837 selected = first;
4838 eof = &s->eof;
4839 f = s->f;
4840 } else if (view->type == TOG_VIEW_BLAME) {
4841 struct tog_blame_view_state *s = &view->state.blame;
4843 first = &s->first_displayed_line;
4844 selected = &s->selected_line;
4845 eof = &s->eof;
4846 f = s->blame.f;
4847 } else
4848 return 0;
4850 /* Center gline in the middle of the page like vi(1). */
4851 if (*lineno < view->gline - (view->nlines - 3) / 2)
4852 return 0;
4853 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4854 rewind(f);
4855 *eof = 0;
4856 *first = 1;
4857 *lineno = 0;
4858 *nprinted = 0;
4859 return 0;
4862 *selected = view->gline <= (view->nlines - 3) / 2 ?
4863 view->gline : (view->nlines - 3) / 2 + 1;
4864 view->gline = 0;
4866 return 1;
4869 static const struct got_error *
4870 draw_file(struct tog_view *view, const char *header)
4872 struct tog_diff_view_state *s = &view->state.diff;
4873 regmatch_t *regmatch = &view->regmatch;
4874 const struct got_error *err;
4875 int nprinted = 0;
4876 char *line;
4877 size_t linesize = 0;
4878 ssize_t linelen;
4879 wchar_t *wline;
4880 int width;
4881 int max_lines = view->nlines;
4882 int nlines = s->nlines;
4883 off_t line_offset;
4885 s->lineno = s->first_displayed_line - 1;
4886 line_offset = s->lines[s->first_displayed_line - 1].offset;
4887 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4888 return got_error_from_errno("fseek");
4890 werase(view->window);
4892 if (view->gline > s->nlines - 1)
4893 view->gline = s->nlines - 1;
4895 if (header) {
4896 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4897 1 : view->gline - (view->nlines - 3) / 2 :
4898 s->lineno + s->selected_line;
4900 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4901 return got_error_from_errno("asprintf");
4902 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4903 0, 0);
4904 free(line);
4905 if (err)
4906 return err;
4908 if (view_needs_focus_indication(view))
4909 wstandout(view->window);
4910 waddwstr(view->window, wline);
4911 free(wline);
4912 wline = NULL;
4913 while (width++ < view->ncols)
4914 waddch(view->window, ' ');
4915 if (view_needs_focus_indication(view))
4916 wstandend(view->window);
4918 if (max_lines <= 1)
4919 return NULL;
4920 max_lines--;
4923 s->eof = 0;
4924 view->maxx = 0;
4925 line = NULL;
4926 while (max_lines > 0 && nprinted < max_lines) {
4927 enum got_diff_line_type linetype;
4928 attr_t attr = 0;
4930 linelen = getline(&line, &linesize, s->f);
4931 if (linelen == -1) {
4932 if (feof(s->f)) {
4933 s->eof = 1;
4934 break;
4936 free(line);
4937 return got_ferror(s->f, GOT_ERR_IO);
4940 if (++s->lineno < s->first_displayed_line)
4941 continue;
4942 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4943 continue;
4944 if (s->lineno == view->hiline)
4945 attr = A_STANDOUT;
4947 /* Set view->maxx based on full line length. */
4948 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4949 view->x ? 1 : 0);
4950 if (err) {
4951 free(line);
4952 return err;
4954 view->maxx = MAX(view->maxx, width);
4955 free(wline);
4956 wline = NULL;
4958 linetype = s->lines[s->lineno].type;
4959 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4960 linetype < GOT_DIFF_LINE_CONTEXT)
4961 attr |= COLOR_PAIR(linetype);
4962 if (attr)
4963 wattron(view->window, attr);
4964 if (s->first_displayed_line + nprinted == s->matched_line &&
4965 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4966 err = add_matched_line(&width, line, view->ncols, 0,
4967 view->window, view->x, regmatch);
4968 if (err) {
4969 free(line);
4970 return err;
4972 } else {
4973 int skip;
4974 err = format_line(&wline, &width, &skip, line,
4975 view->x, view->ncols, 0, view->x ? 1 : 0);
4976 if (err) {
4977 free(line);
4978 return err;
4980 waddwstr(view->window, &wline[skip]);
4981 free(wline);
4982 wline = NULL;
4984 if (s->lineno == view->hiline) {
4985 /* highlight full gline length */
4986 while (width++ < view->ncols)
4987 waddch(view->window, ' ');
4988 } else {
4989 if (width <= view->ncols - 1)
4990 waddch(view->window, '\n');
4992 if (attr)
4993 wattroff(view->window, attr);
4994 if (++nprinted == 1)
4995 s->first_displayed_line = s->lineno;
4997 free(line);
4998 if (nprinted >= 1)
4999 s->last_displayed_line = s->first_displayed_line +
5000 (nprinted - 1);
5001 else
5002 s->last_displayed_line = s->first_displayed_line;
5004 view_border(view);
5006 if (s->eof) {
5007 while (nprinted < view->nlines) {
5008 waddch(view->window, '\n');
5009 nprinted++;
5012 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
5013 view->ncols, 0, 0);
5014 if (err) {
5015 return err;
5018 wstandout(view->window);
5019 waddwstr(view->window, wline);
5020 free(wline);
5021 wline = NULL;
5022 wstandend(view->window);
5025 return NULL;
5028 static char *
5029 get_datestr(time_t *time, char *datebuf)
5031 struct tm mytm, *tm;
5032 char *p, *s;
5034 tm = gmtime_r(time, &mytm);
5035 if (tm == NULL)
5036 return NULL;
5037 s = asctime_r(tm, datebuf);
5038 if (s == NULL)
5039 return NULL;
5040 p = strchr(s, '\n');
5041 if (p)
5042 *p = '\0';
5043 return s;
5046 static const struct got_error *
5047 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
5048 off_t off, uint8_t type)
5050 struct got_diff_line *p;
5052 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
5053 if (p == NULL)
5054 return got_error_from_errno("reallocarray");
5055 *lines = p;
5056 (*lines)[*nlines].offset = off;
5057 (*lines)[*nlines].type = type;
5058 (*nlines)++;
5060 return NULL;
5063 static const struct got_error *
5064 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
5065 struct got_diff_line *s_lines, size_t s_nlines)
5067 struct got_diff_line *p;
5068 char buf[BUFSIZ];
5069 size_t i, r;
5071 if (fseeko(src, 0L, SEEK_SET) == -1)
5072 return got_error_from_errno("fseeko");
5074 for (;;) {
5075 r = fread(buf, 1, sizeof(buf), src);
5076 if (r == 0) {
5077 if (ferror(src))
5078 return got_error_from_errno("fread");
5079 if (feof(src))
5080 break;
5082 if (fwrite(buf, 1, r, dst) != r)
5083 return got_ferror(dst, GOT_ERR_IO);
5086 if (s_nlines == 0 && *d_nlines == 0)
5087 return NULL;
5090 * If commit info was in dst, increment line offsets
5091 * of the appended diff content, but skip s_lines[0]
5092 * because offset zero is already in *d_lines.
5094 if (*d_nlines > 0) {
5095 for (i = 1; i < s_nlines; ++i)
5096 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
5098 if (s_nlines > 0) {
5099 --s_nlines;
5100 ++s_lines;
5104 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
5105 if (p == NULL) {
5106 /* d_lines is freed in close_diff_view() */
5107 return got_error_from_errno("reallocarray");
5110 *d_lines = p;
5112 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
5113 *d_nlines += s_nlines;
5115 return NULL;
5118 static const struct got_error *
5119 write_commit_info(struct got_diff_line **lines, size_t *nlines,
5120 struct got_object_id *commit_id, struct got_reflist_head *refs,
5121 struct got_repository *repo, int ignore_ws, int force_text_diff,
5122 struct got_diffstat_cb_arg *dsa, FILE *outfile)
5124 const struct got_error *err = NULL;
5125 char datebuf[26], *datestr;
5126 struct got_commit_object *commit;
5127 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
5128 time_t committer_time;
5129 const char *author, *committer;
5130 char *refs_str = NULL;
5131 struct got_pathlist_entry *pe;
5132 off_t outoff = 0;
5133 int n;
5135 err = build_refs_str(&refs_str, refs, commit_id, repo);
5136 if (err)
5137 return err;
5139 err = got_object_open_as_commit(&commit, repo, commit_id);
5140 if (err)
5141 return err;
5143 err = got_object_id_str(&id_str, commit_id);
5144 if (err) {
5145 err = got_error_from_errno("got_object_id_str");
5146 goto done;
5149 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
5150 if (err)
5151 goto done;
5153 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
5154 refs_str ? refs_str : "", refs_str ? ")" : "");
5155 if (n < 0) {
5156 err = got_error_from_errno("fprintf");
5157 goto done;
5159 outoff += n;
5160 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
5161 if (err)
5162 goto done;
5164 n = fprintf(outfile, "from: %s\n",
5165 got_object_commit_get_author(commit));
5166 if (n < 0) {
5167 err = got_error_from_errno("fprintf");
5168 goto done;
5170 outoff += n;
5171 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
5172 if (err)
5173 goto done;
5175 author = got_object_commit_get_author(commit);
5176 committer = got_object_commit_get_committer(commit);
5177 if (strcmp(author, committer) != 0) {
5178 n = fprintf(outfile, "via: %s\n", committer);
5179 if (n < 0) {
5180 err = got_error_from_errno("fprintf");
5181 goto done;
5183 outoff += n;
5184 err = add_line_metadata(lines, nlines, outoff,
5185 GOT_DIFF_LINE_AUTHOR);
5186 if (err)
5187 goto done;
5189 committer_time = got_object_commit_get_committer_time(commit);
5190 datestr = get_datestr(&committer_time, datebuf);
5191 if (datestr) {
5192 n = fprintf(outfile, "date: %s UTC\n", datestr);
5193 if (n < 0) {
5194 err = got_error_from_errno("fprintf");
5195 goto done;
5197 outoff += n;
5198 err = add_line_metadata(lines, nlines, outoff,
5199 GOT_DIFF_LINE_DATE);
5200 if (err)
5201 goto done;
5203 if (got_object_commit_get_nparents(commit) > 1) {
5204 const struct got_object_id_queue *parent_ids;
5205 struct got_object_qid *qid;
5206 int pn = 1;
5207 parent_ids = got_object_commit_get_parent_ids(commit);
5208 STAILQ_FOREACH(qid, parent_ids, entry) {
5209 err = got_object_id_str(&id_str, &qid->id);
5210 if (err)
5211 goto done;
5212 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5213 if (n < 0) {
5214 err = got_error_from_errno("fprintf");
5215 goto done;
5217 outoff += n;
5218 err = add_line_metadata(lines, nlines, outoff,
5219 GOT_DIFF_LINE_META);
5220 if (err)
5221 goto done;
5222 free(id_str);
5223 id_str = NULL;
5227 err = got_object_commit_get_logmsg(&logmsg, commit);
5228 if (err)
5229 goto done;
5230 s = logmsg;
5231 while ((line = strsep(&s, "\n")) != NULL) {
5232 n = fprintf(outfile, "%s\n", line);
5233 if (n < 0) {
5234 err = got_error_from_errno("fprintf");
5235 goto done;
5237 outoff += n;
5238 err = add_line_metadata(lines, nlines, outoff,
5239 GOT_DIFF_LINE_LOGMSG);
5240 if (err)
5241 goto done;
5244 TAILQ_FOREACH(pe, dsa->paths, entry) {
5245 struct got_diff_changed_path *cp = pe->data;
5246 int pad = dsa->max_path_len - pe->path_len + 1;
5248 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5249 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5250 dsa->rm_cols + 1, cp->rm);
5251 if (n < 0) {
5252 err = got_error_from_errno("fprintf");
5253 goto done;
5255 outoff += n;
5256 err = add_line_metadata(lines, nlines, outoff,
5257 GOT_DIFF_LINE_CHANGES);
5258 if (err)
5259 goto done;
5262 fputc('\n', outfile);
5263 outoff++;
5264 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5265 if (err)
5266 goto done;
5268 n = fprintf(outfile,
5269 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5270 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5271 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5272 if (n < 0) {
5273 err = got_error_from_errno("fprintf");
5274 goto done;
5276 outoff += n;
5277 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5278 if (err)
5279 goto done;
5281 fputc('\n', outfile);
5282 outoff++;
5283 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5284 done:
5285 free(id_str);
5286 free(logmsg);
5287 free(refs_str);
5288 got_object_commit_close(commit);
5289 if (err) {
5290 free(*lines);
5291 *lines = NULL;
5292 *nlines = 0;
5294 return err;
5297 static const struct got_error *
5298 create_diff(struct tog_diff_view_state *s)
5300 const struct got_error *err = NULL;
5301 FILE *tmp_diff_file = NULL;
5302 int obj_type;
5303 struct got_diff_line *lines = NULL;
5304 struct got_pathlist_head changed_paths;
5305 struct got_commit_object *commit2 = NULL;
5307 TAILQ_INIT(&changed_paths);
5309 free(s->lines);
5310 s->lines = malloc(sizeof(*s->lines));
5311 if (s->lines == NULL)
5312 return got_error_from_errno("malloc");
5313 s->nlines = 0;
5315 if (s->f && fclose(s->f) == EOF) {
5316 s->f = NULL;
5317 return got_error_from_errno("fclose");
5320 s->f = got_opentemp();
5321 if (s->f == NULL)
5322 return got_error_from_errno("got_opentemp");
5324 tmp_diff_file = got_opentemp();
5325 if (tmp_diff_file == NULL)
5326 return got_error_from_errno("got_opentemp");
5328 if (s->id1)
5329 err = got_object_get_type(&obj_type, s->repo, s->id1);
5330 else
5331 err = got_object_get_type(&obj_type, s->repo, s->id2);
5332 if (err)
5333 goto done;
5335 switch (obj_type) {
5336 case GOT_OBJ_TYPE_BLOB:
5337 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5338 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5339 s->label1, s->label2, tog_diff_algo, s->diff_context,
5340 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5341 s->f);
5342 break;
5343 case GOT_OBJ_TYPE_TREE:
5344 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5345 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5346 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5347 s->force_text_diff, NULL, s->repo, s->f);
5348 break;
5349 case GOT_OBJ_TYPE_COMMIT: {
5350 const struct got_object_id_queue *parent_ids;
5351 struct got_object_qid *pid;
5352 struct got_reflist_head *refs;
5353 size_t nlines = 0;
5354 struct got_diffstat_cb_arg dsa = {
5355 0, 0, 0, 0, 0, 0,
5356 &changed_paths,
5357 s->ignore_whitespace,
5358 s->force_text_diff,
5359 tog_diff_algo
5362 lines = malloc(sizeof(*lines));
5363 if (lines == NULL) {
5364 err = got_error_from_errno("malloc");
5365 goto done;
5368 /* build diff first in tmp file then append to commit info */
5369 err = got_diff_objects_as_commits(&lines, &nlines,
5370 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5371 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5372 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5373 if (err)
5374 break;
5376 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5377 /* Show commit info if we're diffing to a parent/root commit. */
5378 if (s->id1 == NULL) {
5379 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5380 refs, s->repo, s->ignore_whitespace,
5381 s->force_text_diff, &dsa, s->f);
5382 if (err)
5383 goto done;
5384 } else {
5385 err = got_object_open_as_commit(&commit2, s->repo,
5386 s->id2);
5387 if (err)
5388 goto done;
5390 parent_ids = got_object_commit_get_parent_ids(commit2);
5391 STAILQ_FOREACH(pid, parent_ids, entry) {
5392 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5393 err = write_commit_info(&s->lines,
5394 &s->nlines, s->id2, refs, s->repo,
5395 s->ignore_whitespace,
5396 s->force_text_diff, &dsa, s->f);
5397 if (err)
5398 goto done;
5399 break;
5404 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5405 lines, nlines);
5406 break;
5408 default:
5409 err = got_error(GOT_ERR_OBJ_TYPE);
5410 break;
5412 done:
5413 free(lines);
5414 if (commit2 != NULL)
5415 got_object_commit_close(commit2);
5416 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5417 if (s->f && fflush(s->f) != 0 && err == NULL)
5418 err = got_error_from_errno("fflush");
5419 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5420 err = got_error_from_errno("fclose");
5421 return err;
5424 static void
5425 diff_view_indicate_progress(struct tog_view *view)
5427 mvwaddstr(view->window, 0, 0, "diffing...");
5428 update_panels();
5429 doupdate();
5432 static const struct got_error *
5433 search_start_diff_view(struct tog_view *view)
5435 struct tog_diff_view_state *s = &view->state.diff;
5437 s->matched_line = 0;
5438 return NULL;
5441 static void
5442 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5443 size_t *nlines, int **first, int **last, int **match, int **selected)
5445 struct tog_diff_view_state *s = &view->state.diff;
5447 *f = s->f;
5448 *nlines = s->nlines;
5449 *line_offsets = NULL;
5450 *match = &s->matched_line;
5451 *first = &s->first_displayed_line;
5452 *last = &s->last_displayed_line;
5453 *selected = &s->selected_line;
5456 static const struct got_error *
5457 search_next_view_match(struct tog_view *view)
5459 const struct got_error *err = NULL;
5460 FILE *f;
5461 int lineno;
5462 char *line = NULL;
5463 size_t linesize = 0;
5464 ssize_t linelen;
5465 off_t *line_offsets;
5466 size_t nlines = 0;
5467 int *first, *last, *match, *selected;
5469 if (!view->search_setup)
5470 return got_error_msg(GOT_ERR_NOT_IMPL,
5471 "view search not supported");
5472 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5473 &match, &selected);
5475 if (!view->searching) {
5476 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5477 return NULL;
5480 if (*match) {
5481 if (view->searching == TOG_SEARCH_FORWARD)
5482 lineno = *first + 1;
5483 else
5484 lineno = *first - 1;
5485 } else
5486 lineno = *first - 1 + *selected;
5488 while (1) {
5489 off_t offset;
5491 if (lineno <= 0 || lineno > nlines) {
5492 if (*match == 0) {
5493 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5494 break;
5497 if (view->searching == TOG_SEARCH_FORWARD)
5498 lineno = 1;
5499 else
5500 lineno = nlines;
5503 offset = view->type == TOG_VIEW_DIFF ?
5504 view->state.diff.lines[lineno - 1].offset :
5505 line_offsets[lineno - 1];
5506 if (fseeko(f, offset, SEEK_SET) != 0) {
5507 free(line);
5508 return got_error_from_errno("fseeko");
5510 linelen = getline(&line, &linesize, f);
5511 if (linelen != -1) {
5512 char *exstr;
5513 err = expand_tab(&exstr, line);
5514 if (err)
5515 break;
5516 if (match_line(exstr, &view->regex, 1,
5517 &view->regmatch)) {
5518 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5519 *match = lineno;
5520 free(exstr);
5521 break;
5523 free(exstr);
5525 if (view->searching == TOG_SEARCH_FORWARD)
5526 lineno++;
5527 else
5528 lineno--;
5530 free(line);
5532 if (*match) {
5533 *first = *match;
5534 *selected = 1;
5537 return err;
5540 static const struct got_error *
5541 close_diff_view(struct tog_view *view)
5543 const struct got_error *err = NULL;
5544 struct tog_diff_view_state *s = &view->state.diff;
5546 free(s->id1);
5547 s->id1 = NULL;
5548 free(s->id2);
5549 s->id2 = NULL;
5550 if (s->f && fclose(s->f) == EOF)
5551 err = got_error_from_errno("fclose");
5552 s->f = NULL;
5553 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5554 err = got_error_from_errno("fclose");
5555 s->f1 = NULL;
5556 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5557 err = got_error_from_errno("fclose");
5558 s->f2 = NULL;
5559 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5560 err = got_error_from_errno("close");
5561 s->fd1 = -1;
5562 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5563 err = got_error_from_errno("close");
5564 s->fd2 = -1;
5565 free(s->lines);
5566 s->lines = NULL;
5567 s->nlines = 0;
5568 return err;
5571 static const struct got_error *
5572 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5573 struct got_object_id *id2, const char *label1, const char *label2,
5574 int diff_context, int ignore_whitespace, int force_text_diff,
5575 struct tog_view *parent_view, struct got_repository *repo)
5577 const struct got_error *err;
5578 struct tog_diff_view_state *s = &view->state.diff;
5580 memset(s, 0, sizeof(*s));
5581 s->fd1 = -1;
5582 s->fd2 = -1;
5584 if (id1 != NULL && id2 != NULL) {
5585 int type1, type2;
5587 err = got_object_get_type(&type1, repo, id1);
5588 if (err)
5589 goto done;
5590 err = got_object_get_type(&type2, repo, id2);
5591 if (err)
5592 goto done;
5594 if (type1 != type2) {
5595 err = got_error(GOT_ERR_OBJ_TYPE);
5596 goto done;
5599 s->first_displayed_line = 1;
5600 s->last_displayed_line = view->nlines;
5601 s->selected_line = 1;
5602 s->repo = repo;
5603 s->label1 = label1;
5604 s->label2 = label2;
5606 if (id1) {
5607 s->id1 = got_object_id_dup(id1);
5608 if (s->id1 == NULL) {
5609 err = got_error_from_errno("got_object_id_dup");
5610 goto done;
5612 } else
5613 s->id1 = NULL;
5615 s->id2 = got_object_id_dup(id2);
5616 if (s->id2 == NULL) {
5617 err = got_error_from_errno("got_object_id_dup");
5618 goto done;
5621 s->f1 = got_opentemp();
5622 if (s->f1 == NULL) {
5623 err = got_error_from_errno("got_opentemp");
5624 goto done;
5627 s->f2 = got_opentemp();
5628 if (s->f2 == NULL) {
5629 err = got_error_from_errno("got_opentemp");
5630 goto done;
5633 s->fd1 = got_opentempfd();
5634 if (s->fd1 == -1) {
5635 err = got_error_from_errno("got_opentempfd");
5636 goto done;
5639 s->fd2 = got_opentempfd();
5640 if (s->fd2 == -1) {
5641 err = got_error_from_errno("got_opentempfd");
5642 goto done;
5645 s->diff_context = diff_context;
5646 s->ignore_whitespace = ignore_whitespace;
5647 s->force_text_diff = force_text_diff;
5648 s->parent_view = parent_view;
5649 s->repo = repo;
5651 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5652 int rc;
5654 rc = init_pair(GOT_DIFF_LINE_MINUS,
5655 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5656 if (rc != ERR)
5657 rc = init_pair(GOT_DIFF_LINE_PLUS,
5658 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5659 if (rc != ERR)
5660 rc = init_pair(GOT_DIFF_LINE_HUNK,
5661 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5662 if (rc != ERR)
5663 rc = init_pair(GOT_DIFF_LINE_META,
5664 get_color_value("TOG_COLOR_DIFF_META"), -1);
5665 if (rc != ERR)
5666 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5667 get_color_value("TOG_COLOR_DIFF_META"), -1);
5668 if (rc != ERR)
5669 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5670 get_color_value("TOG_COLOR_DIFF_META"), -1);
5671 if (rc != ERR)
5672 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5673 get_color_value("TOG_COLOR_DIFF_META"), -1);
5674 if (rc != ERR)
5675 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5676 get_color_value("TOG_COLOR_AUTHOR"), -1);
5677 if (rc != ERR)
5678 rc = init_pair(GOT_DIFF_LINE_DATE,
5679 get_color_value("TOG_COLOR_DATE"), -1);
5680 if (rc == ERR) {
5681 err = got_error(GOT_ERR_RANGE);
5682 goto done;
5686 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5687 view_is_splitscreen(view))
5688 show_log_view(parent_view); /* draw border */
5689 diff_view_indicate_progress(view);
5691 err = create_diff(s);
5693 view->show = show_diff_view;
5694 view->input = input_diff_view;
5695 view->reset = reset_diff_view;
5696 view->close = close_diff_view;
5697 view->search_start = search_start_diff_view;
5698 view->search_setup = search_setup_diff_view;
5699 view->search_next = search_next_view_match;
5700 done:
5701 if (err) {
5702 if (view->close == NULL)
5703 close_diff_view(view);
5704 view_close(view);
5706 return err;
5709 static const struct got_error *
5710 show_diff_view(struct tog_view *view)
5712 const struct got_error *err;
5713 struct tog_diff_view_state *s = &view->state.diff;
5714 char *id_str1 = NULL, *id_str2, *header;
5715 const char *label1, *label2;
5717 if (s->id1) {
5718 err = got_object_id_str(&id_str1, s->id1);
5719 if (err)
5720 return err;
5721 label1 = s->label1 ? s->label1 : id_str1;
5722 } else
5723 label1 = "/dev/null";
5725 err = got_object_id_str(&id_str2, s->id2);
5726 if (err)
5727 return err;
5728 label2 = s->label2 ? s->label2 : id_str2;
5730 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5731 err = got_error_from_errno("asprintf");
5732 free(id_str1);
5733 free(id_str2);
5734 return err;
5736 free(id_str1);
5737 free(id_str2);
5739 err = draw_file(view, header);
5740 free(header);
5741 return err;
5744 static const struct got_error *
5745 set_selected_commit(struct tog_diff_view_state *s,
5746 struct commit_queue_entry *entry)
5748 const struct got_error *err;
5749 const struct got_object_id_queue *parent_ids;
5750 struct got_commit_object *selected_commit;
5751 struct got_object_qid *pid;
5753 free(s->id2);
5754 s->id2 = got_object_id_dup(entry->id);
5755 if (s->id2 == NULL)
5756 return got_error_from_errno("got_object_id_dup");
5758 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5759 if (err)
5760 return err;
5761 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5762 free(s->id1);
5763 pid = STAILQ_FIRST(parent_ids);
5764 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5765 got_object_commit_close(selected_commit);
5766 return NULL;
5769 static const struct got_error *
5770 reset_diff_view(struct tog_view *view)
5772 struct tog_diff_view_state *s = &view->state.diff;
5774 view->count = 0;
5775 wclear(view->window);
5776 s->first_displayed_line = 1;
5777 s->last_displayed_line = view->nlines;
5778 s->matched_line = 0;
5779 diff_view_indicate_progress(view);
5780 return create_diff(s);
5783 static void
5784 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5786 int start, i;
5788 i = start = s->first_displayed_line - 1;
5790 while (s->lines[i].type != type) {
5791 if (i == 0)
5792 i = s->nlines - 1;
5793 if (--i == start)
5794 return; /* do nothing, requested type not in file */
5797 s->selected_line = 1;
5798 s->first_displayed_line = i;
5801 static void
5802 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5804 int start, i;
5806 i = start = s->first_displayed_line + 1;
5808 while (s->lines[i].type != type) {
5809 if (i == s->nlines - 1)
5810 i = 0;
5811 if (++i == start)
5812 return; /* do nothing, requested type not in file */
5815 s->selected_line = 1;
5816 s->first_displayed_line = i;
5819 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5820 int, int, int);
5821 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5822 int, int);
5824 static const struct got_error *
5825 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5827 const struct got_error *err = NULL;
5828 struct tog_diff_view_state *s = &view->state.diff;
5829 struct tog_log_view_state *ls;
5830 struct commit_queue_entry *old_selected_entry;
5831 char *line = NULL;
5832 size_t linesize = 0;
5833 ssize_t linelen;
5834 int i, nscroll = view->nlines - 1, up = 0;
5836 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5838 switch (ch) {
5839 case '0':
5840 case '$':
5841 case KEY_RIGHT:
5842 case 'l':
5843 case KEY_LEFT:
5844 case 'h':
5845 horizontal_scroll_input(view, ch);
5846 break;
5847 case 'a':
5848 case 'w':
5849 if (ch == 'a') {
5850 s->force_text_diff = !s->force_text_diff;
5851 view->action = s->force_text_diff ?
5852 "force ASCII text enabled" :
5853 "force ASCII text disabled";
5855 else if (ch == 'w') {
5856 s->ignore_whitespace = !s->ignore_whitespace;
5857 view->action = s->ignore_whitespace ?
5858 "ignore whitespace enabled" :
5859 "ignore whitespace disabled";
5861 err = reset_diff_view(view);
5862 break;
5863 case 'g':
5864 case KEY_HOME:
5865 s->first_displayed_line = 1;
5866 view->count = 0;
5867 break;
5868 case 'G':
5869 case KEY_END:
5870 view->count = 0;
5871 if (s->eof)
5872 break;
5874 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5875 s->eof = 1;
5876 break;
5877 case 'k':
5878 case KEY_UP:
5879 case CTRL('p'):
5880 if (s->first_displayed_line > 1)
5881 s->first_displayed_line--;
5882 else
5883 view->count = 0;
5884 break;
5885 case CTRL('u'):
5886 case 'u':
5887 nscroll /= 2;
5888 /* FALL THROUGH */
5889 case KEY_PPAGE:
5890 case CTRL('b'):
5891 case 'b':
5892 if (s->first_displayed_line == 1) {
5893 view->count = 0;
5894 break;
5896 i = 0;
5897 while (i++ < nscroll && s->first_displayed_line > 1)
5898 s->first_displayed_line--;
5899 break;
5900 case 'j':
5901 case KEY_DOWN:
5902 case CTRL('n'):
5903 if (!s->eof)
5904 s->first_displayed_line++;
5905 else
5906 view->count = 0;
5907 break;
5908 case CTRL('d'):
5909 case 'd':
5910 nscroll /= 2;
5911 /* FALL THROUGH */
5912 case KEY_NPAGE:
5913 case CTRL('f'):
5914 case 'f':
5915 case ' ':
5916 if (s->eof) {
5917 view->count = 0;
5918 break;
5920 i = 0;
5921 while (!s->eof && i++ < nscroll) {
5922 linelen = getline(&line, &linesize, s->f);
5923 s->first_displayed_line++;
5924 if (linelen == -1) {
5925 if (feof(s->f)) {
5926 s->eof = 1;
5927 } else
5928 err = got_ferror(s->f, GOT_ERR_IO);
5929 break;
5932 free(line);
5933 break;
5934 case '(':
5935 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5936 break;
5937 case ')':
5938 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5939 break;
5940 case '{':
5941 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5942 break;
5943 case '}':
5944 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5945 break;
5946 case '[':
5947 if (s->diff_context > 0) {
5948 s->diff_context--;
5949 s->matched_line = 0;
5950 diff_view_indicate_progress(view);
5951 err = create_diff(s);
5952 if (s->first_displayed_line + view->nlines - 1 >
5953 s->nlines) {
5954 s->first_displayed_line = 1;
5955 s->last_displayed_line = view->nlines;
5957 } else
5958 view->count = 0;
5959 break;
5960 case ']':
5961 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5962 s->diff_context++;
5963 s->matched_line = 0;
5964 diff_view_indicate_progress(view);
5965 err = create_diff(s);
5966 } else
5967 view->count = 0;
5968 break;
5969 case '<':
5970 case ',':
5971 case 'K':
5972 up = 1;
5973 /* FALL THROUGH */
5974 case '>':
5975 case '.':
5976 case 'J':
5977 if (s->parent_view == NULL) {
5978 view->count = 0;
5979 break;
5981 s->parent_view->count = view->count;
5983 if (s->parent_view->type == TOG_VIEW_LOG) {
5984 ls = &s->parent_view->state.log;
5985 old_selected_entry = ls->selected_entry;
5987 err = input_log_view(NULL, s->parent_view,
5988 up ? KEY_UP : KEY_DOWN);
5989 if (err)
5990 break;
5991 view->count = s->parent_view->count;
5993 if (old_selected_entry == ls->selected_entry)
5994 break;
5996 err = set_selected_commit(s, ls->selected_entry);
5997 if (err)
5998 break;
5999 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
6000 struct tog_blame_view_state *bs;
6001 struct got_object_id *id, *prev_id;
6003 bs = &s->parent_view->state.blame;
6004 prev_id = get_annotation_for_line(bs->blame.lines,
6005 bs->blame.nlines, bs->last_diffed_line);
6007 err = input_blame_view(&view, s->parent_view,
6008 up ? KEY_UP : KEY_DOWN);
6009 if (err)
6010 break;
6011 view->count = s->parent_view->count;
6013 if (prev_id == NULL)
6014 break;
6015 id = get_selected_commit_id(bs->blame.lines,
6016 bs->blame.nlines, bs->first_displayed_line,
6017 bs->selected_line);
6018 if (id == NULL)
6019 break;
6021 if (!got_object_id_cmp(prev_id, id))
6022 break;
6024 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
6025 if (err)
6026 break;
6028 s->first_displayed_line = 1;
6029 s->last_displayed_line = view->nlines;
6030 s->matched_line = 0;
6031 view->x = 0;
6033 diff_view_indicate_progress(view);
6034 err = create_diff(s);
6035 break;
6036 default:
6037 view->count = 0;
6038 break;
6041 return err;
6044 static const struct got_error *
6045 cmd_diff(int argc, char *argv[])
6047 const struct got_error *error;
6048 struct got_repository *repo = NULL;
6049 struct got_worktree *worktree = NULL;
6050 struct got_object_id *id1 = NULL, *id2 = NULL;
6051 char *repo_path = NULL, *cwd = NULL;
6052 char *id_str1 = NULL, *id_str2 = NULL;
6053 char *keyword_idstr1 = NULL, *keyword_idstr2 = NULL;
6054 char *label1 = NULL, *label2 = NULL;
6055 int diff_context = 3, ignore_whitespace = 0;
6056 int ch, force_text_diff = 0;
6057 const char *errstr;
6058 struct tog_view *view;
6059 int *pack_fds = NULL;
6061 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
6062 switch (ch) {
6063 case 'a':
6064 force_text_diff = 1;
6065 break;
6066 case 'C':
6067 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
6068 &errstr);
6069 if (errstr != NULL)
6070 errx(1, "number of context lines is %s: %s",
6071 errstr, errstr);
6072 break;
6073 case 'r':
6074 repo_path = realpath(optarg, NULL);
6075 if (repo_path == NULL)
6076 return got_error_from_errno2("realpath",
6077 optarg);
6078 got_path_strip_trailing_slashes(repo_path);
6079 break;
6080 case 'w':
6081 ignore_whitespace = 1;
6082 break;
6083 default:
6084 usage_diff();
6085 /* NOTREACHED */
6089 argc -= optind;
6090 argv += optind;
6092 if (argc == 0) {
6093 usage_diff(); /* TODO show local worktree changes */
6094 } else if (argc == 2) {
6095 id_str1 = argv[0];
6096 id_str2 = argv[1];
6097 } else
6098 usage_diff();
6100 error = got_repo_pack_fds_open(&pack_fds);
6101 if (error)
6102 goto done;
6104 if (repo_path == NULL) {
6105 cwd = getcwd(NULL, 0);
6106 if (cwd == NULL)
6107 return got_error_from_errno("getcwd");
6108 error = got_worktree_open(&worktree, cwd, NULL);
6109 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6110 goto done;
6111 if (worktree)
6112 repo_path =
6113 strdup(got_worktree_get_repo_path(worktree));
6114 else
6115 repo_path = strdup(cwd);
6116 if (repo_path == NULL) {
6117 error = got_error_from_errno("strdup");
6118 goto done;
6122 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6123 if (error)
6124 goto done;
6126 init_curses();
6128 error = apply_unveil(got_repo_get_path(repo), NULL);
6129 if (error)
6130 goto done;
6132 error = tog_load_refs(repo, 0);
6133 if (error)
6134 goto done;
6136 if (id_str1 != NULL) {
6137 error = got_keyword_to_idstr(&keyword_idstr1, id_str1,
6138 repo, worktree);
6139 if (error != NULL)
6140 goto done;
6141 if (keyword_idstr1 != NULL)
6142 id_str1 = keyword_idstr1;
6144 if (id_str2 != NULL) {
6145 error = got_keyword_to_idstr(&keyword_idstr2, id_str2,
6146 repo, worktree);
6147 if (error != NULL)
6148 goto done;
6149 if (keyword_idstr2 != NULL)
6150 id_str2 = keyword_idstr2;
6153 error = got_repo_match_object_id(&id1, &label1, id_str1,
6154 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6155 if (error)
6156 goto done;
6158 error = got_repo_match_object_id(&id2, &label2, id_str2,
6159 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6160 if (error)
6161 goto done;
6163 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
6164 if (view == NULL) {
6165 error = got_error_from_errno("view_open");
6166 goto done;
6168 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
6169 ignore_whitespace, force_text_diff, NULL, repo);
6170 if (error)
6171 goto done;
6173 if (worktree) {
6174 error = set_tog_base_commit(repo, worktree);
6175 if (error != NULL)
6176 goto done;
6178 /* Release work tree lock. */
6179 got_worktree_close(worktree);
6180 worktree = NULL;
6183 error = view_loop(view);
6185 done:
6186 free(tog_base_commit.id);
6187 free(keyword_idstr1);
6188 free(keyword_idstr2);
6189 free(label1);
6190 free(label2);
6191 free(id1);
6192 free(id2);
6193 free(repo_path);
6194 free(cwd);
6195 if (repo) {
6196 const struct got_error *close_err = got_repo_close(repo);
6197 if (error == NULL)
6198 error = close_err;
6200 if (worktree)
6201 got_worktree_close(worktree);
6202 if (pack_fds) {
6203 const struct got_error *pack_err =
6204 got_repo_pack_fds_close(pack_fds);
6205 if (error == NULL)
6206 error = pack_err;
6208 tog_free_refs();
6209 return error;
6212 __dead static void
6213 usage_blame(void)
6215 endwin();
6216 fprintf(stderr,
6217 "usage: %s blame [-c commit] [-r repository-path] path\n",
6218 getprogname());
6219 exit(1);
6222 struct tog_blame_line {
6223 int annotated;
6224 struct got_object_id *id;
6227 static const struct got_error *
6228 draw_blame(struct tog_view *view)
6230 struct tog_blame_view_state *s = &view->state.blame;
6231 struct tog_blame *blame = &s->blame;
6232 regmatch_t *regmatch = &view->regmatch;
6233 const struct got_error *err;
6234 int lineno = 0, nprinted = 0;
6235 char *line = NULL;
6236 size_t linesize = 0;
6237 ssize_t linelen;
6238 wchar_t *wline;
6239 int width;
6240 struct tog_blame_line *blame_line;
6241 struct got_object_id *prev_id = NULL;
6242 char *id_str;
6243 struct tog_color *tc;
6245 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6246 if (err)
6247 return err;
6249 rewind(blame->f);
6250 werase(view->window);
6252 if (asprintf(&line, "commit %s", id_str) == -1) {
6253 err = got_error_from_errno("asprintf");
6254 free(id_str);
6255 return err;
6258 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6259 free(line);
6260 line = NULL;
6261 if (err)
6262 return err;
6263 if (view_needs_focus_indication(view))
6264 wstandout(view->window);
6265 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6266 if (tc)
6267 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6268 waddwstr(view->window, wline);
6269 while (width++ < view->ncols)
6270 waddch(view->window, ' ');
6271 if (tc)
6272 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6273 if (view_needs_focus_indication(view))
6274 wstandend(view->window);
6275 free(wline);
6276 wline = NULL;
6278 if (view->gline > blame->nlines)
6279 view->gline = blame->nlines;
6281 if (tog_io.wait_for_ui) {
6282 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6283 int rc;
6285 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6286 if (rc)
6287 return got_error_set_errno(rc, "pthread_cond_wait");
6288 tog_io.wait_for_ui = 0;
6291 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6292 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6293 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6294 free(id_str);
6295 return got_error_from_errno("asprintf");
6297 free(id_str);
6298 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6299 free(line);
6300 line = NULL;
6301 if (err)
6302 return err;
6303 waddwstr(view->window, wline);
6304 free(wline);
6305 wline = NULL;
6306 if (width < view->ncols - 1)
6307 waddch(view->window, '\n');
6309 s->eof = 0;
6310 view->maxx = 0;
6311 while (nprinted < view->nlines - 2) {
6312 linelen = getline(&line, &linesize, blame->f);
6313 if (linelen == -1) {
6314 if (feof(blame->f)) {
6315 s->eof = 1;
6316 break;
6318 free(line);
6319 return got_ferror(blame->f, GOT_ERR_IO);
6321 if (++lineno < s->first_displayed_line)
6322 continue;
6323 if (view->gline && !gotoline(view, &lineno, &nprinted))
6324 continue;
6326 /* Set view->maxx based on full line length. */
6327 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6328 if (err) {
6329 free(line);
6330 return err;
6332 free(wline);
6333 wline = NULL;
6334 view->maxx = MAX(view->maxx, width);
6336 if (nprinted == s->selected_line - 1)
6337 wstandout(view->window);
6339 if (blame->nlines > 0) {
6340 blame_line = &blame->lines[lineno - 1];
6341 if (blame_line->annotated && prev_id &&
6342 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6343 !(nprinted == s->selected_line - 1)) {
6344 waddstr(view->window, " ");
6345 } else if (blame_line->annotated) {
6346 char *id_str;
6347 err = got_object_id_str(&id_str,
6348 blame_line->id);
6349 if (err) {
6350 free(line);
6351 return err;
6353 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6354 if (tc)
6355 wattr_on(view->window,
6356 COLOR_PAIR(tc->colorpair), NULL);
6357 wprintw(view->window, "%.8s", id_str);
6358 if (tc)
6359 wattr_off(view->window,
6360 COLOR_PAIR(tc->colorpair), NULL);
6361 free(id_str);
6362 prev_id = blame_line->id;
6363 } else {
6364 waddstr(view->window, "........");
6365 prev_id = NULL;
6367 } else {
6368 waddstr(view->window, "........");
6369 prev_id = NULL;
6372 if (nprinted == s->selected_line - 1)
6373 wstandend(view->window);
6374 waddstr(view->window, " ");
6376 if (view->ncols <= 9) {
6377 width = 9;
6378 } else if (s->first_displayed_line + nprinted ==
6379 s->matched_line &&
6380 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6381 err = add_matched_line(&width, line, view->ncols - 9, 9,
6382 view->window, view->x, regmatch);
6383 if (err) {
6384 free(line);
6385 return err;
6387 width += 9;
6388 } else {
6389 int skip;
6390 err = format_line(&wline, &width, &skip, line,
6391 view->x, view->ncols - 9, 9, 1);
6392 if (err) {
6393 free(line);
6394 return err;
6396 waddwstr(view->window, &wline[skip]);
6397 width += 9;
6398 free(wline);
6399 wline = NULL;
6402 if (width <= view->ncols - 1)
6403 waddch(view->window, '\n');
6404 if (++nprinted == 1)
6405 s->first_displayed_line = lineno;
6407 free(line);
6408 s->last_displayed_line = lineno;
6410 view_border(view);
6412 return NULL;
6415 static const struct got_error *
6416 blame_cb(void *arg, int nlines, int lineno,
6417 struct got_commit_object *commit, struct got_object_id *id)
6419 const struct got_error *err = NULL;
6420 struct tog_blame_cb_args *a = arg;
6421 struct tog_blame_line *line;
6422 int errcode;
6424 if (nlines != a->nlines ||
6425 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6426 return got_error(GOT_ERR_RANGE);
6428 errcode = pthread_mutex_lock(&tog_mutex);
6429 if (errcode)
6430 return got_error_set_errno(errcode, "pthread_mutex_lock");
6432 if (*a->quit) { /* user has quit the blame view */
6433 err = got_error(GOT_ERR_ITER_COMPLETED);
6434 goto done;
6437 if (lineno == -1)
6438 goto done; /* no change in this commit */
6440 line = &a->lines[lineno - 1];
6441 if (line->annotated)
6442 goto done;
6444 line->id = got_object_id_dup(id);
6445 if (line->id == NULL) {
6446 err = got_error_from_errno("got_object_id_dup");
6447 goto done;
6449 line->annotated = 1;
6450 done:
6451 errcode = pthread_mutex_unlock(&tog_mutex);
6452 if (errcode)
6453 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6454 return err;
6457 static void *
6458 blame_thread(void *arg)
6460 const struct got_error *err, *close_err;
6461 struct tog_blame_thread_args *ta = arg;
6462 struct tog_blame_cb_args *a = ta->cb_args;
6463 int errcode, fd1 = -1, fd2 = -1;
6464 FILE *f1 = NULL, *f2 = NULL;
6466 fd1 = got_opentempfd();
6467 if (fd1 == -1)
6468 return (void *)got_error_from_errno("got_opentempfd");
6470 fd2 = got_opentempfd();
6471 if (fd2 == -1) {
6472 err = got_error_from_errno("got_opentempfd");
6473 goto done;
6476 f1 = got_opentemp();
6477 if (f1 == NULL) {
6478 err = (void *)got_error_from_errno("got_opentemp");
6479 goto done;
6481 f2 = got_opentemp();
6482 if (f2 == NULL) {
6483 err = (void *)got_error_from_errno("got_opentemp");
6484 goto done;
6487 err = block_signals_used_by_main_thread();
6488 if (err)
6489 goto done;
6491 err = got_blame(ta->path, a->commit_id, ta->repo,
6492 tog_diff_algo, blame_cb, ta->cb_args,
6493 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6494 if (err && err->code == GOT_ERR_CANCELLED)
6495 err = NULL;
6497 errcode = pthread_mutex_lock(&tog_mutex);
6498 if (errcode) {
6499 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6500 goto done;
6503 close_err = got_repo_close(ta->repo);
6504 if (err == NULL)
6505 err = close_err;
6506 ta->repo = NULL;
6507 *ta->complete = 1;
6509 if (tog_io.wait_for_ui) {
6510 errcode = pthread_cond_signal(&ta->blame_complete);
6511 if (errcode && err == NULL)
6512 err = got_error_set_errno(errcode,
6513 "pthread_cond_signal");
6516 errcode = pthread_mutex_unlock(&tog_mutex);
6517 if (errcode && err == NULL)
6518 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6520 done:
6521 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6522 err = got_error_from_errno("close");
6523 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6524 err = got_error_from_errno("close");
6525 if (f1 && fclose(f1) == EOF && err == NULL)
6526 err = got_error_from_errno("fclose");
6527 if (f2 && fclose(f2) == EOF && err == NULL)
6528 err = got_error_from_errno("fclose");
6530 return (void *)err;
6533 static struct got_object_id *
6534 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6535 int first_displayed_line, int selected_line)
6537 struct tog_blame_line *line;
6539 if (nlines <= 0)
6540 return NULL;
6542 line = &lines[first_displayed_line - 1 + selected_line - 1];
6543 if (!line->annotated)
6544 return NULL;
6546 return line->id;
6549 static struct got_object_id *
6550 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6551 int lineno)
6553 struct tog_blame_line *line;
6555 if (nlines <= 0 || lineno >= nlines)
6556 return NULL;
6558 line = &lines[lineno - 1];
6559 if (!line->annotated)
6560 return NULL;
6562 return line->id;
6565 static const struct got_error *
6566 stop_blame(struct tog_blame *blame)
6568 const struct got_error *err = NULL;
6569 int i;
6571 if (blame->thread) {
6572 int errcode;
6573 errcode = pthread_mutex_unlock(&tog_mutex);
6574 if (errcode)
6575 return got_error_set_errno(errcode,
6576 "pthread_mutex_unlock");
6577 errcode = pthread_join(blame->thread, (void **)&err);
6578 if (errcode)
6579 return got_error_set_errno(errcode, "pthread_join");
6580 errcode = pthread_mutex_lock(&tog_mutex);
6581 if (errcode)
6582 return got_error_set_errno(errcode,
6583 "pthread_mutex_lock");
6584 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6585 err = NULL;
6586 blame->thread = 0; //NULL;
6588 if (blame->thread_args.repo) {
6589 const struct got_error *close_err;
6590 close_err = got_repo_close(blame->thread_args.repo);
6591 if (err == NULL)
6592 err = close_err;
6593 blame->thread_args.repo = NULL;
6595 if (blame->f) {
6596 if (fclose(blame->f) == EOF && err == NULL)
6597 err = got_error_from_errno("fclose");
6598 blame->f = NULL;
6600 if (blame->lines) {
6601 for (i = 0; i < blame->nlines; i++)
6602 free(blame->lines[i].id);
6603 free(blame->lines);
6604 blame->lines = NULL;
6606 free(blame->cb_args.commit_id);
6607 blame->cb_args.commit_id = NULL;
6608 if (blame->pack_fds) {
6609 const struct got_error *pack_err =
6610 got_repo_pack_fds_close(blame->pack_fds);
6611 if (err == NULL)
6612 err = pack_err;
6613 blame->pack_fds = NULL;
6615 free(blame->line_offsets);
6616 blame->line_offsets = NULL;
6617 return err;
6620 static const struct got_error *
6621 cancel_blame_view(void *arg)
6623 const struct got_error *err = NULL;
6624 int *done = arg;
6625 int errcode;
6627 errcode = pthread_mutex_lock(&tog_mutex);
6628 if (errcode)
6629 return got_error_set_errno(errcode,
6630 "pthread_mutex_unlock");
6632 if (*done)
6633 err = got_error(GOT_ERR_CANCELLED);
6635 errcode = pthread_mutex_unlock(&tog_mutex);
6636 if (errcode)
6637 return got_error_set_errno(errcode,
6638 "pthread_mutex_lock");
6640 return err;
6643 static const struct got_error *
6644 run_blame(struct tog_view *view)
6646 struct tog_blame_view_state *s = &view->state.blame;
6647 struct tog_blame *blame = &s->blame;
6648 const struct got_error *err = NULL;
6649 struct got_commit_object *commit = NULL;
6650 struct got_blob_object *blob = NULL;
6651 struct got_repository *thread_repo = NULL;
6652 struct got_object_id *obj_id = NULL;
6653 int obj_type, fd = -1;
6654 int *pack_fds = NULL;
6656 err = got_object_open_as_commit(&commit, s->repo,
6657 &s->blamed_commit->id);
6658 if (err)
6659 return err;
6661 fd = got_opentempfd();
6662 if (fd == -1) {
6663 err = got_error_from_errno("got_opentempfd");
6664 goto done;
6667 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6668 if (err)
6669 goto done;
6671 err = got_object_get_type(&obj_type, s->repo, obj_id);
6672 if (err)
6673 goto done;
6675 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6676 err = got_error(GOT_ERR_OBJ_TYPE);
6677 goto done;
6680 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6681 if (err)
6682 goto done;
6683 blame->f = got_opentemp();
6684 if (blame->f == NULL) {
6685 err = got_error_from_errno("got_opentemp");
6686 goto done;
6688 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6689 &blame->line_offsets, blame->f, blob);
6690 if (err)
6691 goto done;
6692 if (blame->nlines == 0) {
6693 s->blame_complete = 1;
6694 goto done;
6697 /* Don't include \n at EOF in the blame line count. */
6698 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6699 blame->nlines--;
6701 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6702 if (blame->lines == NULL) {
6703 err = got_error_from_errno("calloc");
6704 goto done;
6707 err = got_repo_pack_fds_open(&pack_fds);
6708 if (err)
6709 goto done;
6710 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6711 pack_fds);
6712 if (err)
6713 goto done;
6715 blame->pack_fds = pack_fds;
6716 blame->cb_args.view = view;
6717 blame->cb_args.lines = blame->lines;
6718 blame->cb_args.nlines = blame->nlines;
6719 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6720 if (blame->cb_args.commit_id == NULL) {
6721 err = got_error_from_errno("got_object_id_dup");
6722 goto done;
6724 blame->cb_args.quit = &s->done;
6726 blame->thread_args.path = s->path;
6727 blame->thread_args.repo = thread_repo;
6728 blame->thread_args.cb_args = &blame->cb_args;
6729 blame->thread_args.complete = &s->blame_complete;
6730 blame->thread_args.cancel_cb = cancel_blame_view;
6731 blame->thread_args.cancel_arg = &s->done;
6732 s->blame_complete = 0;
6734 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6735 s->first_displayed_line = 1;
6736 s->last_displayed_line = view->nlines;
6737 s->selected_line = 1;
6739 s->matched_line = 0;
6741 done:
6742 if (commit)
6743 got_object_commit_close(commit);
6744 if (fd != -1 && close(fd) == -1 && err == NULL)
6745 err = got_error_from_errno("close");
6746 if (blob)
6747 got_object_blob_close(blob);
6748 free(obj_id);
6749 if (err)
6750 stop_blame(blame);
6751 return err;
6754 static const struct got_error *
6755 open_blame_view(struct tog_view *view, char *path,
6756 struct got_object_id *commit_id, struct got_repository *repo)
6758 const struct got_error *err = NULL;
6759 struct tog_blame_view_state *s = &view->state.blame;
6761 STAILQ_INIT(&s->blamed_commits);
6763 s->path = strdup(path);
6764 if (s->path == NULL)
6765 return got_error_from_errno("strdup");
6767 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6768 if (err) {
6769 free(s->path);
6770 return err;
6773 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6774 s->first_displayed_line = 1;
6775 s->last_displayed_line = view->nlines;
6776 s->selected_line = 1;
6777 s->blame_complete = 0;
6778 s->repo = repo;
6779 s->commit_id = commit_id;
6780 memset(&s->blame, 0, sizeof(s->blame));
6782 STAILQ_INIT(&s->colors);
6783 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6784 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6785 get_color_value("TOG_COLOR_COMMIT"));
6786 if (err)
6787 return err;
6790 view->show = show_blame_view;
6791 view->input = input_blame_view;
6792 view->reset = reset_blame_view;
6793 view->close = close_blame_view;
6794 view->search_start = search_start_blame_view;
6795 view->search_setup = search_setup_blame_view;
6796 view->search_next = search_next_view_match;
6798 if (using_mock_io) {
6799 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6800 int rc;
6802 rc = pthread_cond_init(&bta->blame_complete, NULL);
6803 if (rc)
6804 return got_error_set_errno(rc, "pthread_cond_init");
6807 return run_blame(view);
6810 static const struct got_error *
6811 close_blame_view(struct tog_view *view)
6813 const struct got_error *err = NULL;
6814 struct tog_blame_view_state *s = &view->state.blame;
6816 if (s->blame.thread)
6817 err = stop_blame(&s->blame);
6819 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6820 struct got_object_qid *blamed_commit;
6821 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6822 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6823 got_object_qid_free(blamed_commit);
6826 if (using_mock_io) {
6827 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6828 int rc;
6830 rc = pthread_cond_destroy(&bta->blame_complete);
6831 if (rc && err == NULL)
6832 err = got_error_set_errno(rc, "pthread_cond_destroy");
6835 free(s->path);
6836 free_colors(&s->colors);
6837 return err;
6840 static const struct got_error *
6841 search_start_blame_view(struct tog_view *view)
6843 struct tog_blame_view_state *s = &view->state.blame;
6845 s->matched_line = 0;
6846 return NULL;
6849 static void
6850 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6851 size_t *nlines, int **first, int **last, int **match, int **selected)
6853 struct tog_blame_view_state *s = &view->state.blame;
6855 *f = s->blame.f;
6856 *nlines = s->blame.nlines;
6857 *line_offsets = s->blame.line_offsets;
6858 *match = &s->matched_line;
6859 *first = &s->first_displayed_line;
6860 *last = &s->last_displayed_line;
6861 *selected = &s->selected_line;
6864 static const struct got_error *
6865 show_blame_view(struct tog_view *view)
6867 const struct got_error *err = NULL;
6868 struct tog_blame_view_state *s = &view->state.blame;
6869 int errcode;
6871 if (s->blame.thread == 0 && !s->blame_complete) {
6872 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6873 &s->blame.thread_args);
6874 if (errcode)
6875 return got_error_set_errno(errcode, "pthread_create");
6877 if (!using_mock_io)
6878 halfdelay(1); /* fast refresh while annotating */
6881 if (s->blame_complete && !using_mock_io)
6882 halfdelay(10); /* disable fast refresh */
6884 err = draw_blame(view);
6886 view_border(view);
6887 return err;
6890 static const struct got_error *
6891 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6892 struct got_repository *repo, struct got_object_id *id)
6894 struct tog_view *log_view;
6895 const struct got_error *err = NULL;
6897 *new_view = NULL;
6899 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6900 if (log_view == NULL)
6901 return got_error_from_errno("view_open");
6903 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0, NULL);
6904 if (err)
6905 view_close(log_view);
6906 else
6907 *new_view = log_view;
6909 return err;
6912 static const struct got_error *
6913 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6915 const struct got_error *err = NULL, *thread_err = NULL;
6916 struct tog_view *diff_view;
6917 struct tog_blame_view_state *s = &view->state.blame;
6918 int eos, nscroll, begin_y = 0, begin_x = 0;
6920 eos = nscroll = view->nlines - 2;
6921 if (view_is_hsplit_top(view))
6922 --eos; /* border */
6924 switch (ch) {
6925 case '0':
6926 case '$':
6927 case KEY_RIGHT:
6928 case 'l':
6929 case KEY_LEFT:
6930 case 'h':
6931 horizontal_scroll_input(view, ch);
6932 break;
6933 case 'q':
6934 s->done = 1;
6935 break;
6936 case 'g':
6937 case KEY_HOME:
6938 s->selected_line = 1;
6939 s->first_displayed_line = 1;
6940 view->count = 0;
6941 break;
6942 case 'G':
6943 case KEY_END:
6944 if (s->blame.nlines < eos) {
6945 s->selected_line = s->blame.nlines;
6946 s->first_displayed_line = 1;
6947 } else {
6948 s->selected_line = eos;
6949 s->first_displayed_line = s->blame.nlines - (eos - 1);
6951 view->count = 0;
6952 break;
6953 case 'k':
6954 case KEY_UP:
6955 case CTRL('p'):
6956 if (s->selected_line > 1)
6957 s->selected_line--;
6958 else if (s->selected_line == 1 &&
6959 s->first_displayed_line > 1)
6960 s->first_displayed_line--;
6961 else
6962 view->count = 0;
6963 break;
6964 case CTRL('u'):
6965 case 'u':
6966 nscroll /= 2;
6967 /* FALL THROUGH */
6968 case KEY_PPAGE:
6969 case CTRL('b'):
6970 case 'b':
6971 if (s->first_displayed_line == 1) {
6972 if (view->count > 1)
6973 nscroll += nscroll;
6974 s->selected_line = MAX(1, s->selected_line - nscroll);
6975 view->count = 0;
6976 break;
6978 if (s->first_displayed_line > nscroll)
6979 s->first_displayed_line -= nscroll;
6980 else
6981 s->first_displayed_line = 1;
6982 break;
6983 case 'j':
6984 case KEY_DOWN:
6985 case CTRL('n'):
6986 if (s->selected_line < eos && s->first_displayed_line +
6987 s->selected_line <= s->blame.nlines)
6988 s->selected_line++;
6989 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6990 s->first_displayed_line++;
6991 else
6992 view->count = 0;
6993 break;
6994 case 'c':
6995 case 'p': {
6996 struct got_object_id *id = NULL;
6998 view->count = 0;
6999 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
7000 s->first_displayed_line, s->selected_line);
7001 if (id == NULL)
7002 break;
7003 if (ch == 'p') {
7004 struct got_commit_object *commit, *pcommit;
7005 struct got_object_qid *pid;
7006 struct got_object_id *blob_id = NULL;
7007 int obj_type;
7008 err = got_object_open_as_commit(&commit,
7009 s->repo, id);
7010 if (err)
7011 break;
7012 pid = STAILQ_FIRST(
7013 got_object_commit_get_parent_ids(commit));
7014 if (pid == NULL) {
7015 got_object_commit_close(commit);
7016 break;
7018 /* Check if path history ends here. */
7019 err = got_object_open_as_commit(&pcommit,
7020 s->repo, &pid->id);
7021 if (err)
7022 break;
7023 err = got_object_id_by_path(&blob_id, s->repo,
7024 pcommit, s->path);
7025 got_object_commit_close(pcommit);
7026 if (err) {
7027 if (err->code == GOT_ERR_NO_TREE_ENTRY)
7028 err = NULL;
7029 got_object_commit_close(commit);
7030 break;
7032 err = got_object_get_type(&obj_type, s->repo,
7033 blob_id);
7034 free(blob_id);
7035 /* Can't blame non-blob type objects. */
7036 if (obj_type != GOT_OBJ_TYPE_BLOB) {
7037 got_object_commit_close(commit);
7038 break;
7040 err = got_object_qid_alloc(&s->blamed_commit,
7041 &pid->id);
7042 got_object_commit_close(commit);
7043 } else {
7044 if (got_object_id_cmp(id,
7045 &s->blamed_commit->id) == 0)
7046 break;
7047 err = got_object_qid_alloc(&s->blamed_commit,
7048 id);
7050 if (err)
7051 break;
7052 s->done = 1;
7053 thread_err = stop_blame(&s->blame);
7054 s->done = 0;
7055 if (thread_err)
7056 break;
7057 STAILQ_INSERT_HEAD(&s->blamed_commits,
7058 s->blamed_commit, entry);
7059 err = run_blame(view);
7060 if (err)
7061 break;
7062 break;
7064 case 'C': {
7065 struct got_object_qid *first;
7067 view->count = 0;
7068 first = STAILQ_FIRST(&s->blamed_commits);
7069 if (!got_object_id_cmp(&first->id, s->commit_id))
7070 break;
7071 s->done = 1;
7072 thread_err = stop_blame(&s->blame);
7073 s->done = 0;
7074 if (thread_err)
7075 break;
7076 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
7077 got_object_qid_free(s->blamed_commit);
7078 s->blamed_commit =
7079 STAILQ_FIRST(&s->blamed_commits);
7080 err = run_blame(view);
7081 if (err)
7082 break;
7083 break;
7085 case 'L':
7086 view->count = 0;
7087 s->id_to_log = get_selected_commit_id(s->blame.lines,
7088 s->blame.nlines, s->first_displayed_line, s->selected_line);
7089 if (s->id_to_log)
7090 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7091 break;
7092 case KEY_ENTER:
7093 case '\r': {
7094 struct got_object_id *id = NULL;
7095 struct got_object_qid *pid;
7096 struct got_commit_object *commit = NULL;
7098 view->count = 0;
7099 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
7100 s->first_displayed_line, s->selected_line);
7101 if (id == NULL)
7102 break;
7103 err = got_object_open_as_commit(&commit, s->repo, id);
7104 if (err)
7105 break;
7106 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7107 if (*new_view) {
7108 /* traversed from diff view, release diff resources */
7109 err = close_diff_view(*new_view);
7110 if (err)
7111 break;
7112 diff_view = *new_view;
7113 } else {
7114 if (view_is_parent_view(view))
7115 view_get_split(view, &begin_y, &begin_x);
7117 diff_view = view_open(0, 0, begin_y, begin_x,
7118 TOG_VIEW_DIFF);
7119 if (diff_view == NULL) {
7120 got_object_commit_close(commit);
7121 err = got_error_from_errno("view_open");
7122 break;
7125 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
7126 id, NULL, NULL, 3, 0, 0, view, s->repo);
7127 got_object_commit_close(commit);
7128 if (err)
7129 break;
7130 s->last_diffed_line = s->first_displayed_line - 1 +
7131 s->selected_line;
7132 if (*new_view)
7133 break; /* still open from active diff view */
7134 if (view_is_parent_view(view) &&
7135 view->mode == TOG_VIEW_SPLIT_HRZN) {
7136 err = view_init_hsplit(view, begin_y);
7137 if (err)
7138 break;
7141 view->focussed = 0;
7142 diff_view->focussed = 1;
7143 diff_view->mode = view->mode;
7144 diff_view->nlines = view->lines - begin_y;
7145 if (view_is_parent_view(view)) {
7146 view_transfer_size(diff_view, view);
7147 err = view_close_child(view);
7148 if (err)
7149 break;
7150 err = view_set_child(view, diff_view);
7151 if (err)
7152 break;
7153 view->focus_child = 1;
7154 } else
7155 *new_view = diff_view;
7156 if (err)
7157 break;
7158 break;
7160 case CTRL('d'):
7161 case 'd':
7162 nscroll /= 2;
7163 /* FALL THROUGH */
7164 case KEY_NPAGE:
7165 case CTRL('f'):
7166 case 'f':
7167 case ' ':
7168 if (s->last_displayed_line >= s->blame.nlines &&
7169 s->selected_line >= MIN(s->blame.nlines,
7170 view->nlines - 2)) {
7171 view->count = 0;
7172 break;
7174 if (s->last_displayed_line >= s->blame.nlines &&
7175 s->selected_line < view->nlines - 2) {
7176 s->selected_line +=
7177 MIN(nscroll, s->last_displayed_line -
7178 s->first_displayed_line - s->selected_line + 1);
7180 if (s->last_displayed_line + nscroll <= s->blame.nlines)
7181 s->first_displayed_line += nscroll;
7182 else
7183 s->first_displayed_line =
7184 s->blame.nlines - (view->nlines - 3);
7185 break;
7186 case KEY_RESIZE:
7187 if (s->selected_line > view->nlines - 2) {
7188 s->selected_line = MIN(s->blame.nlines,
7189 view->nlines - 2);
7191 break;
7192 default:
7193 view->count = 0;
7194 break;
7196 return thread_err ? thread_err : err;
7199 static const struct got_error *
7200 reset_blame_view(struct tog_view *view)
7202 const struct got_error *err;
7203 struct tog_blame_view_state *s = &view->state.blame;
7205 view->count = 0;
7206 s->done = 1;
7207 err = stop_blame(&s->blame);
7208 s->done = 0;
7209 if (err)
7210 return err;
7211 return run_blame(view);
7214 static const struct got_error *
7215 cmd_blame(int argc, char *argv[])
7217 const struct got_error *error;
7218 struct got_repository *repo = NULL;
7219 struct got_worktree *worktree = NULL;
7220 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7221 char *link_target = NULL;
7222 struct got_object_id *commit_id = NULL;
7223 struct got_commit_object *commit = NULL;
7224 char *keyword_idstr = NULL, *commit_id_str = NULL;
7225 int ch;
7226 struct tog_view *view = NULL;
7227 int *pack_fds = NULL;
7229 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7230 switch (ch) {
7231 case 'c':
7232 commit_id_str = optarg;
7233 break;
7234 case 'r':
7235 repo_path = realpath(optarg, NULL);
7236 if (repo_path == NULL)
7237 return got_error_from_errno2("realpath",
7238 optarg);
7239 break;
7240 default:
7241 usage_blame();
7242 /* NOTREACHED */
7246 argc -= optind;
7247 argv += optind;
7249 if (argc != 1)
7250 usage_blame();
7252 error = got_repo_pack_fds_open(&pack_fds);
7253 if (error != NULL)
7254 goto done;
7256 if (repo_path == NULL) {
7257 cwd = getcwd(NULL, 0);
7258 if (cwd == NULL)
7259 return got_error_from_errno("getcwd");
7260 error = got_worktree_open(&worktree, cwd, NULL);
7261 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7262 goto done;
7263 if (worktree)
7264 repo_path =
7265 strdup(got_worktree_get_repo_path(worktree));
7266 else
7267 repo_path = strdup(cwd);
7268 if (repo_path == NULL) {
7269 error = got_error_from_errno("strdup");
7270 goto done;
7274 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7275 if (error != NULL)
7276 goto done;
7278 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7279 worktree);
7280 if (error)
7281 goto done;
7283 init_curses();
7285 error = apply_unveil(got_repo_get_path(repo), NULL);
7286 if (error)
7287 goto done;
7289 error = tog_load_refs(repo, 0);
7290 if (error)
7291 goto done;
7293 if (commit_id_str == NULL) {
7294 struct got_reference *head_ref;
7295 error = got_ref_open(&head_ref, repo, worktree ?
7296 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7297 if (error != NULL)
7298 goto done;
7299 error = got_ref_resolve(&commit_id, repo, head_ref);
7300 got_ref_close(head_ref);
7301 } else {
7302 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
7303 repo, worktree);
7304 if (error != NULL)
7305 goto done;
7306 if (keyword_idstr != NULL)
7307 commit_id_str = keyword_idstr;
7309 error = got_repo_match_object_id(&commit_id, NULL,
7310 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7312 if (error != NULL)
7313 goto done;
7315 error = got_object_open_as_commit(&commit, repo, commit_id);
7316 if (error)
7317 goto done;
7319 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7320 commit, repo);
7321 if (error)
7322 goto done;
7324 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7325 if (view == NULL) {
7326 error = got_error_from_errno("view_open");
7327 goto done;
7329 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7330 commit_id, repo);
7331 if (error != NULL) {
7332 if (view->close == NULL)
7333 close_blame_view(view);
7334 view_close(view);
7335 goto done;
7338 if (worktree) {
7339 error = set_tog_base_commit(repo, worktree);
7340 if (error != NULL)
7341 goto done;
7343 /* Release work tree lock. */
7344 got_worktree_close(worktree);
7345 worktree = NULL;
7348 error = view_loop(view);
7350 done:
7351 free(tog_base_commit.id);
7352 free(repo_path);
7353 free(in_repo_path);
7354 free(link_target);
7355 free(cwd);
7356 free(commit_id);
7357 free(keyword_idstr);
7358 if (commit)
7359 got_object_commit_close(commit);
7360 if (worktree)
7361 got_worktree_close(worktree);
7362 if (repo) {
7363 const struct got_error *close_err = got_repo_close(repo);
7364 if (error == NULL)
7365 error = close_err;
7367 if (pack_fds) {
7368 const struct got_error *pack_err =
7369 got_repo_pack_fds_close(pack_fds);
7370 if (error == NULL)
7371 error = pack_err;
7373 tog_free_refs();
7374 return error;
7377 static const struct got_error *
7378 draw_tree_entries(struct tog_view *view, const char *parent_path)
7380 struct tog_tree_view_state *s = &view->state.tree;
7381 const struct got_error *err = NULL;
7382 struct got_tree_entry *te;
7383 wchar_t *wline;
7384 char *index = NULL;
7385 struct tog_color *tc;
7386 int width, n, nentries, scrollx, i = 1;
7387 int limit = view->nlines;
7389 s->ndisplayed = 0;
7390 if (view_is_hsplit_top(view))
7391 --limit; /* border */
7393 werase(view->window);
7395 if (limit == 0)
7396 return NULL;
7398 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7399 0, 0);
7400 if (err)
7401 return err;
7402 if (view_needs_focus_indication(view))
7403 wstandout(view->window);
7404 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7405 if (tc)
7406 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7407 waddwstr(view->window, wline);
7408 free(wline);
7409 wline = NULL;
7410 while (width++ < view->ncols)
7411 waddch(view->window, ' ');
7412 if (tc)
7413 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7414 if (view_needs_focus_indication(view))
7415 wstandend(view->window);
7416 if (--limit <= 0)
7417 return NULL;
7419 i += s->selected;
7420 if (s->first_displayed_entry) {
7421 i += got_tree_entry_get_index(s->first_displayed_entry);
7422 if (s->tree != s->root)
7423 ++i; /* account for ".." entry */
7425 nentries = got_object_tree_get_nentries(s->tree);
7426 if (asprintf(&index, "[%d/%d] %s",
7427 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7428 return got_error_from_errno("asprintf");
7429 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7430 free(index);
7431 if (err)
7432 return err;
7433 waddwstr(view->window, wline);
7434 free(wline);
7435 wline = NULL;
7436 if (width < view->ncols - 1)
7437 waddch(view->window, '\n');
7438 if (--limit <= 0)
7439 return NULL;
7440 waddch(view->window, '\n');
7441 if (--limit <= 0)
7442 return NULL;
7444 if (s->first_displayed_entry == NULL) {
7445 te = got_object_tree_get_first_entry(s->tree);
7446 if (s->selected == 0) {
7447 if (view->focussed)
7448 wstandout(view->window);
7449 s->selected_entry = NULL;
7451 waddstr(view->window, " ..\n"); /* parent directory */
7452 if (s->selected == 0 && view->focussed)
7453 wstandend(view->window);
7454 s->ndisplayed++;
7455 if (--limit <= 0)
7456 return NULL;
7457 n = 1;
7458 } else {
7459 n = 0;
7460 te = s->first_displayed_entry;
7463 view->maxx = 0;
7464 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7465 char *line = NULL, *id_str = NULL, *link_target = NULL;
7466 const char *modestr = "";
7467 mode_t mode;
7469 te = got_object_tree_get_entry(s->tree, i);
7470 mode = got_tree_entry_get_mode(te);
7472 if (s->show_ids) {
7473 err = got_object_id_str(&id_str,
7474 got_tree_entry_get_id(te));
7475 if (err)
7476 return got_error_from_errno(
7477 "got_object_id_str");
7479 if (got_object_tree_entry_is_submodule(te))
7480 modestr = "$";
7481 else if (S_ISLNK(mode)) {
7482 int i;
7484 err = got_tree_entry_get_symlink_target(&link_target,
7485 te, s->repo);
7486 if (err) {
7487 free(id_str);
7488 return err;
7490 for (i = 0; link_target[i] != '\0'; i++) {
7491 if (!isprint((unsigned char)link_target[i]))
7492 link_target[i] = '?';
7494 modestr = "@";
7496 else if (S_ISDIR(mode))
7497 modestr = "/";
7498 else if (mode & S_IXUSR)
7499 modestr = "*";
7500 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7501 got_tree_entry_get_name(te), modestr,
7502 link_target ? " -> ": "",
7503 link_target ? link_target : "") == -1) {
7504 free(id_str);
7505 free(link_target);
7506 return got_error_from_errno("asprintf");
7508 free(id_str);
7509 free(link_target);
7511 /* use full line width to determine view->maxx */
7512 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7513 if (err) {
7514 free(line);
7515 break;
7517 view->maxx = MAX(view->maxx, width);
7518 free(wline);
7519 wline = NULL;
7521 err = format_line(&wline, &width, &scrollx, line, view->x,
7522 view->ncols, 0, 0);
7523 if (err) {
7524 free(line);
7525 break;
7527 if (n == s->selected) {
7528 if (view->focussed)
7529 wstandout(view->window);
7530 s->selected_entry = te;
7532 tc = match_color(&s->colors, line);
7533 if (tc)
7534 wattr_on(view->window,
7535 COLOR_PAIR(tc->colorpair), NULL);
7536 waddwstr(view->window, &wline[scrollx]);
7537 if (tc)
7538 wattr_off(view->window,
7539 COLOR_PAIR(tc->colorpair), NULL);
7540 if (width < view->ncols)
7541 waddch(view->window, '\n');
7542 if (n == s->selected && view->focussed)
7543 wstandend(view->window);
7544 free(line);
7545 free(wline);
7546 wline = NULL;
7547 n++;
7548 s->ndisplayed++;
7549 s->last_displayed_entry = te;
7550 if (--limit <= 0)
7551 break;
7554 return err;
7557 static void
7558 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7560 struct got_tree_entry *te;
7561 int isroot = s->tree == s->root;
7562 int i = 0;
7564 if (s->first_displayed_entry == NULL)
7565 return;
7567 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7568 while (i++ < maxscroll) {
7569 if (te == NULL) {
7570 if (!isroot)
7571 s->first_displayed_entry = NULL;
7572 break;
7574 s->first_displayed_entry = te;
7575 te = got_tree_entry_get_prev(s->tree, te);
7579 static const struct got_error *
7580 tree_scroll_down(struct tog_view *view, int maxscroll)
7582 struct tog_tree_view_state *s = &view->state.tree;
7583 struct got_tree_entry *next, *last;
7584 int n = 0;
7586 if (s->first_displayed_entry)
7587 next = got_tree_entry_get_next(s->tree,
7588 s->first_displayed_entry);
7589 else
7590 next = got_object_tree_get_first_entry(s->tree);
7592 last = s->last_displayed_entry;
7593 while (next && n++ < maxscroll) {
7594 if (last) {
7595 s->last_displayed_entry = last;
7596 last = got_tree_entry_get_next(s->tree, last);
7598 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7599 s->first_displayed_entry = next;
7600 next = got_tree_entry_get_next(s->tree, next);
7604 return NULL;
7607 static const struct got_error *
7608 tree_entry_path(char **path, struct tog_parent_trees *parents,
7609 struct got_tree_entry *te)
7611 const struct got_error *err = NULL;
7612 struct tog_parent_tree *pt;
7613 size_t len = 2; /* for leading slash and NUL */
7615 TAILQ_FOREACH(pt, parents, entry)
7616 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7617 + 1 /* slash */;
7618 if (te)
7619 len += strlen(got_tree_entry_get_name(te));
7621 *path = calloc(1, len);
7622 if (path == NULL)
7623 return got_error_from_errno("calloc");
7625 (*path)[0] = '/';
7626 pt = TAILQ_LAST(parents, tog_parent_trees);
7627 while (pt) {
7628 const char *name = got_tree_entry_get_name(pt->selected_entry);
7629 if (strlcat(*path, name, len) >= len) {
7630 err = got_error(GOT_ERR_NO_SPACE);
7631 goto done;
7633 if (strlcat(*path, "/", len) >= len) {
7634 err = got_error(GOT_ERR_NO_SPACE);
7635 goto done;
7637 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7639 if (te) {
7640 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7641 err = got_error(GOT_ERR_NO_SPACE);
7642 goto done;
7645 done:
7646 if (err) {
7647 free(*path);
7648 *path = NULL;
7650 return err;
7653 static const struct got_error *
7654 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7655 struct got_tree_entry *te, struct tog_parent_trees *parents,
7656 struct got_object_id *commit_id, struct got_repository *repo)
7658 const struct got_error *err = NULL;
7659 char *path;
7660 struct tog_view *blame_view;
7662 *new_view = NULL;
7664 err = tree_entry_path(&path, parents, te);
7665 if (err)
7666 return err;
7668 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7669 if (blame_view == NULL) {
7670 err = got_error_from_errno("view_open");
7671 goto done;
7674 err = open_blame_view(blame_view, path, commit_id, repo);
7675 if (err) {
7676 if (err->code == GOT_ERR_CANCELLED)
7677 err = NULL;
7678 view_close(blame_view);
7679 } else
7680 *new_view = blame_view;
7681 done:
7682 free(path);
7683 return err;
7686 static const struct got_error *
7687 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7688 struct tog_tree_view_state *s)
7690 struct tog_view *log_view;
7691 const struct got_error *err = NULL;
7692 char *path;
7694 *new_view = NULL;
7696 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7697 if (log_view == NULL)
7698 return got_error_from_errno("view_open");
7700 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7701 if (err)
7702 return err;
7704 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7705 path, 0, NULL);
7706 if (err)
7707 view_close(log_view);
7708 else
7709 *new_view = log_view;
7710 free(path);
7711 return err;
7714 static const struct got_error *
7715 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7716 const char *head_ref_name, struct got_repository *repo)
7718 const struct got_error *err = NULL;
7719 char *commit_id_str = NULL;
7720 struct tog_tree_view_state *s = &view->state.tree;
7721 struct got_commit_object *commit = NULL;
7723 TAILQ_INIT(&s->parents);
7724 STAILQ_INIT(&s->colors);
7726 s->commit_id = got_object_id_dup(commit_id);
7727 if (s->commit_id == NULL) {
7728 err = got_error_from_errno("got_object_id_dup");
7729 goto done;
7732 err = got_object_open_as_commit(&commit, repo, commit_id);
7733 if (err)
7734 goto done;
7737 * The root is opened here and will be closed when the view is closed.
7738 * Any visited subtrees and their path-wise parents are opened and
7739 * closed on demand.
7741 err = got_object_open_as_tree(&s->root, repo,
7742 got_object_commit_get_tree_id(commit));
7743 if (err)
7744 goto done;
7745 s->tree = s->root;
7747 err = got_object_id_str(&commit_id_str, commit_id);
7748 if (err != NULL)
7749 goto done;
7751 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7752 err = got_error_from_errno("asprintf");
7753 goto done;
7756 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7757 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7758 if (head_ref_name) {
7759 s->head_ref_name = strdup(head_ref_name);
7760 if (s->head_ref_name == NULL) {
7761 err = got_error_from_errno("strdup");
7762 goto done;
7765 s->repo = repo;
7767 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7768 err = add_color(&s->colors, "\\$$",
7769 TOG_COLOR_TREE_SUBMODULE,
7770 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7771 if (err)
7772 goto done;
7773 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7774 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7775 if (err)
7776 goto done;
7777 err = add_color(&s->colors, "/$",
7778 TOG_COLOR_TREE_DIRECTORY,
7779 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7780 if (err)
7781 goto done;
7783 err = add_color(&s->colors, "\\*$",
7784 TOG_COLOR_TREE_EXECUTABLE,
7785 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7786 if (err)
7787 goto done;
7789 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7790 get_color_value("TOG_COLOR_COMMIT"));
7791 if (err)
7792 goto done;
7795 view->show = show_tree_view;
7796 view->input = input_tree_view;
7797 view->close = close_tree_view;
7798 view->search_start = search_start_tree_view;
7799 view->search_next = search_next_tree_view;
7800 done:
7801 free(commit_id_str);
7802 if (commit)
7803 got_object_commit_close(commit);
7804 if (err) {
7805 if (view->close == NULL)
7806 close_tree_view(view);
7807 view_close(view);
7809 return err;
7812 static const struct got_error *
7813 close_tree_view(struct tog_view *view)
7815 struct tog_tree_view_state *s = &view->state.tree;
7817 free_colors(&s->colors);
7818 free(s->tree_label);
7819 s->tree_label = NULL;
7820 free(s->commit_id);
7821 s->commit_id = NULL;
7822 free(s->head_ref_name);
7823 s->head_ref_name = NULL;
7824 while (!TAILQ_EMPTY(&s->parents)) {
7825 struct tog_parent_tree *parent;
7826 parent = TAILQ_FIRST(&s->parents);
7827 TAILQ_REMOVE(&s->parents, parent, entry);
7828 if (parent->tree != s->root)
7829 got_object_tree_close(parent->tree);
7830 free(parent);
7833 if (s->tree != NULL && s->tree != s->root)
7834 got_object_tree_close(s->tree);
7835 if (s->root)
7836 got_object_tree_close(s->root);
7837 return NULL;
7840 static const struct got_error *
7841 search_start_tree_view(struct tog_view *view)
7843 struct tog_tree_view_state *s = &view->state.tree;
7845 s->matched_entry = NULL;
7846 return NULL;
7849 static int
7850 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7852 regmatch_t regmatch;
7854 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7855 0) == 0;
7858 static const struct got_error *
7859 search_next_tree_view(struct tog_view *view)
7861 struct tog_tree_view_state *s = &view->state.tree;
7862 struct got_tree_entry *te = NULL;
7864 if (!view->searching) {
7865 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7866 return NULL;
7869 if (s->matched_entry) {
7870 if (view->searching == TOG_SEARCH_FORWARD) {
7871 if (s->selected_entry)
7872 te = got_tree_entry_get_next(s->tree,
7873 s->selected_entry);
7874 else
7875 te = got_object_tree_get_first_entry(s->tree);
7876 } else {
7877 if (s->selected_entry == NULL)
7878 te = got_object_tree_get_last_entry(s->tree);
7879 else
7880 te = got_tree_entry_get_prev(s->tree,
7881 s->selected_entry);
7883 } else {
7884 if (s->selected_entry)
7885 te = s->selected_entry;
7886 else if (view->searching == TOG_SEARCH_FORWARD)
7887 te = got_object_tree_get_first_entry(s->tree);
7888 else
7889 te = got_object_tree_get_last_entry(s->tree);
7892 while (1) {
7893 if (te == NULL) {
7894 if (s->matched_entry == NULL) {
7895 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7896 return NULL;
7898 if (view->searching == TOG_SEARCH_FORWARD)
7899 te = got_object_tree_get_first_entry(s->tree);
7900 else
7901 te = got_object_tree_get_last_entry(s->tree);
7904 if (match_tree_entry(te, &view->regex)) {
7905 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7906 s->matched_entry = te;
7907 break;
7910 if (view->searching == TOG_SEARCH_FORWARD)
7911 te = got_tree_entry_get_next(s->tree, te);
7912 else
7913 te = got_tree_entry_get_prev(s->tree, te);
7916 if (s->matched_entry) {
7917 s->first_displayed_entry = s->matched_entry;
7918 s->selected = 0;
7921 return NULL;
7924 static const struct got_error *
7925 show_tree_view(struct tog_view *view)
7927 const struct got_error *err = NULL;
7928 struct tog_tree_view_state *s = &view->state.tree;
7929 char *parent_path;
7931 err = tree_entry_path(&parent_path, &s->parents, NULL);
7932 if (err)
7933 return err;
7935 err = draw_tree_entries(view, parent_path);
7936 free(parent_path);
7938 view_border(view);
7939 return err;
7942 static const struct got_error *
7943 tree_goto_line(struct tog_view *view, int nlines)
7945 const struct got_error *err = NULL;
7946 struct tog_tree_view_state *s = &view->state.tree;
7947 struct got_tree_entry **fte, **lte, **ste;
7948 int g, last, first = 1, i = 1;
7949 int root = s->tree == s->root;
7950 int off = root ? 1 : 2;
7952 g = view->gline;
7953 view->gline = 0;
7955 if (g == 0)
7956 g = 1;
7957 else if (g > got_object_tree_get_nentries(s->tree))
7958 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7960 fte = &s->first_displayed_entry;
7961 lte = &s->last_displayed_entry;
7962 ste = &s->selected_entry;
7964 if (*fte != NULL) {
7965 first = got_tree_entry_get_index(*fte);
7966 first += off; /* account for ".." */
7968 last = got_tree_entry_get_index(*lte);
7969 last += off;
7971 if (g >= first && g <= last && g - first < nlines) {
7972 s->selected = g - first;
7973 return NULL; /* gline is on the current page */
7976 if (*ste != NULL) {
7977 i = got_tree_entry_get_index(*ste);
7978 i += off;
7981 if (i < g) {
7982 err = tree_scroll_down(view, g - i);
7983 if (err)
7984 return err;
7985 if (got_tree_entry_get_index(*lte) >=
7986 got_object_tree_get_nentries(s->tree) - 1 &&
7987 first + s->selected < g &&
7988 s->selected < s->ndisplayed - 1) {
7989 first = got_tree_entry_get_index(*fte);
7990 first += off;
7991 s->selected = g - first;
7993 } else if (i > g)
7994 tree_scroll_up(s, i - g);
7996 if (g < nlines &&
7997 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7998 s->selected = g - 1;
8000 return NULL;
8003 static const struct got_error *
8004 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
8006 const struct got_error *err = NULL;
8007 struct tog_tree_view_state *s = &view->state.tree;
8008 struct got_tree_entry *te;
8009 int n, nscroll = view->nlines - 3;
8011 if (view->gline)
8012 return tree_goto_line(view, nscroll);
8014 switch (ch) {
8015 case '0':
8016 case '$':
8017 case KEY_RIGHT:
8018 case 'l':
8019 case KEY_LEFT:
8020 case 'h':
8021 horizontal_scroll_input(view, ch);
8022 break;
8023 case 'i':
8024 s->show_ids = !s->show_ids;
8025 view->count = 0;
8026 break;
8027 case 'L':
8028 view->count = 0;
8029 if (!s->selected_entry)
8030 break;
8031 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8032 break;
8033 case 'R':
8034 view->count = 0;
8035 err = view_request_new(new_view, view, TOG_VIEW_REF);
8036 break;
8037 case 'g':
8038 case '=':
8039 case KEY_HOME:
8040 s->selected = 0;
8041 view->count = 0;
8042 if (s->tree == s->root)
8043 s->first_displayed_entry =
8044 got_object_tree_get_first_entry(s->tree);
8045 else
8046 s->first_displayed_entry = NULL;
8047 break;
8048 case 'G':
8049 case '*':
8050 case KEY_END: {
8051 int eos = view->nlines - 3;
8053 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8054 --eos; /* border */
8055 s->selected = 0;
8056 view->count = 0;
8057 te = got_object_tree_get_last_entry(s->tree);
8058 for (n = 0; n < eos; n++) {
8059 if (te == NULL) {
8060 if (s->tree != s->root) {
8061 s->first_displayed_entry = NULL;
8062 n++;
8064 break;
8066 s->first_displayed_entry = te;
8067 te = got_tree_entry_get_prev(s->tree, te);
8069 if (n > 0)
8070 s->selected = n - 1;
8071 break;
8073 case 'k':
8074 case KEY_UP:
8075 case CTRL('p'):
8076 if (s->selected > 0) {
8077 s->selected--;
8078 break;
8080 tree_scroll_up(s, 1);
8081 if (s->selected_entry == NULL ||