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 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2312 wline[wlen - 1] = L'\0';
2313 wlen--;
2315 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2316 wline[wlen - 1] = L'\0';
2317 wlen--;
2320 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
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 + 2 + 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 (view_is_hsplit_top(view) && s->first_displayed_entry &&
4021 s->last_displayed_entry) {
4022 s->selected = MIN(s->selected,
4023 s->last_displayed_entry->idx -
4024 s->first_displayed_entry->idx);
4027 select_commit(s);
4029 if (s->thread_args.log_complete &&
4030 s->selected_entry->idx == s->commits->ncommits - 1)
4031 view->count = 0;
4033 return NULL;
4036 static void
4037 view_get_split(struct tog_view *view, int *y, int *x)
4039 *x = 0;
4040 *y = 0;
4042 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
4043 if (view->child && view->child->resized_y)
4044 *y = view->child->resized_y;
4045 else if (view->resized_y)
4046 *y = view->resized_y;
4047 else
4048 *y = view_split_begin_y(view->lines);
4049 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
4050 if (view->child && view->child->resized_x)
4051 *x = view->child->resized_x;
4052 else if (view->resized_x)
4053 *x = view->resized_x;
4054 else
4055 *x = view_split_begin_x(view->begin_x);
4059 /* Split view horizontally at y and offset view->state->selected line. */
4060 static const struct got_error *
4061 view_init_hsplit(struct tog_view *view, int y)
4063 const struct got_error *err = NULL;
4065 view->nlines = y;
4066 view->ncols = COLS;
4067 err = view_resize(view);
4068 if (err)
4069 return err;
4071 err = offset_selection_down(view);
4073 return err;
4076 static const struct got_error *
4077 log_goto_line(struct tog_view *view, int nlines)
4079 const struct got_error *err = NULL;
4080 struct tog_log_view_state *s = &view->state.log;
4081 int g, idx = s->selected_entry->idx;
4083 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
4084 return NULL;
4086 g = view->gline;
4087 view->gline = 0;
4089 if (g >= s->first_displayed_entry->idx + 1 &&
4090 g <= s->last_displayed_entry->idx + 1 &&
4091 g - s->first_displayed_entry->idx - 1 < nlines) {
4092 s->selected = g - s->first_displayed_entry->idx - 1;
4093 select_commit(s);
4094 return NULL;
4097 if (idx + 1 < g) {
4098 err = log_move_cursor_down(view, g - idx - 1);
4099 if (!err && g > s->selected_entry->idx + 1)
4100 err = log_move_cursor_down(view,
4101 g - s->first_displayed_entry->idx - 1);
4102 if (err)
4103 return err;
4104 } else if (idx + 1 > g)
4105 log_move_cursor_up(view, idx - g + 1, 0);
4107 if (g < nlines && s->first_displayed_entry->idx == 0)
4108 s->selected = g - 1;
4110 select_commit(s);
4111 return NULL;
4115 static void
4116 horizontal_scroll_input(struct tog_view *view, int ch)
4119 switch (ch) {
4120 case KEY_LEFT:
4121 case 'h':
4122 view->x -= MIN(view->x, 2);
4123 if (view->x <= 0)
4124 view->count = 0;
4125 break;
4126 case KEY_RIGHT:
4127 case 'l':
4128 if (view->x + view->ncols / 2 < view->maxx)
4129 view->x += 2;
4130 else
4131 view->count = 0;
4132 break;
4133 case '0':
4134 view->x = 0;
4135 break;
4136 case '$':
4137 view->x = MAX(view->maxx - view->ncols / 2, 0);
4138 view->count = 0;
4139 break;
4140 default:
4141 break;
4145 static const struct got_error *
4146 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
4148 const struct got_error *err = NULL;
4149 struct tog_log_view_state *s = &view->state.log;
4150 int eos, nscroll;
4152 if (s->thread_args.load_all) {
4153 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
4154 s->thread_args.load_all = 0;
4155 else if (s->thread_args.log_complete) {
4156 err = log_move_cursor_down(view, s->commits->ncommits);
4157 s->thread_args.load_all = 0;
4159 if (err)
4160 return err;
4163 eos = nscroll = view->nlines - 1;
4164 if (view_is_hsplit_top(view))
4165 --eos; /* border */
4167 if (view->gline)
4168 return log_goto_line(view, eos);
4170 switch (ch) {
4171 case '&':
4172 err = limit_log_view(view);
4173 break;
4174 case 'q':
4175 s->quit = 1;
4176 break;
4177 case '0':
4178 case '$':
4179 case KEY_RIGHT:
4180 case 'l':
4181 case KEY_LEFT:
4182 case 'h':
4183 horizontal_scroll_input(view, ch);
4184 break;
4185 case 'k':
4186 case KEY_UP:
4187 case '<':
4188 case ',':
4189 case CTRL('p'):
4190 log_move_cursor_up(view, 0, 0);
4191 break;
4192 case 'g':
4193 case '=':
4194 case KEY_HOME:
4195 log_move_cursor_up(view, 0, 1);
4196 view->count = 0;
4197 break;
4198 case CTRL('u'):
4199 case 'u':
4200 nscroll /= 2;
4201 /* FALL THROUGH */
4202 case KEY_PPAGE:
4203 case CTRL('b'):
4204 case 'b':
4205 log_move_cursor_up(view, nscroll, 0);
4206 break;
4207 case 'j':
4208 case KEY_DOWN:
4209 case '>':
4210 case '.':
4211 case CTRL('n'):
4212 err = log_move_cursor_down(view, 0);
4213 break;
4214 case '@':
4215 s->use_committer = !s->use_committer;
4216 view->action = s->use_committer ?
4217 "show committer" : "show commit author";
4218 break;
4219 case 'G':
4220 case '*':
4221 case KEY_END: {
4222 /* We don't know yet how many commits, so we're forced to
4223 * traverse them all. */
4224 view->count = 0;
4225 s->thread_args.load_all = 1;
4226 if (!s->thread_args.log_complete)
4227 return trigger_log_thread(view, 0);
4228 err = log_move_cursor_down(view, s->commits->ncommits);
4229 s->thread_args.load_all = 0;
4230 break;
4232 case CTRL('d'):
4233 case 'd':
4234 nscroll /= 2;
4235 /* FALL THROUGH */
4236 case KEY_NPAGE:
4237 case CTRL('f'):
4238 case 'f':
4239 case ' ':
4240 err = log_move_cursor_down(view, nscroll);
4241 break;
4242 case KEY_RESIZE:
4243 if (s->selected > view->nlines - 2)
4244 s->selected = view->nlines - 2;
4245 if (s->selected > s->commits->ncommits - 1)
4246 s->selected = s->commits->ncommits - 1;
4247 select_commit(s);
4248 if (s->commits->ncommits < view->nlines - 1 &&
4249 !s->thread_args.log_complete) {
4250 s->thread_args.commits_needed += (view->nlines - 1) -
4251 s->commits->ncommits;
4252 err = trigger_log_thread(view, 1);
4254 break;
4255 case KEY_ENTER:
4256 case '\r':
4257 view->count = 0;
4258 if (s->selected_entry == NULL)
4259 break;
4260 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4261 break;
4262 case 'T':
4263 view->count = 0;
4264 if (s->selected_entry == NULL)
4265 break;
4266 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4267 break;
4268 case KEY_BACKSPACE:
4269 case CTRL('l'):
4270 case 'B':
4271 view->count = 0;
4272 if (ch == KEY_BACKSPACE &&
4273 got_path_is_root_dir(s->in_repo_path))
4274 break;
4275 err = stop_log_thread(s);
4276 if (err)
4277 return err;
4278 if (ch == KEY_BACKSPACE) {
4279 char *parent_path;
4280 err = got_path_dirname(&parent_path, s->in_repo_path);
4281 if (err)
4282 return err;
4283 free(s->in_repo_path);
4284 s->in_repo_path = parent_path;
4285 s->thread_args.in_repo_path = s->in_repo_path;
4286 } else if (ch == CTRL('l')) {
4287 struct got_object_id *start_id;
4288 err = got_repo_match_object_id(&start_id, NULL,
4289 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4290 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4291 if (err) {
4292 if (s->head_ref_name == NULL ||
4293 err->code != GOT_ERR_NOT_REF)
4294 return err;
4295 /* Try to cope with deleted references. */
4296 free(s->head_ref_name);
4297 s->head_ref_name = NULL;
4298 err = got_repo_match_object_id(&start_id,
4299 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4300 &tog_refs, s->repo);
4301 if (err)
4302 return err;
4304 free(s->start_id);
4305 s->start_id = start_id;
4306 s->thread_args.start_id = s->start_id;
4307 } else /* 'B' */
4308 s->log_branches = !s->log_branches;
4310 if (s->thread_args.pack_fds == NULL) {
4311 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4312 if (err)
4313 return err;
4315 err = got_repo_open(&s->thread_args.repo,
4316 got_repo_get_path(s->repo), NULL,
4317 s->thread_args.pack_fds);
4318 if (err)
4319 return err;
4320 tog_free_refs();
4321 err = tog_load_refs(s->repo, 0);
4322 if (err)
4323 return err;
4324 err = got_commit_graph_open(&s->thread_args.graph,
4325 s->in_repo_path, !s->log_branches);
4326 if (err)
4327 return err;
4328 err = got_commit_graph_bfsort(s->thread_args.graph,
4329 s->start_id, s->repo, NULL, NULL);
4330 if (err)
4331 return err;
4332 free_commits(&s->real_commits);
4333 free_commits(&s->limit_commits);
4334 s->first_displayed_entry = NULL;
4335 s->last_displayed_entry = NULL;
4336 s->selected_entry = NULL;
4337 s->selected = 0;
4338 s->thread_args.log_complete = 0;
4339 s->quit = 0;
4340 s->thread_args.commits_needed = view->lines;
4341 s->matched_entry = NULL;
4342 s->search_entry = NULL;
4343 view->offset = 0;
4344 break;
4345 case 'R':
4346 view->count = 0;
4347 err = view_request_new(new_view, view, TOG_VIEW_REF);
4348 break;
4349 default:
4350 view->count = 0;
4351 break;
4354 return err;
4357 static const struct got_error *
4358 apply_unveil(const char *repo_path, const char *worktree_path)
4360 const struct got_error *error;
4362 #ifdef PROFILE
4363 if (unveil("gmon.out", "rwc") != 0)
4364 return got_error_from_errno2("unveil", "gmon.out");
4365 #endif
4366 if (repo_path && unveil(repo_path, "r") != 0)
4367 return got_error_from_errno2("unveil", repo_path);
4369 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4370 return got_error_from_errno2("unveil", worktree_path);
4372 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4373 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4375 error = got_privsep_unveil_exec_helpers();
4376 if (error != NULL)
4377 return error;
4379 if (unveil(NULL, NULL) != 0)
4380 return got_error_from_errno("unveil");
4382 return NULL;
4385 static const struct got_error *
4386 init_mock_term(const char *test_script_path)
4388 const struct got_error *err = NULL;
4389 const char *screen_dump_path;
4390 int in;
4392 if (test_script_path == NULL || *test_script_path == '\0')
4393 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4395 tog_io.f = fopen(test_script_path, "re");
4396 if (tog_io.f == NULL) {
4397 err = got_error_from_errno_fmt("fopen: %s",
4398 test_script_path);
4399 goto done;
4402 /* test mode, we don't want any output */
4403 tog_io.cout = fopen("/dev/null", "w+");
4404 if (tog_io.cout == NULL) {
4405 err = got_error_from_errno2("fopen", "/dev/null");
4406 goto done;
4409 in = dup(fileno(tog_io.cout));
4410 if (in == -1) {
4411 err = got_error_from_errno("dup");
4412 goto done;
4414 tog_io.cin = fdopen(in, "r");
4415 if (tog_io.cin == NULL) {
4416 err = got_error_from_errno("fdopen");
4417 close(in);
4418 goto done;
4421 screen_dump_path = getenv("TOG_SCR_DUMP");
4422 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4423 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4424 tog_io.sdump = fopen(screen_dump_path, "we");
4425 if (tog_io.sdump == NULL) {
4426 err = got_error_from_errno2("fopen", screen_dump_path);
4427 goto done;
4430 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4431 err = got_error_from_errno("fseeko");
4432 goto done;
4435 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4436 err = got_error_msg(GOT_ERR_IO,
4437 "newterm: failed to initialise curses");
4439 using_mock_io = 1;
4441 done:
4442 if (err)
4443 tog_io_close();
4444 return err;
4447 static void
4448 init_curses(void)
4450 if (using_mock_io) /* In test mode we use a fake terminal */
4451 return;
4453 initscr();
4455 cbreak();
4456 halfdelay(1); /* Fast refresh while initial view is loading. */
4457 noecho();
4458 nonl();
4459 intrflush(stdscr, FALSE);
4460 keypad(stdscr, TRUE);
4461 curs_set(0);
4462 if (getenv("TOG_COLORS") != NULL) {
4463 start_color();
4464 use_default_colors();
4467 return;
4470 static const struct got_error *
4471 set_tog_base_commit(struct got_repository *repo, struct got_worktree *worktree)
4473 tog_base_commit.id = got_object_id_dup(
4474 got_worktree_get_base_commit_id(worktree));
4475 if (tog_base_commit.id == NULL)
4476 return got_error_from_errno( "got_object_id_dup");
4478 return NULL;
4481 static const struct got_error *
4482 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4483 struct got_repository *repo, struct got_worktree *worktree)
4485 const struct got_error *err = NULL;
4487 if (argc == 0) {
4488 *in_repo_path = strdup("/");
4489 if (*in_repo_path == NULL)
4490 return got_error_from_errno("strdup");
4491 return NULL;
4494 if (worktree) {
4495 const char *prefix = got_worktree_get_path_prefix(worktree);
4496 char *p;
4498 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4499 if (err)
4500 return err;
4501 if (asprintf(in_repo_path, "%s%s%s", prefix,
4502 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4503 p) == -1) {
4504 err = got_error_from_errno("asprintf");
4505 *in_repo_path = NULL;
4507 free(p);
4508 } else
4509 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4511 return err;
4514 static const struct got_error *
4515 cmd_log(int argc, char *argv[])
4517 const struct got_error *error;
4518 struct got_repository *repo = NULL;
4519 struct got_worktree *worktree = NULL;
4520 struct got_object_id *start_id = NULL;
4521 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4522 char *keyword_idstr = NULL, *start_commit = NULL, *label = NULL;
4523 struct got_reference *ref = NULL;
4524 const char *head_ref_name = NULL;
4525 int ch, log_branches = 0;
4526 struct tog_view *view;
4527 int *pack_fds = NULL;
4529 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4530 switch (ch) {
4531 case 'b':
4532 log_branches = 1;
4533 break;
4534 case 'c':
4535 start_commit = optarg;
4536 break;
4537 case 'r':
4538 repo_path = realpath(optarg, NULL);
4539 if (repo_path == NULL)
4540 return got_error_from_errno2("realpath",
4541 optarg);
4542 break;
4543 default:
4544 usage_log();
4545 /* NOTREACHED */
4549 argc -= optind;
4550 argv += optind;
4552 if (argc > 1)
4553 usage_log();
4555 error = got_repo_pack_fds_open(&pack_fds);
4556 if (error != NULL)
4557 goto done;
4559 if (repo_path == NULL) {
4560 cwd = getcwd(NULL, 0);
4561 if (cwd == NULL) {
4562 error = got_error_from_errno("getcwd");
4563 goto done;
4565 error = got_worktree_open(&worktree, cwd, NULL);
4566 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4567 goto done;
4568 if (worktree)
4569 repo_path =
4570 strdup(got_worktree_get_repo_path(worktree));
4571 else
4572 repo_path = strdup(cwd);
4573 if (repo_path == NULL) {
4574 error = got_error_from_errno("strdup");
4575 goto done;
4579 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4580 if (error != NULL)
4581 goto done;
4583 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4584 repo, worktree);
4585 if (error)
4586 goto done;
4588 init_curses();
4590 error = apply_unveil(got_repo_get_path(repo),
4591 worktree ? got_worktree_get_root_path(worktree) : NULL);
4592 if (error)
4593 goto done;
4595 /* already loaded by tog_log_with_path()? */
4596 if (TAILQ_EMPTY(&tog_refs)) {
4597 error = tog_load_refs(repo, 0);
4598 if (error)
4599 goto done;
4602 if (start_commit == NULL) {
4603 error = got_repo_match_object_id(&start_id, &label,
4604 worktree ? got_worktree_get_head_ref_name(worktree) :
4605 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4606 if (error)
4607 goto done;
4608 head_ref_name = label;
4609 } else {
4610 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4611 repo, worktree);
4612 if (error != NULL)
4613 goto done;
4614 if (keyword_idstr != NULL)
4615 start_commit = keyword_idstr;
4617 error = got_ref_open(&ref, repo, start_commit, 0);
4618 if (error == NULL)
4619 head_ref_name = got_ref_get_name(ref);
4620 else if (error->code != GOT_ERR_NOT_REF)
4621 goto done;
4622 error = got_repo_match_object_id(&start_id, NULL,
4623 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4624 if (error)
4625 goto done;
4628 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4629 if (view == NULL) {
4630 error = got_error_from_errno("view_open");
4631 goto done;
4634 if (worktree) {
4635 error = set_tog_base_commit(repo, worktree);
4636 if (error != NULL)
4637 goto done;
4640 error = open_log_view(view, start_id, repo, head_ref_name,
4641 in_repo_path, log_branches, worktree);
4642 if (error)
4643 goto done;
4645 if (worktree) {
4646 /* The work tree will be closed by the log thread. */
4647 worktree = NULL;
4650 error = view_loop(view);
4652 done:
4653 free(tog_base_commit.id);
4654 free(keyword_idstr);
4655 free(in_repo_path);
4656 free(repo_path);
4657 free(cwd);
4658 free(start_id);
4659 free(label);
4660 if (ref)
4661 got_ref_close(ref);
4662 if (repo) {
4663 const struct got_error *close_err = got_repo_close(repo);
4664 if (error == NULL)
4665 error = close_err;
4667 if (worktree)
4668 got_worktree_close(worktree);
4669 if (pack_fds) {
4670 const struct got_error *pack_err =
4671 got_repo_pack_fds_close(pack_fds);
4672 if (error == NULL)
4673 error = pack_err;
4675 tog_free_refs();
4676 return error;
4679 __dead static void
4680 usage_diff(void)
4682 endwin();
4683 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4684 "object1 object2\n", getprogname());
4685 exit(1);
4688 static int
4689 match_line(const char *line, regex_t *regex, size_t nmatch,
4690 regmatch_t *regmatch)
4692 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4695 static struct tog_color *
4696 match_color(struct tog_colors *colors, const char *line)
4698 struct tog_color *tc = NULL;
4700 STAILQ_FOREACH(tc, colors, entry) {
4701 if (match_line(line, &tc->regex, 0, NULL))
4702 return tc;
4705 return NULL;
4708 static const struct got_error *
4709 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4710 WINDOW *window, int skipcol, regmatch_t *regmatch)
4712 const struct got_error *err = NULL;
4713 char *exstr = NULL;
4714 wchar_t *wline = NULL;
4715 int rme, rms, n, width, scrollx;
4716 int width0 = 0, width1 = 0, width2 = 0;
4717 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4719 *wtotal = 0;
4721 rms = regmatch->rm_so;
4722 rme = regmatch->rm_eo;
4724 err = expand_tab(&exstr, line);
4725 if (err)
4726 return err;
4728 /* Split the line into 3 segments, according to match offsets. */
4729 seg0 = strndup(exstr, rms);
4730 if (seg0 == NULL) {
4731 err = got_error_from_errno("strndup");
4732 goto done;
4734 seg1 = strndup(exstr + rms, rme - rms);
4735 if (seg1 == NULL) {
4736 err = got_error_from_errno("strndup");
4737 goto done;
4739 seg2 = strdup(exstr + rme);
4740 if (seg2 == NULL) {
4741 err = got_error_from_errno("strndup");
4742 goto done;
4745 /* draw up to matched token if we haven't scrolled past it */
4746 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4747 col_tab_align, 1);
4748 if (err)
4749 goto done;
4750 n = MAX(width0 - skipcol, 0);
4751 if (n) {
4752 free(wline);
4753 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4754 wlimit, col_tab_align, 1);
4755 if (err)
4756 goto done;
4757 waddwstr(window, &wline[scrollx]);
4758 wlimit -= width;
4759 *wtotal += width;
4762 if (wlimit > 0) {
4763 int i = 0, w = 0;
4764 size_t wlen;
4766 free(wline);
4767 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4768 col_tab_align, 1);
4769 if (err)
4770 goto done;
4771 wlen = wcslen(wline);
4772 while (i < wlen) {
4773 width = wcwidth(wline[i]);
4774 if (width == -1) {
4775 /* should not happen, tabs are expanded */
4776 err = got_error(GOT_ERR_RANGE);
4777 goto done;
4779 if (width0 + w + width > skipcol)
4780 break;
4781 w += width;
4782 i++;
4784 /* draw (visible part of) matched token (if scrolled into it) */
4785 if (width1 - w > 0) {
4786 wattron(window, A_STANDOUT);
4787 waddwstr(window, &wline[i]);
4788 wattroff(window, A_STANDOUT);
4789 wlimit -= (width1 - w);
4790 *wtotal += (width1 - w);
4794 if (wlimit > 0) { /* draw rest of line */
4795 free(wline);
4796 if (skipcol > width0 + width1) {
4797 err = format_line(&wline, &width2, &scrollx, seg2,
4798 skipcol - (width0 + width1), wlimit,
4799 col_tab_align, 1);
4800 if (err)
4801 goto done;
4802 waddwstr(window, &wline[scrollx]);
4803 } else {
4804 err = format_line(&wline, &width2, NULL, seg2, 0,
4805 wlimit, col_tab_align, 1);
4806 if (err)
4807 goto done;
4808 waddwstr(window, wline);
4810 *wtotal += width2;
4812 done:
4813 free(wline);
4814 free(exstr);
4815 free(seg0);
4816 free(seg1);
4817 free(seg2);
4818 return err;
4821 static int
4822 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4824 FILE *f = NULL;
4825 int *eof, *first, *selected;
4827 if (view->type == TOG_VIEW_DIFF) {
4828 struct tog_diff_view_state *s = &view->state.diff;
4830 first = &s->first_displayed_line;
4831 selected = first;
4832 eof = &s->eof;
4833 f = s->f;
4834 } else if (view->type == TOG_VIEW_HELP) {
4835 struct tog_help_view_state *s = &view->state.help;
4837 first = &s->first_displayed_line;
4838 selected = first;
4839 eof = &s->eof;
4840 f = s->f;
4841 } else if (view->type == TOG_VIEW_BLAME) {
4842 struct tog_blame_view_state *s = &view->state.blame;
4844 first = &s->first_displayed_line;
4845 selected = &s->selected_line;
4846 eof = &s->eof;
4847 f = s->blame.f;
4848 } else
4849 return 0;
4851 /* Center gline in the middle of the page like vi(1). */
4852 if (*lineno < view->gline - (view->nlines - 3) / 2)
4853 return 0;
4854 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4855 rewind(f);
4856 *eof = 0;
4857 *first = 1;
4858 *lineno = 0;
4859 *nprinted = 0;
4860 return 0;
4863 *selected = view->gline <= (view->nlines - 3) / 2 ?
4864 view->gline : (view->nlines - 3) / 2 + 1;
4865 view->gline = 0;
4867 return 1;
4870 static const struct got_error *
4871 draw_file(struct tog_view *view, const char *header)
4873 struct tog_diff_view_state *s = &view->state.diff;
4874 regmatch_t *regmatch = &view->regmatch;
4875 const struct got_error *err;
4876 int nprinted = 0;
4877 char *line;
4878 size_t linesize = 0;
4879 ssize_t linelen;
4880 wchar_t *wline;
4881 int width;
4882 int max_lines = view->nlines;
4883 int nlines = s->nlines;
4884 off_t line_offset;
4886 s->lineno = s->first_displayed_line - 1;
4887 line_offset = s->lines[s->first_displayed_line - 1].offset;
4888 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4889 return got_error_from_errno("fseek");
4891 werase(view->window);
4893 if (view->gline > s->nlines - 1)
4894 view->gline = s->nlines - 1;
4896 if (header) {
4897 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4898 1 : view->gline - (view->nlines - 3) / 2 :
4899 s->lineno + s->selected_line;
4901 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4902 return got_error_from_errno("asprintf");
4903 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4904 0, 0);
4905 free(line);
4906 if (err)
4907 return err;
4909 if (view_needs_focus_indication(view))
4910 wstandout(view->window);
4911 waddwstr(view->window, wline);
4912 free(wline);
4913 wline = NULL;
4914 while (width++ < view->ncols)
4915 waddch(view->window, ' ');
4916 if (view_needs_focus_indication(view))
4917 wstandend(view->window);
4919 if (max_lines <= 1)
4920 return NULL;
4921 max_lines--;
4924 s->eof = 0;
4925 view->maxx = 0;
4926 line = NULL;
4927 while (max_lines > 0 && nprinted < max_lines) {
4928 enum got_diff_line_type linetype;
4929 attr_t attr = 0;
4931 linelen = getline(&line, &linesize, s->f);
4932 if (linelen == -1) {
4933 if (feof(s->f)) {
4934 s->eof = 1;
4935 break;
4937 free(line);
4938 return got_ferror(s->f, GOT_ERR_IO);
4941 if (++s->lineno < s->first_displayed_line)
4942 continue;
4943 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4944 continue;
4945 if (s->lineno == view->hiline)
4946 attr = A_STANDOUT;
4948 /* Set view->maxx based on full line length. */
4949 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4950 view->x ? 1 : 0);
4951 if (err) {
4952 free(line);
4953 return err;
4955 view->maxx = MAX(view->maxx, width);
4956 free(wline);
4957 wline = NULL;
4959 linetype = s->lines[s->lineno].type;
4960 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4961 linetype < GOT_DIFF_LINE_CONTEXT)
4962 attr |= COLOR_PAIR(linetype);
4963 if (attr)
4964 wattron(view->window, attr);
4965 if (s->first_displayed_line + nprinted == s->matched_line &&
4966 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4967 err = add_matched_line(&width, line, view->ncols, 0,
4968 view->window, view->x, regmatch);
4969 if (err) {
4970 free(line);
4971 return err;
4973 } else {
4974 int skip;
4975 err = format_line(&wline, &width, &skip, line,
4976 view->x, view->ncols, 0, view->x ? 1 : 0);
4977 if (err) {
4978 free(line);
4979 return err;
4981 waddwstr(view->window, &wline[skip]);
4982 free(wline);
4983 wline = NULL;
4985 if (s->lineno == view->hiline) {
4986 /* highlight full gline length */
4987 while (width++ < view->ncols)
4988 waddch(view->window, ' ');
4989 } else {
4990 if (width <= view->ncols - 1)
4991 waddch(view->window, '\n');
4993 if (attr)
4994 wattroff(view->window, attr);
4995 if (++nprinted == 1)
4996 s->first_displayed_line = s->lineno;
4998 free(line);
4999 if (nprinted >= 1)
5000 s->last_displayed_line = s->first_displayed_line +
5001 (nprinted - 1);
5002 else
5003 s->last_displayed_line = s->first_displayed_line;
5005 view_border(view);
5007 if (s->eof) {
5008 while (nprinted < view->nlines) {
5009 waddch(view->window, '\n');
5010 nprinted++;
5013 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
5014 view->ncols, 0, 0);
5015 if (err) {
5016 return err;
5019 wstandout(view->window);
5020 waddwstr(view->window, wline);
5021 free(wline);
5022 wline = NULL;
5023 wstandend(view->window);
5026 return NULL;
5029 static char *
5030 get_datestr(time_t *time, char *datebuf)
5032 struct tm mytm, *tm;
5033 char *p, *s;
5035 tm = gmtime_r(time, &mytm);
5036 if (tm == NULL)
5037 return NULL;
5038 s = asctime_r(tm, datebuf);
5039 if (s == NULL)
5040 return NULL;
5041 p = strchr(s, '\n');
5042 if (p)
5043 *p = '\0';
5044 return s;
5047 static const struct got_error *
5048 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
5049 off_t off, uint8_t type)
5051 struct got_diff_line *p;
5053 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
5054 if (p == NULL)
5055 return got_error_from_errno("reallocarray");
5056 *lines = p;
5057 (*lines)[*nlines].offset = off;
5058 (*lines)[*nlines].type = type;
5059 (*nlines)++;
5061 return NULL;
5064 static const struct got_error *
5065 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
5066 struct got_diff_line *s_lines, size_t s_nlines)
5068 struct got_diff_line *p;
5069 char buf[BUFSIZ];
5070 size_t i, r;
5072 if (fseeko(src, 0L, SEEK_SET) == -1)
5073 return got_error_from_errno("fseeko");
5075 for (;;) {
5076 r = fread(buf, 1, sizeof(buf), src);
5077 if (r == 0) {
5078 if (ferror(src))
5079 return got_error_from_errno("fread");
5080 if (feof(src))
5081 break;
5083 if (fwrite(buf, 1, r, dst) != r)
5084 return got_ferror(dst, GOT_ERR_IO);
5087 if (s_nlines == 0 && *d_nlines == 0)
5088 return NULL;
5091 * If commit info was in dst, increment line offsets
5092 * of the appended diff content, but skip s_lines[0]
5093 * because offset zero is already in *d_lines.
5095 if (*d_nlines > 0) {
5096 for (i = 1; i < s_nlines; ++i)
5097 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
5099 if (s_nlines > 0) {
5100 --s_nlines;
5101 ++s_lines;
5105 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
5106 if (p == NULL) {
5107 /* d_lines is freed in close_diff_view() */
5108 return got_error_from_errno("reallocarray");
5111 *d_lines = p;
5113 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
5114 *d_nlines += s_nlines;
5116 return NULL;
5119 static const struct got_error *
5120 write_commit_info(struct got_diff_line **lines, size_t *nlines,
5121 struct got_object_id *commit_id, struct got_reflist_head *refs,
5122 struct got_repository *repo, int ignore_ws, int force_text_diff,
5123 struct got_diffstat_cb_arg *dsa, FILE *outfile)
5125 const struct got_error *err = NULL;
5126 char datebuf[26], *datestr;
5127 struct got_commit_object *commit;
5128 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
5129 time_t committer_time;
5130 const char *author, *committer;
5131 char *refs_str = NULL;
5132 struct got_pathlist_entry *pe;
5133 off_t outoff = 0;
5134 int n;
5136 err = build_refs_str(&refs_str, refs, commit_id, repo);
5137 if (err)
5138 return err;
5140 err = got_object_open_as_commit(&commit, repo, commit_id);
5141 if (err)
5142 return err;
5144 err = got_object_id_str(&id_str, commit_id);
5145 if (err) {
5146 err = got_error_from_errno("got_object_id_str");
5147 goto done;
5150 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
5151 if (err)
5152 goto done;
5154 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
5155 refs_str ? refs_str : "", refs_str ? ")" : "");
5156 if (n < 0) {
5157 err = got_error_from_errno("fprintf");
5158 goto done;
5160 outoff += n;
5161 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
5162 if (err)
5163 goto done;
5165 n = fprintf(outfile, "from: %s\n",
5166 got_object_commit_get_author(commit));
5167 if (n < 0) {
5168 err = got_error_from_errno("fprintf");
5169 goto done;
5171 outoff += n;
5172 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
5173 if (err)
5174 goto done;
5176 author = got_object_commit_get_author(commit);
5177 committer = got_object_commit_get_committer(commit);
5178 if (strcmp(author, committer) != 0) {
5179 n = fprintf(outfile, "via: %s\n", committer);
5180 if (n < 0) {
5181 err = got_error_from_errno("fprintf");
5182 goto done;
5184 outoff += n;
5185 err = add_line_metadata(lines, nlines, outoff,
5186 GOT_DIFF_LINE_AUTHOR);
5187 if (err)
5188 goto done;
5190 committer_time = got_object_commit_get_committer_time(commit);
5191 datestr = get_datestr(&committer_time, datebuf);
5192 if (datestr) {
5193 n = fprintf(outfile, "date: %s UTC\n", datestr);
5194 if (n < 0) {
5195 err = got_error_from_errno("fprintf");
5196 goto done;
5198 outoff += n;
5199 err = add_line_metadata(lines, nlines, outoff,
5200 GOT_DIFF_LINE_DATE);
5201 if (err)
5202 goto done;
5204 if (got_object_commit_get_nparents(commit) > 1) {
5205 const struct got_object_id_queue *parent_ids;
5206 struct got_object_qid *qid;
5207 int pn = 1;
5208 parent_ids = got_object_commit_get_parent_ids(commit);
5209 STAILQ_FOREACH(qid, parent_ids, entry) {
5210 err = got_object_id_str(&id_str, &qid->id);
5211 if (err)
5212 goto done;
5213 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5214 if (n < 0) {
5215 err = got_error_from_errno("fprintf");
5216 goto done;
5218 outoff += n;
5219 err = add_line_metadata(lines, nlines, outoff,
5220 GOT_DIFF_LINE_META);
5221 if (err)
5222 goto done;
5223 free(id_str);
5224 id_str = NULL;
5228 err = got_object_commit_get_logmsg(&logmsg, commit);
5229 if (err)
5230 goto done;
5231 s = logmsg;
5232 while ((line = strsep(&s, "\n")) != NULL) {
5233 n = fprintf(outfile, "%s\n", line);
5234 if (n < 0) {
5235 err = got_error_from_errno("fprintf");
5236 goto done;
5238 outoff += n;
5239 err = add_line_metadata(lines, nlines, outoff,
5240 GOT_DIFF_LINE_LOGMSG);
5241 if (err)
5242 goto done;
5245 TAILQ_FOREACH(pe, dsa->paths, entry) {
5246 struct got_diff_changed_path *cp = pe->data;
5247 int pad = dsa->max_path_len - pe->path_len + 1;
5249 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5250 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5251 dsa->rm_cols + 1, cp->rm);
5252 if (n < 0) {
5253 err = got_error_from_errno("fprintf");
5254 goto done;
5256 outoff += n;
5257 err = add_line_metadata(lines, nlines, outoff,
5258 GOT_DIFF_LINE_CHANGES);
5259 if (err)
5260 goto done;
5263 fputc('\n', outfile);
5264 outoff++;
5265 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5266 if (err)
5267 goto done;
5269 n = fprintf(outfile,
5270 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5271 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5272 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5273 if (n < 0) {
5274 err = got_error_from_errno("fprintf");
5275 goto done;
5277 outoff += n;
5278 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5279 if (err)
5280 goto done;
5282 fputc('\n', outfile);
5283 outoff++;
5284 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5285 done:
5286 free(id_str);
5287 free(logmsg);
5288 free(refs_str);
5289 got_object_commit_close(commit);
5290 if (err) {
5291 free(*lines);
5292 *lines = NULL;
5293 *nlines = 0;
5295 return err;
5298 static const struct got_error *
5299 create_diff(struct tog_diff_view_state *s)
5301 const struct got_error *err = NULL;
5302 FILE *tmp_diff_file = NULL;
5303 int obj_type;
5304 struct got_diff_line *lines = NULL;
5305 struct got_pathlist_head changed_paths;
5306 struct got_commit_object *commit2 = NULL;
5308 TAILQ_INIT(&changed_paths);
5310 free(s->lines);
5311 s->lines = malloc(sizeof(*s->lines));
5312 if (s->lines == NULL)
5313 return got_error_from_errno("malloc");
5314 s->nlines = 0;
5316 if (s->f && fclose(s->f) == EOF) {
5317 s->f = NULL;
5318 return got_error_from_errno("fclose");
5321 s->f = got_opentemp();
5322 if (s->f == NULL)
5323 return got_error_from_errno("got_opentemp");
5325 tmp_diff_file = got_opentemp();
5326 if (tmp_diff_file == NULL)
5327 return got_error_from_errno("got_opentemp");
5329 if (s->id1)
5330 err = got_object_get_type(&obj_type, s->repo, s->id1);
5331 else
5332 err = got_object_get_type(&obj_type, s->repo, s->id2);
5333 if (err)
5334 goto done;
5336 switch (obj_type) {
5337 case GOT_OBJ_TYPE_BLOB:
5338 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5339 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5340 s->label1, s->label2, tog_diff_algo, s->diff_context,
5341 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5342 s->f);
5343 break;
5344 case GOT_OBJ_TYPE_TREE:
5345 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5346 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5347 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5348 s->force_text_diff, NULL, s->repo, s->f);
5349 break;
5350 case GOT_OBJ_TYPE_COMMIT: {
5351 const struct got_object_id_queue *parent_ids;
5352 struct got_object_qid *pid;
5353 struct got_reflist_head *refs;
5354 size_t nlines = 0;
5355 struct got_diffstat_cb_arg dsa = {
5356 0, 0, 0, 0, 0, 0,
5357 &changed_paths,
5358 s->ignore_whitespace,
5359 s->force_text_diff,
5360 tog_diff_algo
5363 lines = malloc(sizeof(*lines));
5364 if (lines == NULL) {
5365 err = got_error_from_errno("malloc");
5366 goto done;
5369 /* build diff first in tmp file then append to commit info */
5370 err = got_diff_objects_as_commits(&lines, &nlines,
5371 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5372 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5373 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5374 if (err)
5375 break;
5377 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5378 /* Show commit info if we're diffing to a parent/root commit. */
5379 if (s->id1 == NULL) {
5380 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5381 refs, s->repo, s->ignore_whitespace,
5382 s->force_text_diff, &dsa, s->f);
5383 if (err)
5384 goto done;
5385 } else {
5386 err = got_object_open_as_commit(&commit2, s->repo,
5387 s->id2);
5388 if (err)
5389 goto done;
5391 parent_ids = got_object_commit_get_parent_ids(commit2);
5392 STAILQ_FOREACH(pid, parent_ids, entry) {
5393 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5394 err = write_commit_info(&s->lines,
5395 &s->nlines, s->id2, refs, s->repo,
5396 s->ignore_whitespace,
5397 s->force_text_diff, &dsa, s->f);
5398 if (err)
5399 goto done;
5400 break;
5405 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5406 lines, nlines);
5407 break;
5409 default:
5410 err = got_error(GOT_ERR_OBJ_TYPE);
5411 break;
5413 done:
5414 free(lines);
5415 if (commit2 != NULL)
5416 got_object_commit_close(commit2);
5417 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5418 if (s->f && fflush(s->f) != 0 && err == NULL)
5419 err = got_error_from_errno("fflush");
5420 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5421 err = got_error_from_errno("fclose");
5422 return err;
5425 static void
5426 diff_view_indicate_progress(struct tog_view *view)
5428 mvwaddstr(view->window, 0, 0, "diffing...");
5429 update_panels();
5430 doupdate();
5433 static const struct got_error *
5434 search_start_diff_view(struct tog_view *view)
5436 struct tog_diff_view_state *s = &view->state.diff;
5438 s->matched_line = 0;
5439 return NULL;
5442 static void
5443 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5444 size_t *nlines, int **first, int **last, int **match, int **selected)
5446 struct tog_diff_view_state *s = &view->state.diff;
5448 *f = s->f;
5449 *nlines = s->nlines;
5450 *line_offsets = NULL;
5451 *match = &s->matched_line;
5452 *first = &s->first_displayed_line;
5453 *last = &s->last_displayed_line;
5454 *selected = &s->selected_line;
5457 static const struct got_error *
5458 search_next_view_match(struct tog_view *view)
5460 const struct got_error *err = NULL;
5461 FILE *f;
5462 int lineno;
5463 char *line = NULL;
5464 size_t linesize = 0;
5465 ssize_t linelen;
5466 off_t *line_offsets;
5467 size_t nlines = 0;
5468 int *first, *last, *match, *selected;
5470 if (!view->search_setup)
5471 return got_error_msg(GOT_ERR_NOT_IMPL,
5472 "view search not supported");
5473 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5474 &match, &selected);
5476 if (!view->searching) {
5477 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5478 return NULL;
5481 if (*match) {
5482 if (view->searching == TOG_SEARCH_FORWARD)
5483 lineno = *first + 1;
5484 else
5485 lineno = *first - 1;
5486 } else
5487 lineno = *first - 1 + *selected;
5489 while (1) {
5490 off_t offset;
5492 if (lineno <= 0 || lineno > nlines) {
5493 if (*match == 0) {
5494 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5495 break;
5498 if (view->searching == TOG_SEARCH_FORWARD)
5499 lineno = 1;
5500 else
5501 lineno = nlines;
5504 offset = view->type == TOG_VIEW_DIFF ?
5505 view->state.diff.lines[lineno - 1].offset :
5506 line_offsets[lineno - 1];
5507 if (fseeko(f, offset, SEEK_SET) != 0) {
5508 free(line);
5509 return got_error_from_errno("fseeko");
5511 linelen = getline(&line, &linesize, f);
5512 if (linelen != -1) {
5513 char *exstr;
5514 err = expand_tab(&exstr, line);
5515 if (err)
5516 break;
5517 if (match_line(exstr, &view->regex, 1,
5518 &view->regmatch)) {
5519 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5520 *match = lineno;
5521 free(exstr);
5522 break;
5524 free(exstr);
5526 if (view->searching == TOG_SEARCH_FORWARD)
5527 lineno++;
5528 else
5529 lineno--;
5531 free(line);
5533 if (*match) {
5534 *first = *match;
5535 *selected = 1;
5538 return err;
5541 static const struct got_error *
5542 close_diff_view(struct tog_view *view)
5544 const struct got_error *err = NULL;
5545 struct tog_diff_view_state *s = &view->state.diff;
5547 free(s->id1);
5548 s->id1 = NULL;
5549 free(s->id2);
5550 s->id2 = NULL;
5551 if (s->f && fclose(s->f) == EOF)
5552 err = got_error_from_errno("fclose");
5553 s->f = NULL;
5554 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5555 err = got_error_from_errno("fclose");
5556 s->f1 = NULL;
5557 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5558 err = got_error_from_errno("fclose");
5559 s->f2 = NULL;
5560 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5561 err = got_error_from_errno("close");
5562 s->fd1 = -1;
5563 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5564 err = got_error_from_errno("close");
5565 s->fd2 = -1;
5566 free(s->lines);
5567 s->lines = NULL;
5568 s->nlines = 0;
5569 return err;
5572 static const struct got_error *
5573 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5574 struct got_object_id *id2, const char *label1, const char *label2,
5575 int diff_context, int ignore_whitespace, int force_text_diff,
5576 struct tog_view *parent_view, struct got_repository *repo)
5578 const struct got_error *err;
5579 struct tog_diff_view_state *s = &view->state.diff;
5581 memset(s, 0, sizeof(*s));
5582 s->fd1 = -1;
5583 s->fd2 = -1;
5585 if (id1 != NULL && id2 != NULL) {
5586 int type1, type2;
5588 err = got_object_get_type(&type1, repo, id1);
5589 if (err)
5590 goto done;
5591 err = got_object_get_type(&type2, repo, id2);
5592 if (err)
5593 goto done;
5595 if (type1 != type2) {
5596 err = got_error(GOT_ERR_OBJ_TYPE);
5597 goto done;
5600 s->first_displayed_line = 1;
5601 s->last_displayed_line = view->nlines;
5602 s->selected_line = 1;
5603 s->repo = repo;
5604 s->label1 = label1;
5605 s->label2 = label2;
5607 if (id1) {
5608 s->id1 = got_object_id_dup(id1);
5609 if (s->id1 == NULL) {
5610 err = got_error_from_errno("got_object_id_dup");
5611 goto done;
5613 } else
5614 s->id1 = NULL;
5616 s->id2 = got_object_id_dup(id2);
5617 if (s->id2 == NULL) {
5618 err = got_error_from_errno("got_object_id_dup");
5619 goto done;
5622 s->f1 = got_opentemp();
5623 if (s->f1 == NULL) {
5624 err = got_error_from_errno("got_opentemp");
5625 goto done;
5628 s->f2 = got_opentemp();
5629 if (s->f2 == NULL) {
5630 err = got_error_from_errno("got_opentemp");
5631 goto done;
5634 s->fd1 = got_opentempfd();
5635 if (s->fd1 == -1) {
5636 err = got_error_from_errno("got_opentempfd");
5637 goto done;
5640 s->fd2 = got_opentempfd();
5641 if (s->fd2 == -1) {
5642 err = got_error_from_errno("got_opentempfd");
5643 goto done;
5646 s->diff_context = diff_context;
5647 s->ignore_whitespace = ignore_whitespace;
5648 s->force_text_diff = force_text_diff;
5649 s->parent_view = parent_view;
5650 s->repo = repo;
5652 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5653 int rc;
5655 rc = init_pair(GOT_DIFF_LINE_MINUS,
5656 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5657 if (rc != ERR)
5658 rc = init_pair(GOT_DIFF_LINE_PLUS,
5659 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5660 if (rc != ERR)
5661 rc = init_pair(GOT_DIFF_LINE_HUNK,
5662 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5663 if (rc != ERR)
5664 rc = init_pair(GOT_DIFF_LINE_META,
5665 get_color_value("TOG_COLOR_DIFF_META"), -1);
5666 if (rc != ERR)
5667 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5668 get_color_value("TOG_COLOR_DIFF_META"), -1);
5669 if (rc != ERR)
5670 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5671 get_color_value("TOG_COLOR_DIFF_META"), -1);
5672 if (rc != ERR)
5673 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5674 get_color_value("TOG_COLOR_DIFF_META"), -1);
5675 if (rc != ERR)
5676 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5677 get_color_value("TOG_COLOR_AUTHOR"), -1);
5678 if (rc != ERR)
5679 rc = init_pair(GOT_DIFF_LINE_DATE,
5680 get_color_value("TOG_COLOR_DATE"), -1);
5681 if (rc == ERR) {
5682 err = got_error(GOT_ERR_RANGE);
5683 goto done;
5687 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5688 view_is_splitscreen(view))
5689 show_log_view(parent_view); /* draw border */
5690 diff_view_indicate_progress(view);
5692 err = create_diff(s);
5694 view->show = show_diff_view;
5695 view->input = input_diff_view;
5696 view->reset = reset_diff_view;
5697 view->close = close_diff_view;
5698 view->search_start = search_start_diff_view;
5699 view->search_setup = search_setup_diff_view;
5700 view->search_next = search_next_view_match;
5701 done:
5702 if (err) {
5703 if (view->close == NULL)
5704 close_diff_view(view);
5705 view_close(view);
5707 return err;
5710 static const struct got_error *
5711 show_diff_view(struct tog_view *view)
5713 const struct got_error *err;
5714 struct tog_diff_view_state *s = &view->state.diff;
5715 char *id_str1 = NULL, *id_str2, *header;
5716 const char *label1, *label2;
5718 if (s->id1) {
5719 err = got_object_id_str(&id_str1, s->id1);
5720 if (err)
5721 return err;
5722 label1 = s->label1 ? s->label1 : id_str1;
5723 } else
5724 label1 = "/dev/null";
5726 err = got_object_id_str(&id_str2, s->id2);
5727 if (err)
5728 return err;
5729 label2 = s->label2 ? s->label2 : id_str2;
5731 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5732 err = got_error_from_errno("asprintf");
5733 free(id_str1);
5734 free(id_str2);
5735 return err;
5737 free(id_str1);
5738 free(id_str2);
5740 err = draw_file(view, header);
5741 free(header);
5742 return err;
5745 static const struct got_error *
5746 set_selected_commit(struct tog_diff_view_state *s,
5747 struct commit_queue_entry *entry)
5749 const struct got_error *err;
5750 const struct got_object_id_queue *parent_ids;
5751 struct got_commit_object *selected_commit;
5752 struct got_object_qid *pid;
5754 free(s->id2);
5755 s->id2 = got_object_id_dup(entry->id);
5756 if (s->id2 == NULL)
5757 return got_error_from_errno("got_object_id_dup");
5759 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5760 if (err)
5761 return err;
5762 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5763 free(s->id1);
5764 pid = STAILQ_FIRST(parent_ids);
5765 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5766 got_object_commit_close(selected_commit);
5767 return NULL;
5770 static const struct got_error *
5771 reset_diff_view(struct tog_view *view)
5773 struct tog_diff_view_state *s = &view->state.diff;
5775 view->count = 0;
5776 wclear(view->window);
5777 s->first_displayed_line = 1;
5778 s->last_displayed_line = view->nlines;
5779 s->matched_line = 0;
5780 diff_view_indicate_progress(view);
5781 return create_diff(s);
5784 static void
5785 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5787 int start, i;
5789 i = start = s->first_displayed_line - 1;
5791 while (s->lines[i].type != type) {
5792 if (i == 0)
5793 i = s->nlines - 1;
5794 if (--i == start)
5795 return; /* do nothing, requested type not in file */
5798 s->selected_line = 1;
5799 s->first_displayed_line = i;
5802 static void
5803 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5805 int start, i;
5807 i = start = s->first_displayed_line + 1;
5809 while (s->lines[i].type != type) {
5810 if (i == s->nlines - 1)
5811 i = 0;
5812 if (++i == start)
5813 return; /* do nothing, requested type not in file */
5816 s->selected_line = 1;
5817 s->first_displayed_line = i;
5820 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5821 int, int, int);
5822 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5823 int, int);
5825 static const struct got_error *
5826 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5828 const struct got_error *err = NULL;
5829 struct tog_diff_view_state *s = &view->state.diff;
5830 struct tog_log_view_state *ls;
5831 struct commit_queue_entry *old_selected_entry;
5832 char *line = NULL;
5833 size_t linesize = 0;
5834 ssize_t linelen;
5835 int i, nscroll = view->nlines - 1, up = 0;
5837 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5839 switch (ch) {
5840 case '0':
5841 case '$':
5842 case KEY_RIGHT:
5843 case 'l':
5844 case KEY_LEFT:
5845 case 'h':
5846 horizontal_scroll_input(view, ch);
5847 break;
5848 case 'a':
5849 case 'w':
5850 if (ch == 'a') {
5851 s->force_text_diff = !s->force_text_diff;
5852 view->action = s->force_text_diff ?
5853 "force ASCII text enabled" :
5854 "force ASCII text disabled";
5856 else if (ch == 'w') {
5857 s->ignore_whitespace = !s->ignore_whitespace;
5858 view->action = s->ignore_whitespace ?
5859 "ignore whitespace enabled" :
5860 "ignore whitespace disabled";
5862 err = reset_diff_view(view);
5863 break;
5864 case 'g':
5865 case KEY_HOME:
5866 s->first_displayed_line = 1;
5867 view->count = 0;
5868 break;
5869 case 'G':
5870 case KEY_END:
5871 view->count = 0;
5872 if (s->eof)
5873 break;
5875 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5876 s->eof = 1;
5877 break;
5878 case 'k':
5879 case KEY_UP:
5880 case CTRL('p'):
5881 if (s->first_displayed_line > 1)
5882 s->first_displayed_line--;
5883 else
5884 view->count = 0;
5885 break;
5886 case CTRL('u'):
5887 case 'u':
5888 nscroll /= 2;
5889 /* FALL THROUGH */
5890 case KEY_PPAGE:
5891 case CTRL('b'):
5892 case 'b':
5893 if (s->first_displayed_line == 1) {
5894 view->count = 0;
5895 break;
5897 i = 0;
5898 while (i++ < nscroll && s->first_displayed_line > 1)
5899 s->first_displayed_line--;
5900 break;
5901 case 'j':
5902 case KEY_DOWN:
5903 case CTRL('n'):
5904 if (!s->eof)
5905 s->first_displayed_line++;
5906 else
5907 view->count = 0;
5908 break;
5909 case CTRL('d'):
5910 case 'd':
5911 nscroll /= 2;
5912 /* FALL THROUGH */
5913 case KEY_NPAGE:
5914 case CTRL('f'):
5915 case 'f':
5916 case ' ':
5917 if (s->eof) {
5918 view->count = 0;
5919 break;
5921 i = 0;
5922 while (!s->eof && i++ < nscroll) {
5923 linelen = getline(&line, &linesize, s->f);
5924 s->first_displayed_line++;
5925 if (linelen == -1) {
5926 if (feof(s->f)) {
5927 s->eof = 1;
5928 } else
5929 err = got_ferror(s->f, GOT_ERR_IO);
5930 break;
5933 free(line);
5934 break;
5935 case '(':
5936 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5937 break;
5938 case ')':
5939 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5940 break;
5941 case '{':
5942 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5943 break;
5944 case '}':
5945 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5946 break;
5947 case '[':
5948 if (s->diff_context > 0) {
5949 s->diff_context--;
5950 s->matched_line = 0;
5951 diff_view_indicate_progress(view);
5952 err = create_diff(s);
5953 if (s->first_displayed_line + view->nlines - 1 >
5954 s->nlines) {
5955 s->first_displayed_line = 1;
5956 s->last_displayed_line = view->nlines;
5958 } else
5959 view->count = 0;
5960 break;
5961 case ']':
5962 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5963 s->diff_context++;
5964 s->matched_line = 0;
5965 diff_view_indicate_progress(view);
5966 err = create_diff(s);
5967 } else
5968 view->count = 0;
5969 break;
5970 case '<':
5971 case ',':
5972 case 'K':
5973 up = 1;
5974 /* FALL THROUGH */
5975 case '>':
5976 case '.':
5977 case 'J':
5978 if (s->parent_view == NULL) {
5979 view->count = 0;
5980 break;
5982 s->parent_view->count = view->count;
5984 if (s->parent_view->type == TOG_VIEW_LOG) {
5985 ls = &s->parent_view->state.log;
5986 old_selected_entry = ls->selected_entry;
5988 err = input_log_view(NULL, s->parent_view,
5989 up ? KEY_UP : KEY_DOWN);
5990 if (err)
5991 break;
5992 view->count = s->parent_view->count;
5994 if (old_selected_entry == ls->selected_entry)
5995 break;
5997 err = set_selected_commit(s, ls->selected_entry);
5998 if (err)
5999 break;
6000 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
6001 struct tog_blame_view_state *bs;
6002 struct got_object_id *id, *prev_id;
6004 bs = &s->parent_view->state.blame;
6005 prev_id = get_annotation_for_line(bs->blame.lines,
6006 bs->blame.nlines, bs->last_diffed_line);
6008 err = input_blame_view(&view, s->parent_view,
6009 up ? KEY_UP : KEY_DOWN);
6010 if (err)
6011 break;
6012 view->count = s->parent_view->count;
6014 if (prev_id == NULL)
6015 break;
6016 id = get_selected_commit_id(bs->blame.lines,
6017 bs->blame.nlines, bs->first_displayed_line,
6018 bs->selected_line);
6019 if (id == NULL)
6020 break;
6022 if (!got_object_id_cmp(prev_id, id))
6023 break;
6025 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
6026 if (err)
6027 break;
6029 s->first_displayed_line = 1;
6030 s->last_displayed_line = view->nlines;
6031 s->matched_line = 0;
6032 view->x = 0;
6034 diff_view_indicate_progress(view);
6035 err = create_diff(s);
6036 break;
6037 default:
6038 view->count = 0;
6039 break;
6042 return err;
6045 static const struct got_error *
6046 cmd_diff(int argc, char *argv[])
6048 const struct got_error *error;
6049 struct got_repository *repo = NULL;
6050 struct got_worktree *worktree = NULL;
6051 struct got_object_id *id1 = NULL, *id2 = NULL;
6052 char *repo_path = NULL, *cwd = NULL;
6053 char *id_str1 = NULL, *id_str2 = NULL;
6054 char *keyword_idstr1 = NULL, *keyword_idstr2 = NULL;
6055 char *label1 = NULL, *label2 = NULL;
6056 int diff_context = 3, ignore_whitespace = 0;
6057 int ch, force_text_diff = 0;
6058 const char *errstr;
6059 struct tog_view *view;
6060 int *pack_fds = NULL;
6062 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
6063 switch (ch) {
6064 case 'a':
6065 force_text_diff = 1;
6066 break;
6067 case 'C':
6068 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
6069 &errstr);
6070 if (errstr != NULL)
6071 errx(1, "number of context lines is %s: %s",
6072 errstr, errstr);
6073 break;
6074 case 'r':
6075 repo_path = realpath(optarg, NULL);
6076 if (repo_path == NULL)
6077 return got_error_from_errno2("realpath",
6078 optarg);
6079 got_path_strip_trailing_slashes(repo_path);
6080 break;
6081 case 'w':
6082 ignore_whitespace = 1;
6083 break;
6084 default:
6085 usage_diff();
6086 /* NOTREACHED */
6090 argc -= optind;
6091 argv += optind;
6093 if (argc == 0) {
6094 usage_diff(); /* TODO show local worktree changes */
6095 } else if (argc == 2) {
6096 id_str1 = argv[0];
6097 id_str2 = argv[1];
6098 } else
6099 usage_diff();
6101 error = got_repo_pack_fds_open(&pack_fds);
6102 if (error)
6103 goto done;
6105 if (repo_path == NULL) {
6106 cwd = getcwd(NULL, 0);
6107 if (cwd == NULL)
6108 return got_error_from_errno("getcwd");
6109 error = got_worktree_open(&worktree, cwd, NULL);
6110 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6111 goto done;
6112 if (worktree)
6113 repo_path =
6114 strdup(got_worktree_get_repo_path(worktree));
6115 else
6116 repo_path = strdup(cwd);
6117 if (repo_path == NULL) {
6118 error = got_error_from_errno("strdup");
6119 goto done;
6123 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6124 if (error)
6125 goto done;
6127 init_curses();
6129 error = apply_unveil(got_repo_get_path(repo), NULL);
6130 if (error)
6131 goto done;
6133 error = tog_load_refs(repo, 0);
6134 if (error)
6135 goto done;
6137 if (id_str1 != NULL) {
6138 error = got_keyword_to_idstr(&keyword_idstr1, id_str1,
6139 repo, worktree);
6140 if (error != NULL)
6141 goto done;
6142 if (keyword_idstr1 != NULL)
6143 id_str1 = keyword_idstr1;
6145 if (id_str2 != NULL) {
6146 error = got_keyword_to_idstr(&keyword_idstr2, id_str2,
6147 repo, worktree);
6148 if (error != NULL)
6149 goto done;
6150 if (keyword_idstr2 != NULL)
6151 id_str2 = keyword_idstr2;
6154 error = got_repo_match_object_id(&id1, &label1, id_str1,
6155 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6156 if (error)
6157 goto done;
6159 error = got_repo_match_object_id(&id2, &label2, id_str2,
6160 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6161 if (error)
6162 goto done;
6164 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
6165 if (view == NULL) {
6166 error = got_error_from_errno("view_open");
6167 goto done;
6169 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
6170 ignore_whitespace, force_text_diff, NULL, repo);
6171 if (error)
6172 goto done;
6174 if (worktree) {
6175 error = set_tog_base_commit(repo, worktree);
6176 if (error != NULL)
6177 goto done;
6179 /* Release work tree lock. */
6180 got_worktree_close(worktree);
6181 worktree = NULL;
6184 error = view_loop(view);
6186 done:
6187 free(tog_base_commit.id);
6188 free(keyword_idstr1);
6189 free(keyword_idstr2);
6190 free(label1);
6191 free(label2);
6192 free(id1);
6193 free(id2);
6194 free(repo_path);
6195 free(cwd);
6196 if (repo) {
6197 const struct got_error *close_err = got_repo_close(repo);
6198 if (error == NULL)
6199 error = close_err;
6201 if (worktree)
6202 got_worktree_close(worktree);
6203 if (pack_fds) {
6204 const struct got_error *pack_err =
6205 got_repo_pack_fds_close(pack_fds);
6206 if (error == NULL)
6207 error = pack_err;
6209 tog_free_refs();
6210 return error;
6213 __dead static void
6214 usage_blame(void)
6216 endwin();
6217 fprintf(stderr,
6218 "usage: %s blame [-c commit] [-r repository-path] path\n",
6219 getprogname());
6220 exit(1);
6223 struct tog_blame_line {
6224 int annotated;
6225 struct got_object_id *id;
6228 static const struct got_error *
6229 draw_blame(struct tog_view *view)
6231 struct tog_blame_view_state *s = &view->state.blame;
6232 struct tog_blame *blame = &s->blame;
6233 regmatch_t *regmatch = &view->regmatch;
6234 const struct got_error *err;
6235 int lineno = 0, nprinted = 0;
6236 char *line = NULL;
6237 size_t linesize = 0;
6238 ssize_t linelen;
6239 wchar_t *wline;
6240 int width;
6241 struct tog_blame_line *blame_line;
6242 struct got_object_id *prev_id = NULL;
6243 char *id_str;
6244 struct tog_color *tc;
6246 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6247 if (err)
6248 return err;
6250 rewind(blame->f);
6251 werase(view->window);
6253 if (asprintf(&line, "commit %s", id_str) == -1) {
6254 err = got_error_from_errno("asprintf");
6255 free(id_str);
6256 return err;
6259 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6260 free(line);
6261 line = NULL;
6262 if (err)
6263 return err;
6264 if (view_needs_focus_indication(view))
6265 wstandout(view->window);
6266 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6267 if (tc)
6268 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6269 waddwstr(view->window, wline);
6270 while (width++ < view->ncols)
6271 waddch(view->window, ' ');
6272 if (tc)
6273 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6274 if (view_needs_focus_indication(view))
6275 wstandend(view->window);
6276 free(wline);
6277 wline = NULL;
6279 if (view->gline > blame->nlines)
6280 view->gline = blame->nlines;
6282 if (tog_io.wait_for_ui) {
6283 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6284 int rc;
6286 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6287 if (rc)
6288 return got_error_set_errno(rc, "pthread_cond_wait");
6289 tog_io.wait_for_ui = 0;
6292 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6293 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6294 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6295 free(id_str);
6296 return got_error_from_errno("asprintf");
6298 free(id_str);
6299 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6300 free(line);
6301 line = NULL;
6302 if (err)
6303 return err;
6304 waddwstr(view->window, wline);
6305 free(wline);
6306 wline = NULL;
6307 if (width < view->ncols - 1)
6308 waddch(view->window, '\n');
6310 s->eof = 0;
6311 view->maxx = 0;
6312 while (nprinted < view->nlines - 2) {
6313 linelen = getline(&line, &linesize, blame->f);
6314 if (linelen == -1) {
6315 if (feof(blame->f)) {
6316 s->eof = 1;
6317 break;
6319 free(line);
6320 return got_ferror(blame->f, GOT_ERR_IO);
6322 if (++lineno < s->first_displayed_line)
6323 continue;
6324 if (view->gline && !gotoline(view, &lineno, &nprinted))
6325 continue;
6327 /* Set view->maxx based on full line length. */
6328 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6329 if (err) {
6330 free(line);
6331 return err;
6333 free(wline);
6334 wline = NULL;
6335 view->maxx = MAX(view->maxx, width);
6337 if (nprinted == s->selected_line - 1)
6338 wstandout(view->window);
6340 if (blame->nlines > 0) {
6341 blame_line = &blame->lines[lineno - 1];
6342 if (blame_line->annotated && prev_id &&
6343 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6344 !(nprinted == s->selected_line - 1)) {
6345 waddstr(view->window, " ");
6346 } else if (blame_line->annotated) {
6347 char *id_str;
6348 err = got_object_id_str(&id_str,
6349 blame_line->id);
6350 if (err) {
6351 free(line);
6352 return err;
6354 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6355 if (tc)
6356 wattr_on(view->window,
6357 COLOR_PAIR(tc->colorpair), NULL);
6358 wprintw(view->window, "%.8s", id_str);
6359 if (tc)
6360 wattr_off(view->window,
6361 COLOR_PAIR(tc->colorpair), NULL);
6362 free(id_str);
6363 prev_id = blame_line->id;
6364 } else {
6365 waddstr(view->window, "........");
6366 prev_id = NULL;
6368 } else {
6369 waddstr(view->window, "........");
6370 prev_id = NULL;
6373 if (nprinted == s->selected_line - 1)
6374 wstandend(view->window);
6375 waddstr(view->window, " ");
6377 if (view->ncols <= 9) {
6378 width = 9;
6379 } else if (s->first_displayed_line + nprinted ==
6380 s->matched_line &&
6381 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6382 err = add_matched_line(&width, line, view->ncols - 9, 9,
6383 view->window, view->x, regmatch);
6384 if (err) {
6385 free(line);
6386 return err;
6388 width += 9;
6389 } else {
6390 int skip;
6391 err = format_line(&wline, &width, &skip, line,
6392 view->x, view->ncols - 9, 9, 1);
6393 if (err) {
6394 free(line);
6395 return err;
6397 waddwstr(view->window, &wline[skip]);
6398 width += 9;
6399 free(wline);
6400 wline = NULL;
6403 if (width <= view->ncols - 1)
6404 waddch(view->window, '\n');
6405 if (++nprinted == 1)
6406 s->first_displayed_line = lineno;
6408 free(line);
6409 s->last_displayed_line = lineno;
6411 view_border(view);
6413 return NULL;
6416 static const struct got_error *
6417 blame_cb(void *arg, int nlines, int lineno,
6418 struct got_commit_object *commit, struct got_object_id *id)
6420 const struct got_error *err = NULL;
6421 struct tog_blame_cb_args *a = arg;
6422 struct tog_blame_line *line;
6423 int errcode;
6425 if (nlines != a->nlines ||
6426 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6427 return got_error(GOT_ERR_RANGE);
6429 errcode = pthread_mutex_lock(&tog_mutex);
6430 if (errcode)
6431 return got_error_set_errno(errcode, "pthread_mutex_lock");
6433 if (*a->quit) { /* user has quit the blame view */
6434 err = got_error(GOT_ERR_ITER_COMPLETED);
6435 goto done;
6438 if (lineno == -1)
6439 goto done; /* no change in this commit */
6441 line = &a->lines[lineno - 1];
6442 if (line->annotated)
6443 goto done;
6445 line->id = got_object_id_dup(id);
6446 if (line->id == NULL) {
6447 err = got_error_from_errno("got_object_id_dup");
6448 goto done;
6450 line->annotated = 1;
6451 done:
6452 errcode = pthread_mutex_unlock(&tog_mutex);
6453 if (errcode)
6454 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6455 return err;
6458 static void *
6459 blame_thread(void *arg)
6461 const struct got_error *err, *close_err;
6462 struct tog_blame_thread_args *ta = arg;
6463 struct tog_blame_cb_args *a = ta->cb_args;
6464 int errcode, fd1 = -1, fd2 = -1;
6465 FILE *f1 = NULL, *f2 = NULL;
6467 fd1 = got_opentempfd();
6468 if (fd1 == -1)
6469 return (void *)got_error_from_errno("got_opentempfd");
6471 fd2 = got_opentempfd();
6472 if (fd2 == -1) {
6473 err = got_error_from_errno("got_opentempfd");
6474 goto done;
6477 f1 = got_opentemp();
6478 if (f1 == NULL) {
6479 err = (void *)got_error_from_errno("got_opentemp");
6480 goto done;
6482 f2 = got_opentemp();
6483 if (f2 == NULL) {
6484 err = (void *)got_error_from_errno("got_opentemp");
6485 goto done;
6488 err = block_signals_used_by_main_thread();
6489 if (err)
6490 goto done;
6492 err = got_blame(ta->path, a->commit_id, ta->repo,
6493 tog_diff_algo, blame_cb, ta->cb_args,
6494 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6495 if (err && err->code == GOT_ERR_CANCELLED)
6496 err = NULL;
6498 errcode = pthread_mutex_lock(&tog_mutex);
6499 if (errcode) {
6500 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6501 goto done;
6504 close_err = got_repo_close(ta->repo);
6505 if (err == NULL)
6506 err = close_err;
6507 ta->repo = NULL;
6508 *ta->complete = 1;
6510 if (tog_io.wait_for_ui) {
6511 errcode = pthread_cond_signal(&ta->blame_complete);
6512 if (errcode && err == NULL)
6513 err = got_error_set_errno(errcode,
6514 "pthread_cond_signal");
6517 errcode = pthread_mutex_unlock(&tog_mutex);
6518 if (errcode && err == NULL)
6519 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6521 done:
6522 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6523 err = got_error_from_errno("close");
6524 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6525 err = got_error_from_errno("close");
6526 if (f1 && fclose(f1) == EOF && err == NULL)
6527 err = got_error_from_errno("fclose");
6528 if (f2 && fclose(f2) == EOF && err == NULL)
6529 err = got_error_from_errno("fclose");
6531 return (void *)err;
6534 static struct got_object_id *
6535 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6536 int first_displayed_line, int selected_line)
6538 struct tog_blame_line *line;
6540 if (nlines <= 0)
6541 return NULL;
6543 line = &lines[first_displayed_line - 1 + selected_line - 1];
6544 if (!line->annotated)
6545 return NULL;
6547 return line->id;
6550 static struct got_object_id *
6551 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6552 int lineno)
6554 struct tog_blame_line *line;
6556 if (nlines <= 0 || lineno >= nlines)
6557 return NULL;
6559 line = &lines[lineno - 1];
6560 if (!line->annotated)
6561 return NULL;
6563 return line->id;
6566 static const struct got_error *
6567 stop_blame(struct tog_blame *blame)
6569 const struct got_error *err = NULL;
6570 int i;
6572 if (blame->thread) {
6573 int errcode;
6574 errcode = pthread_mutex_unlock(&tog_mutex);
6575 if (errcode)
6576 return got_error_set_errno(errcode,
6577 "pthread_mutex_unlock");
6578 errcode = pthread_join(blame->thread, (void **)&err);
6579 if (errcode)
6580 return got_error_set_errno(errcode, "pthread_join");
6581 errcode = pthread_mutex_lock(&tog_mutex);
6582 if (errcode)
6583 return got_error_set_errno(errcode,
6584 "pthread_mutex_lock");
6585 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6586 err = NULL;
6587 blame->thread = 0; //NULL;
6589 if (blame->thread_args.repo) {
6590 const struct got_error *close_err;
6591 close_err = got_repo_close(blame->thread_args.repo);
6592 if (err == NULL)
6593 err = close_err;
6594 blame->thread_args.repo = NULL;
6596 if (blame->f) {
6597 if (fclose(blame->f) == EOF && err == NULL)
6598 err = got_error_from_errno("fclose");
6599 blame->f = NULL;
6601 if (blame->lines) {
6602 for (i = 0; i < blame->nlines; i++)
6603 free(blame->lines[i].id);
6604 free(blame->lines);
6605 blame->lines = NULL;
6607 free(blame->cb_args.commit_id);
6608 blame->cb_args.commit_id = NULL;
6609 if (blame->pack_fds) {
6610 const struct got_error *pack_err =
6611 got_repo_pack_fds_close(blame->pack_fds);
6612 if (err == NULL)
6613 err = pack_err;
6614 blame->pack_fds = NULL;
6616 free(blame->line_offsets);
6617 blame->line_offsets = NULL;
6618 return err;
6621 static const struct got_error *
6622 cancel_blame_view(void *arg)
6624 const struct got_error *err = NULL;
6625 int *done = arg;
6626 int errcode;
6628 errcode = pthread_mutex_lock(&tog_mutex);
6629 if (errcode)
6630 return got_error_set_errno(errcode,
6631 "pthread_mutex_unlock");
6633 if (*done)
6634 err = got_error(GOT_ERR_CANCELLED);
6636 errcode = pthread_mutex_unlock(&tog_mutex);
6637 if (errcode)
6638 return got_error_set_errno(errcode,
6639 "pthread_mutex_lock");
6641 return err;
6644 static const struct got_error *
6645 run_blame(struct tog_view *view)
6647 struct tog_blame_view_state *s = &view->state.blame;
6648 struct tog_blame *blame = &s->blame;
6649 const struct got_error *err = NULL;
6650 struct got_commit_object *commit = NULL;
6651 struct got_blob_object *blob = NULL;
6652 struct got_repository *thread_repo = NULL;
6653 struct got_object_id *obj_id = NULL;
6654 int obj_type, fd = -1;
6655 int *pack_fds = NULL;
6657 err = got_object_open_as_commit(&commit, s->repo,
6658 &s->blamed_commit->id);
6659 if (err)
6660 return err;
6662 fd = got_opentempfd();
6663 if (fd == -1) {
6664 err = got_error_from_errno("got_opentempfd");
6665 goto done;
6668 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6669 if (err)
6670 goto done;
6672 err = got_object_get_type(&obj_type, s->repo, obj_id);
6673 if (err)
6674 goto done;
6676 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6677 err = got_error(GOT_ERR_OBJ_TYPE);
6678 goto done;
6681 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6682 if (err)
6683 goto done;
6684 blame->f = got_opentemp();
6685 if (blame->f == NULL) {
6686 err = got_error_from_errno("got_opentemp");
6687 goto done;
6689 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6690 &blame->line_offsets, blame->f, blob);
6691 if (err)
6692 goto done;
6693 if (blame->nlines == 0) {
6694 s->blame_complete = 1;
6695 goto done;
6698 /* Don't include \n at EOF in the blame line count. */
6699 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6700 blame->nlines--;
6702 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6703 if (blame->lines == NULL) {
6704 err = got_error_from_errno("calloc");
6705 goto done;
6708 err = got_repo_pack_fds_open(&pack_fds);
6709 if (err)
6710 goto done;
6711 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6712 pack_fds);
6713 if (err)
6714 goto done;
6716 blame->pack_fds = pack_fds;
6717 blame->cb_args.view = view;
6718 blame->cb_args.lines = blame->lines;
6719 blame->cb_args.nlines = blame->nlines;
6720 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6721 if (blame->cb_args.commit_id == NULL) {
6722 err = got_error_from_errno("got_object_id_dup");
6723 goto done;
6725 blame->cb_args.quit = &s->done;
6727 blame->thread_args.path = s->path;
6728 blame->thread_args.repo = thread_repo;
6729 blame->thread_args.cb_args = &blame->cb_args;
6730 blame->thread_args.complete = &s->blame_complete;
6731 blame->thread_args.cancel_cb = cancel_blame_view;
6732 blame->thread_args.cancel_arg = &s->done;
6733 s->blame_complete = 0;
6735 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6736 s->first_displayed_line = 1;
6737 s->last_displayed_line = view->nlines;
6738 s->selected_line = 1;
6740 s->matched_line = 0;
6742 done:
6743 if (commit)
6744 got_object_commit_close(commit);
6745 if (fd != -1 && close(fd) == -1 && err == NULL)
6746 err = got_error_from_errno("close");
6747 if (blob)
6748 got_object_blob_close(blob);
6749 free(obj_id);
6750 if (err)
6751 stop_blame(blame);
6752 return err;
6755 static const struct got_error *
6756 open_blame_view(struct tog_view *view, char *path,
6757 struct got_object_id *commit_id, struct got_repository *repo)
6759 const struct got_error *err = NULL;
6760 struct tog_blame_view_state *s = &view->state.blame;
6762 STAILQ_INIT(&s->blamed_commits);
6764 s->path = strdup(path);
6765 if (s->path == NULL)
6766 return got_error_from_errno("strdup");
6768 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6769 if (err) {
6770 free(s->path);
6771 return err;
6774 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6775 s->first_displayed_line = 1;
6776 s->last_displayed_line = view->nlines;
6777 s->selected_line = 1;
6778 s->blame_complete = 0;
6779 s->repo = repo;
6780 s->commit_id = commit_id;
6781 memset(&s->blame, 0, sizeof(s->blame));
6783 STAILQ_INIT(&s->colors);
6784 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6785 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6786 get_color_value("TOG_COLOR_COMMIT"));
6787 if (err)
6788 return err;
6791 view->show = show_blame_view;
6792 view->input = input_blame_view;
6793 view->reset = reset_blame_view;
6794 view->close = close_blame_view;
6795 view->search_start = search_start_blame_view;
6796 view->search_setup = search_setup_blame_view;
6797 view->search_next = search_next_view_match;
6799 if (using_mock_io) {
6800 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6801 int rc;
6803 rc = pthread_cond_init(&bta->blame_complete, NULL);
6804 if (rc)
6805 return got_error_set_errno(rc, "pthread_cond_init");
6808 return run_blame(view);
6811 static const struct got_error *
6812 close_blame_view(struct tog_view *view)
6814 const struct got_error *err = NULL;
6815 struct tog_blame_view_state *s = &view->state.blame;
6817 if (s->blame.thread)
6818 err = stop_blame(&s->blame);
6820 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6821 struct got_object_qid *blamed_commit;
6822 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6823 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6824 got_object_qid_free(blamed_commit);
6827 if (using_mock_io) {
6828 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6829 int rc;
6831 rc = pthread_cond_destroy(&bta->blame_complete);
6832 if (rc && err == NULL)
6833 err = got_error_set_errno(rc, "pthread_cond_destroy");
6836 free(s->path);
6837 free_colors(&s->colors);
6838 return err;
6841 static const struct got_error *
6842 search_start_blame_view(struct tog_view *view)
6844 struct tog_blame_view_state *s = &view->state.blame;
6846 s->matched_line = 0;
6847 return NULL;
6850 static void
6851 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6852 size_t *nlines, int **first, int **last, int **match, int **selected)
6854 struct tog_blame_view_state *s = &view->state.blame;
6856 *f = s->blame.f;
6857 *nlines = s->blame.nlines;
6858 *line_offsets = s->blame.line_offsets;
6859 *match = &s->matched_line;
6860 *first = &s->first_displayed_line;
6861 *last = &s->last_displayed_line;
6862 *selected = &s->selected_line;
6865 static const struct got_error *
6866 show_blame_view(struct tog_view *view)
6868 const struct got_error *err = NULL;
6869 struct tog_blame_view_state *s = &view->state.blame;
6870 int errcode;
6872 if (s->blame.thread == 0 && !s->blame_complete) {
6873 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6874 &s->blame.thread_args);
6875 if (errcode)
6876 return got_error_set_errno(errcode, "pthread_create");
6878 if (!using_mock_io)
6879 halfdelay(1); /* fast refresh while annotating */
6882 if (s->blame_complete && !using_mock_io)
6883 halfdelay(10); /* disable fast refresh */
6885 err = draw_blame(view);
6887 view_border(view);
6888 return err;
6891 static const struct got_error *
6892 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6893 struct got_repository *repo, struct got_object_id *id)
6895 struct tog_view *log_view;
6896 const struct got_error *err = NULL;
6898 *new_view = NULL;
6900 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6901 if (log_view == NULL)
6902 return got_error_from_errno("view_open");
6904 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0, NULL);
6905 if (err)
6906 view_close(log_view);
6907 else
6908 *new_view = log_view;
6910 return err;
6913 static const struct got_error *
6914 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6916 const struct got_error *err = NULL, *thread_err = NULL;
6917 struct tog_view *diff_view;
6918 struct tog_blame_view_state *s = &view->state.blame;
6919 int eos, nscroll, begin_y = 0, begin_x = 0;
6921 eos = nscroll = view->nlines - 2;
6922 if (view_is_hsplit_top(view))
6923 --eos; /* border */
6925 switch (ch) {
6926 case '0':
6927 case '$':
6928 case KEY_RIGHT:
6929 case 'l':
6930 case KEY_LEFT:
6931 case 'h':
6932 horizontal_scroll_input(view, ch);
6933 break;
6934 case 'q':
6935 s->done = 1;
6936 break;
6937 case 'g':
6938 case KEY_HOME:
6939 s->selected_line = 1;
6940 s->first_displayed_line = 1;
6941 view->count = 0;
6942 break;
6943 case 'G':
6944 case KEY_END:
6945 if (s->blame.nlines < eos) {
6946 s->selected_line = s->blame.nlines;
6947 s->first_displayed_line = 1;
6948 } else {
6949 s->selected_line = eos;
6950 s->first_displayed_line = s->blame.nlines - (eos - 1);
6952 view->count = 0;
6953 break;
6954 case 'k':
6955 case KEY_UP:
6956 case CTRL('p'):
6957 if (s->selected_line > 1)
6958 s->selected_line--;
6959 else if (s->selected_line == 1 &&
6960 s->first_displayed_line > 1)
6961 s->first_displayed_line--;
6962 else
6963 view->count = 0;
6964 break;
6965 case CTRL('u'):
6966 case 'u':
6967 nscroll /= 2;
6968 /* FALL THROUGH */
6969 case KEY_PPAGE:
6970 case CTRL('b'):
6971 case 'b':
6972 if (s->first_displayed_line == 1) {
6973 if (view->count > 1)
6974 nscroll += nscroll;
6975 s->selected_line = MAX(1, s->selected_line - nscroll);
6976 view->count = 0;
6977 break;
6979 if (s->first_displayed_line > nscroll)
6980 s->first_displayed_line -= nscroll;
6981 else
6982 s->first_displayed_line = 1;
6983 break;
6984 case 'j':
6985 case KEY_DOWN:
6986 case CTRL('n'):
6987 if (s->selected_line < eos && s->first_displayed_line +
6988 s->selected_line <= s->blame.nlines)
6989 s->selected_line++;
6990 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6991 s->first_displayed_line++;
6992 else
6993 view->count = 0;
6994 break;
6995 case 'c':
6996 case 'p': {
6997 struct got_object_id *id = NULL;
6999 view->count = 0;
7000 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
7001 s->first_displayed_line, s->selected_line);
7002 if (id == NULL)
7003 break;
7004 if (ch == 'p') {
7005 struct got_commit_object *commit, *pcommit;
7006 struct got_object_qid *pid;
7007 struct got_object_id *blob_id = NULL;
7008 int obj_type;
7009 err = got_object_open_as_commit(&commit,
7010 s->repo, id);
7011 if (err)
7012 break;
7013 pid = STAILQ_FIRST(
7014 got_object_commit_get_parent_ids(commit));
7015 if (pid == NULL) {
7016 got_object_commit_close(commit);
7017 break;
7019 /* Check if path history ends here. */
7020 err = got_object_open_as_commit(&pcommit,
7021 s->repo, &pid->id);
7022 if (err)
7023 break;
7024 err = got_object_id_by_path(&blob_id, s->repo,
7025 pcommit, s->path);
7026 got_object_commit_close(pcommit);
7027 if (err) {
7028 if (err->code == GOT_ERR_NO_TREE_ENTRY)
7029 err = NULL;
7030 got_object_commit_close(commit);
7031 break;
7033 err = got_object_get_type(&obj_type, s->repo,
7034 blob_id);
7035 free(blob_id);
7036 /* Can't blame non-blob type objects. */
7037 if (obj_type != GOT_OBJ_TYPE_BLOB) {
7038 got_object_commit_close(commit);
7039 break;
7041 err = got_object_qid_alloc(&s->blamed_commit,
7042 &pid->id);
7043 got_object_commit_close(commit);
7044 } else {
7045 if (got_object_id_cmp(id,
7046 &s->blamed_commit->id) == 0)
7047 break;
7048 err = got_object_qid_alloc(&s->blamed_commit,
7049 id);
7051 if (err)
7052 break;
7053 s->done = 1;
7054 thread_err = stop_blame(&s->blame);
7055 s->done = 0;
7056 if (thread_err)
7057 break;
7058 STAILQ_INSERT_HEAD(&s->blamed_commits,
7059 s->blamed_commit, entry);
7060 err = run_blame(view);
7061 if (err)
7062 break;
7063 break;
7065 case 'C': {
7066 struct got_object_qid *first;
7068 view->count = 0;
7069 first = STAILQ_FIRST(&s->blamed_commits);
7070 if (!got_object_id_cmp(&first->id, s->commit_id))
7071 break;
7072 s->done = 1;
7073 thread_err = stop_blame(&s->blame);
7074 s->done = 0;
7075 if (thread_err)
7076 break;
7077 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
7078 got_object_qid_free(s->blamed_commit);
7079 s->blamed_commit =
7080 STAILQ_FIRST(&s->blamed_commits);
7081 err = run_blame(view);
7082 if (err)
7083 break;
7084 break;
7086 case 'L':
7087 view->count = 0;
7088 s->id_to_log = get_selected_commit_id(s->blame.lines,
7089 s->blame.nlines, s->first_displayed_line, s->selected_line);
7090 if (s->id_to_log)
7091 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7092 break;
7093 case KEY_ENTER:
7094 case '\r': {
7095 struct got_object_id *id = NULL;
7096 struct got_object_qid *pid;
7097 struct got_commit_object *commit = NULL;
7099 view->count = 0;
7100 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
7101 s->first_displayed_line, s->selected_line);
7102 if (id == NULL)
7103 break;
7104 err = got_object_open_as_commit(&commit, s->repo, id);
7105 if (err)
7106 break;
7107 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7108 if (*new_view) {
7109 /* traversed from diff view, release diff resources */
7110 err = close_diff_view(*new_view);
7111 if (err)
7112 break;
7113 diff_view = *new_view;
7114 } else {
7115 if (view_is_parent_view(view))
7116 view_get_split(view, &begin_y, &begin_x);
7118 diff_view = view_open(0, 0, begin_y, begin_x,
7119 TOG_VIEW_DIFF);
7120 if (diff_view == NULL) {
7121 got_object_commit_close(commit);
7122 err = got_error_from_errno("view_open");
7123 break;
7126 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
7127 id, NULL, NULL, 3, 0, 0, view, s->repo);
7128 got_object_commit_close(commit);
7129 if (err)
7130 break;
7131 s->last_diffed_line = s->first_displayed_line - 1 +
7132 s->selected_line;
7133 if (*new_view)
7134 break; /* still open from active diff view */
7135 if (view_is_parent_view(view) &&
7136 view->mode == TOG_VIEW_SPLIT_HRZN) {
7137 err = view_init_hsplit(view, begin_y);
7138 if (err)
7139 break;
7142 view->focussed = 0;
7143 diff_view->focussed = 1;
7144 diff_view->mode = view->mode;
7145 diff_view->nlines = view->lines - begin_y;
7146 if (view_is_parent_view(view)) {
7147 view_transfer_size(diff_view, view);
7148 err = view_close_child(view);
7149 if (err)
7150 break;
7151 err = view_set_child(view, diff_view);
7152 if (err)
7153 break;
7154 view->focus_child = 1;
7155 } else
7156 *new_view = diff_view;
7157 if (err)
7158 break;
7159 break;
7161 case CTRL('d'):
7162 case 'd':
7163 nscroll /= 2;
7164 /* FALL THROUGH */
7165 case KEY_NPAGE:
7166 case CTRL('f'):
7167 case 'f':
7168 case ' ':
7169 if (s->last_displayed_line >= s->blame.nlines &&
7170 s->selected_line >= MIN(s->blame.nlines,
7171 view->nlines - 2)) {
7172 view->count = 0;
7173 break;
7175 if (s->last_displayed_line >= s->blame.nlines &&
7176 s->selected_line < view->nlines - 2) {
7177 s->selected_line +=
7178 MIN(nscroll, s->last_displayed_line -
7179 s->first_displayed_line - s->selected_line + 1);
7181 if (s->last_displayed_line + nscroll <= s->blame.nlines)
7182 s->first_displayed_line += nscroll;
7183 else
7184 s->first_displayed_line =
7185 s->blame.nlines - (view->nlines - 3);
7186 break;
7187 case KEY_RESIZE:
7188 if (s->selected_line > view->nlines - 2) {
7189 s->selected_line = MIN(s->blame.nlines,
7190 view->nlines - 2);
7192 break;
7193 default:
7194 view->count = 0;
7195 break;
7197 return thread_err ? thread_err : err;
7200 static const struct got_error *
7201 reset_blame_view(struct tog_view *view)
7203 const struct got_error *err;
7204 struct tog_blame_view_state *s = &view->state.blame;
7206 view->count = 0;
7207 s->done = 1;
7208 err = stop_blame(&s->blame);
7209 s->done = 0;
7210 if (err)
7211 return err;
7212 return run_blame(view);
7215 static const struct got_error *
7216 cmd_blame(int argc, char *argv[])
7218 const struct got_error *error;
7219 struct got_repository *repo = NULL;
7220 struct got_worktree *worktree = NULL;
7221 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7222 char *link_target = NULL;
7223 struct got_object_id *commit_id = NULL;
7224 struct got_commit_object *commit = NULL;
7225 char *keyword_idstr = NULL, *commit_id_str = NULL;
7226 int ch;
7227 struct tog_view *view = NULL;
7228 int *pack_fds = NULL;
7230 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7231 switch (ch) {
7232 case 'c':
7233 commit_id_str = optarg;
7234 break;
7235 case 'r':
7236 repo_path = realpath(optarg, NULL);
7237 if (repo_path == NULL)
7238 return got_error_from_errno2("realpath",
7239 optarg);
7240 break;
7241 default:
7242 usage_blame();
7243 /* NOTREACHED */
7247 argc -= optind;
7248 argv += optind;
7250 if (argc != 1)
7251 usage_blame();
7253 error = got_repo_pack_fds_open(&pack_fds);
7254 if (error != NULL)
7255 goto done;
7257 if (repo_path == NULL) {
7258 cwd = getcwd(NULL, 0);
7259 if (cwd == NULL)
7260 return got_error_from_errno("getcwd");
7261 error = got_worktree_open(&worktree, cwd, NULL);
7262 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7263 goto done;
7264 if (worktree)
7265 repo_path =
7266 strdup(got_worktree_get_repo_path(worktree));
7267 else
7268 repo_path = strdup(cwd);
7269 if (repo_path == NULL) {
7270 error = got_error_from_errno("strdup");
7271 goto done;
7275 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7276 if (error != NULL)
7277 goto done;
7279 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7280 worktree);
7281 if (error)
7282 goto done;
7284 init_curses();
7286 error = apply_unveil(got_repo_get_path(repo), NULL);
7287 if (error)
7288 goto done;
7290 error = tog_load_refs(repo, 0);
7291 if (error)
7292 goto done;
7294 if (commit_id_str == NULL) {
7295 struct got_reference *head_ref;
7296 error = got_ref_open(&head_ref, repo, worktree ?
7297 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7298 if (error != NULL)
7299 goto done;
7300 error = got_ref_resolve(&commit_id, repo, head_ref);
7301 got_ref_close(head_ref);
7302 } else {
7303 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
7304 repo, worktree);
7305 if (error != NULL)
7306 goto done;
7307 if (keyword_idstr != NULL)
7308 commit_id_str = keyword_idstr;
7310 error = got_repo_match_object_id(&commit_id, NULL,
7311 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7313 if (error != NULL)
7314 goto done;
7316 error = got_object_open_as_commit(&commit, repo, commit_id);
7317 if (error)
7318 goto done;
7320 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7321 commit, repo);
7322 if (error)
7323 goto done;
7325 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7326 if (view == NULL) {
7327 error = got_error_from_errno("view_open");
7328 goto done;
7330 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7331 commit_id, repo);
7332 if (error != NULL) {
7333 if (view->close == NULL)
7334 close_blame_view(view);
7335 view_close(view);
7336 goto done;
7339 if (worktree) {
7340 error = set_tog_base_commit(repo, worktree);
7341 if (error != NULL)
7342 goto done;
7344 /* Release work tree lock. */
7345 got_worktree_close(worktree);
7346 worktree = NULL;
7349 error = view_loop(view);
7351 done:
7352 free(tog_base_commit.id);
7353 free(repo_path);
7354 free(in_repo_path);
7355 free(link_target);
7356 free(cwd);
7357 free(commit_id);
7358 free(keyword_idstr);
7359 if (commit)
7360 got_object_commit_close(commit);
7361 if (worktree)
7362 got_worktree_close(worktree);
7363 if (repo) {
7364 const struct got_error *close_err = got_repo_close(repo);
7365 if (error == NULL)
7366 error = close_err;
7368 if (pack_fds) {
7369 const struct got_error *pack_err =
7370 got_repo_pack_fds_close(pack_fds);
7371 if (error == NULL)
7372 error = pack_err;
7374 tog_free_refs();
7375 return error;
7378 static const struct got_error *
7379 draw_tree_entries(struct tog_view *view, const char *parent_path)
7381 struct tog_tree_view_state *s = &view->state.tree;
7382 const struct got_error *err = NULL;
7383 struct got_tree_entry *te;
7384 wchar_t *wline;
7385 char *index = NULL;
7386 struct tog_color *tc;
7387 int width, n, nentries, scrollx, i = 1;
7388 int limit = view->nlines;
7390 s->ndisplayed = 0;
7391 if (view_is_hsplit_top(view))
7392 --limit; /* border */
7394 werase(view->window);
7396 if (limit == 0)
7397 return NULL;
7399 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7400 0, 0);
7401 if (err)
7402 return err;
7403 if (view_needs_focus_indication(view))
7404 wstandout(view->window);
7405 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7406 if (tc)
7407 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7408 waddwstr(view->window, wline);
7409 free(wline);
7410 wline = NULL;
7411 while (width++ < view->ncols)
7412 waddch(view->window, ' ');
7413 if (tc)
7414 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7415 if (view_needs_focus_indication(view))
7416 wstandend(view->window);
7417 if (--limit <= 0)
7418 return NULL;
7420 i += s->selected;
7421 if (s->first_displayed_entry) {
7422 i += got_tree_entry_get_index(s->first_displayed_entry);
7423 if (s->tree != s->root)
7424 ++i; /* account for ".." entry */
7426 nentries = got_object_tree_get_nentries(s->tree);
7427 if (asprintf(&index, "[%d/%d] %s",
7428 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7429 return got_error_from_errno("asprintf");
7430 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7431 free(index);
7432 if (err)
7433 return err;
7434 waddwstr(view->window, wline);
7435 free(wline);
7436 wline = NULL;
7437 if (width < view->ncols - 1)
7438 waddch(view->window, '\n');
7439 if (--limit <= 0)
7440 return NULL;
7441 waddch(view->window, '\n');
7442 if (--limit <= 0)
7443 return NULL;
7445 if (s->first_displayed_entry == NULL) {
7446 te = got_object_tree_get_first_entry(s->tree);
7447 if (s->selected == 0) {
7448 if (view->focussed)
7449 wstandout(view->window);
7450 s->selected_entry = NULL;
7452 waddstr(view->window, " ..\n"); /* parent directory */
7453 if (s->selected == 0 && view->focussed)
7454 wstandend(view->window);
7455 s->ndisplayed++;
7456 if (--limit <= 0)
7457 return NULL;
7458 n = 1;
7459 } else {
7460 n = 0;
7461 te = s->first_displayed_entry;
7464 view->maxx = 0;
7465 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7466 char *line = NULL, *id_str = NULL, *link_target = NULL;
7467 const char *modestr = "";
7468 mode_t mode;
7470 te = got_object_tree_get_entry(s->tree, i);
7471 mode = got_tree_entry_get_mode(te);
7473 if (s->show_ids) {
7474 err = got_object_id_str(&id_str,
7475 got_tree_entry_get_id(te));
7476 if (err)
7477 return got_error_from_errno(
7478 "got_object_id_str");
7480 if (got_object_tree_entry_is_submodule(te))
7481 modestr = "$";
7482 else if (S_ISLNK(mode)) {
7483 int i;
7485 err = got_tree_entry_get_symlink_target(&link_target,
7486 te, s->repo);
7487 if (err) {
7488 free(id_str);
7489 return err;
7491 for (i = 0; link_target[i] != '\0'; i++) {
7492 if (!isprint((unsigned char)link_target[i]))
7493 link_target[i] = '?';
7495 modestr = "@";
7497 else if (S_ISDIR(mode))
7498 modestr = "/";
7499 else if (mode & S_IXUSR)
7500 modestr = "*";
7501 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7502 got_tree_entry_get_name(te), modestr,
7503 link_target ? " -> ": "",
7504 link_target ? link_target : "") == -1) {
7505 free(id_str);
7506 free(link_target);
7507 return got_error_from_errno("asprintf");
7509 free(id_str);
7510 free(link_target);
7512 /* use full line width to determine view->maxx */
7513 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7514 if (err) {
7515 free(line);
7516 break;
7518 view->maxx = MAX(view->maxx, width);
7519 free(wline);
7520 wline = NULL;
7522 err = format_line(&wline, &width, &scrollx, line, view->x,
7523 view->ncols, 0, 0);
7524 if (err) {
7525 free(line);
7526 break;
7528 if (n == s->selected) {
7529 if (view->focussed)
7530 wstandout(view->window);
7531 s->selected_entry = te;
7533 tc = match_color(&s->colors, line);
7534 if (tc)
7535 wattr_on(view->window,
7536 COLOR_PAIR(tc->colorpair), NULL);
7537 waddwstr(view->window, &wline[scrollx]);
7538 if (tc)
7539 wattr_off(view->window,
7540 COLOR_PAIR(tc->colorpair), NULL);
7541 if (width < view->ncols)
7542 waddch(view->window, '\n');
7543 if (n == s->selected && view->focussed)
7544 wstandend(view->window);
7545 free(line);
7546 free(wline);
7547 wline = NULL;
7548 n++;
7549 s->ndisplayed++;
7550 s->last_displayed_entry = te;
7551 if (--limit <= 0)
7552 break;
7555 return err;
7558 static void
7559 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7561 struct got_tree_entry *te;
7562 int isroot = s->tree == s->root;
7563 int i = 0;
7565 if (s->first_displayed_entry == NULL)
7566 return;
7568 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7569 while (i++ < maxscroll) {
7570 if (te == NULL) {
7571 if (!isroot)
7572 s->first_displayed_entry = NULL;
7573 break;
7575 s->first_displayed_entry = te;
7576 te = got_tree_entry_get_prev(s->tree, te);
7580 static const struct got_error *
7581 tree_scroll_down(struct tog_view *view, int maxscroll)
7583 struct tog_tree_view_state *s = &view->state.tree;
7584 struct got_tree_entry *next, *last;
7585 int n = 0;
7587 if (s->first_displayed_entry)
7588 next = got_tree_entry_get_next(s->tree,
7589 s->first_displayed_entry);
7590 else
7591 next = got_object_tree_get_first_entry(s->tree);
7593 last = s->last_displayed_entry;
7594 while (next && n++ < maxscroll) {
7595 if (last) {
7596 s->last_displayed_entry = last;
7597 last = got_tree_entry_get_next(s->tree, last);
7599 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7600 s->first_displayed_entry = next;
7601 next = got_tree_entry_get_next(s->tree, next);
7605 return NULL;
7608 static const struct got_error *
7609 tree_entry_path(char **path, struct tog_parent_trees *parents,
7610 struct got_tree_entry *te)
7612 const struct got_error *err = NULL;
7613 struct tog_parent_tree *pt;
7614 size_t len = 2; /* for leading slash and NUL */
7616 TAILQ_FOREACH(pt, parents, entry)
7617 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7618 + 1 /* slash */;
7619 if (te)
7620 len += strlen(got_tree_entry_get_name(te));
7622 *path = calloc(1, len);
7623 if (path == NULL)
7624 return got_error_from_errno("calloc");
7626 (*path)[0] = '/';
7627 pt = TAILQ_LAST(parents, tog_parent_trees);
7628 while (pt) {
7629 const char *name = got_tree_entry_get_name(pt->selected_entry);
7630 if (strlcat(*path, name, len) >= len) {
7631 err = got_error(GOT_ERR_NO_SPACE);
7632 goto done;
7634 if (strlcat(*path, "/", len) >= len) {
7635 err = got_error(GOT_ERR_NO_SPACE);
7636 goto done;
7638 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7640 if (te) {
7641 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7642 err = got_error(GOT_ERR_NO_SPACE);
7643 goto done;
7646 done:
7647 if (err) {
7648 free(*path);
7649 *path = NULL;
7651 return err;
7654 static const struct got_error *
7655 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7656 struct got_tree_entry *te, struct tog_parent_trees *parents,
7657 struct got_object_id *commit_id, struct got_repository *repo)
7659 const struct got_error *err = NULL;
7660 char *path;
7661 struct tog_view *blame_view;
7663 *new_view = NULL;
7665 err = tree_entry_path(&path, parents, te);
7666 if (err)
7667 return err;
7669 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7670 if (blame_view == NULL) {
7671 err = got_error_from_errno("view_open");
7672 goto done;
7675 err = open_blame_view(blame_view, path, commit_id, repo);
7676 if (err) {
7677 if (err->code == GOT_ERR_CANCELLED)
7678 err = NULL;
7679 view_close(blame_view);
7680 } else
7681 *new_view = blame_view;
7682 done:
7683 free(path);
7684 return err;
7687 static const struct got_error *
7688 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7689 struct tog_tree_view_state *s)
7691 struct tog_view *log_view;
7692 const struct got_error *err = NULL;
7693 char *path;
7695 *new_view = NULL;
7697 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7698 if (log_view == NULL)
7699 return got_error_from_errno("view_open");
7701 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7702 if (err)
7703 return err;
7705 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7706 path, 0, NULL);
7707 if (err)
7708 view_close(log_view);
7709 else
7710 *new_view = log_view;
7711 free(path);
7712 return err;
7715 static const struct got_error *
7716 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7717 const char *head_ref_name, struct got_repository *repo)
7719 const struct got_error *err = NULL;
7720 char *commit_id_str = NULL;
7721 struct tog_tree_view_state *s = &view->state.tree;
7722 struct got_commit_object *commit = NULL;
7724 TAILQ_INIT(&s->parents);
7725 STAILQ_INIT(&s->colors);
7727 s->commit_id = got_object_id_dup(commit_id);
7728 if (s->commit_id == NULL) {
7729 err = got_error_from_errno("got_object_id_dup");
7730 goto done;
7733 err = got_object_open_as_commit(&commit, repo, commit_id);
7734 if (err)
7735 goto done;
7738 * The root is opened here and will be closed when the view is closed.
7739 * Any visited subtrees and their path-wise parents are opened and
7740 * closed on demand.
7742 err = got_object_open_as_tree(&s->root, repo,
7743 got_object_commit_get_tree_id(commit));
7744 if (err)
7745 goto done;
7746 s->tree = s->root;
7748 err = got_object_id_str(&commit_id_str, commit_id);
7749 if (err != NULL)
7750 goto done;
7752 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7753 err = got_error_from_errno("asprintf");
7754 goto done;
7757 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7758 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7759 if (head_ref_name) {
7760 s->head_ref_name = strdup(head_ref_name);
7761 if (s->head_ref_name == NULL) {
7762 err = got_error_from_errno("strdup");
7763 goto done;
7766 s->repo = repo;
7768 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7769 err = add_color(&s->colors, "\\$$",
7770 TOG_COLOR_TREE_SUBMODULE,
7771 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7772 if (err)
7773 goto done;
7774 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7775 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7776 if (err)
7777 goto done;
7778 err = add_color(&s->colors, "/$",
7779 TOG_COLOR_TREE_DIRECTORY,
7780 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7781 if (err)
7782 goto done;
7784 err = add_color(&s->colors, "\\*$",
7785 TOG_COLOR_TREE_EXECUTABLE,
7786 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7787 if (err)
7788 goto done;
7790 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7791 get_color_value("TOG_COLOR_COMMIT"));
7792 if (err)
7793 goto done;
7796 view->show = show_tree_view;
7797 view->input = input_tree_view;
7798 view->close = close_tree_view;
7799 view->search_start = search_start_tree_view;
7800 view->search_next = search_next_tree_view;
7801 done:
7802 free(commit_id_str);
7803 if (commit)
7804 got_object_commit_close(commit);
7805 if (err) {
7806 if (view->close == NULL)
7807 close_tree_view(view);
7808 view_close(view);
7810 return err;
7813 static const struct got_error *
7814 close_tree_view(struct tog_view *view)
7816 struct tog_tree_view_state *s = &view->state.tree;
7818 free_colors(&s->colors);
7819 free(s->tree_label);
7820 s->tree_label = NULL;
7821 free(s->commit_id);
7822 s->commit_id = NULL;
7823 free(s->head_ref_name);
7824 s->head_ref_name = NULL;
7825 while (!TAILQ_EMPTY(&s->parents)) {
7826 struct tog_parent_tree *parent;
7827 parent = TAILQ_FIRST(&s->parents);
7828 TAILQ_REMOVE(&s->parents, parent, entry);
7829 if (parent->tree != s->root)
7830 got_object_tree_close(parent->tree);
7831 free(parent);
7834 if (s->tree != NULL && s->tree != s->root)
7835 got_object_tree_close(s->tree);
7836 if (s->root)
7837 got_object_tree_close(s->root);
7838 return NULL;
7841 static const struct got_error *
7842 search_start_tree_view(struct tog_view *view)
7844 struct tog_tree_view_state *s = &view->state.tree;
7846 s->matched_entry = NULL;
7847 return NULL;
7850 static int
7851 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7853 regmatch_t regmatch;
7855 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7856 0) == 0;
7859 static const struct got_error *
7860 search_next_tree_view(struct tog_view *view)
7862 struct tog_tree_view_state *s = &view->state.tree;
7863 struct got_tree_entry *te = NULL;
7865 if (!view->searching) {
7866 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7867 return NULL;
7870 if (s->matched_entry) {
7871 if (view->searching == TOG_SEARCH_FORWARD) {
7872 if (s->selected_entry)
7873 te = got_tree_entry_get_next(s->tree,
7874 s->selected_entry);
7875 else
7876 te = got_object_tree_get_first_entry(s->tree);
7877 } else {
7878 if (s->selected_entry == NULL)
7879 te = got_object_tree_get_last_entry(s->tree);
7880 else
7881 te = got_tree_entry_get_prev(s->tree,
7882 s->selected_entry);
7884 } else {
7885 if (s->selected_entry)
7886 te = s->selected_entry;
7887 else if (view->searching == TOG_SEARCH_FORWARD)
7888 te = got_object_tree_get_first_entry(s->tree);
7889 else
7890 te = got_object_tree_get_last_entry(s->tree);
7893 while (1) {
7894 if (te == NULL) {
7895 if (s->matched_entry == NULL) {
7896 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7897 return NULL;
7899 if (view->searching == TOG_SEARCH_FORWARD)
7900 te = got_object_tree_get_first_entry(s->tree);
7901 else
7902 te = got_object_tree_get_last_entry(s->tree);
7905 if (match_tree_entry(te, &view->regex)) {
7906 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7907 s->matched_entry = te;
7908 break;
7911 if (view->searching == TOG_SEARCH_FORWARD)
7912 te = got_tree_entry_get_next(s->tree, te);
7913 else
7914 te = got_tree_entry_get_prev(s->tree, te);
7917 if (s->matched_entry) {
7918 s->first_displayed_entry = s->matched_entry;
7919 s->selected = 0;
7922 return NULL;
7925 static const struct got_error *
7926 show_tree_view(struct tog_view *view)
7928 const struct got_error *err = NULL;
7929 struct tog_tree_view_state *s = &view->state.tree;
7930 char *parent_path;
7932 err = tree_entry_path(&parent_path, &s->parents, NULL);
7933 if (err)
7934 return err;
7936 err = draw_tree_entries(view, parent_path);
7937 free(parent_path);
7939 view_border(view);
7940 return err;
7943 static const struct got_error *
7944 tree_goto_line(struct tog_view *view, int nlines)
7946 const struct got_error *err = NULL;
7947 struct tog_tree_view_state *s = &view->state.tree;
7948 struct got_tree_entry **fte, **lte, **ste;
7949 int g, last, first = 1, i = 1;
7950 int root = s->tree == s->root;
7951 int off = root ? 1 : 2;
7953 g = view->gline;
7954 view->gline = 0;
7956 if (g == 0)
7957 g = 1;
7958 else if (g > got_object_tree_get_nentries(s->tree))
7959 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7961 fte = &s->first_displayed_entry;
7962 lte = &s->last_displayed_entry;
7963 ste = &s->selected_entry;
7965 if (*fte != NULL) {
7966 first = got_tree_entry_get_index(*fte);
7967 first += off; /* account for ".." */
7969 last = got_tree_entry_get_index(*lte);
7970 last += off;
7972 if (g >= first && g <= last && g - first < nlines) {
7973 s->selected = g - first;
7974 return NULL; /* gline is on the current page */
7977 if (*ste != NULL) {
7978 i = got_tree_entry_get_index(*ste);
7979 i += off;
7982 if (i < g) {
7983 err = tree_scroll_down(view, g - i);
7984 if (err)
7985 return err;
7986 if (got_tree_entry_get_index(*lte) >=
7987 got_object_tree_get_nentries(s->tree) - 1 &&
7988 first + s->selected < g &&
7989 s->selected < s->ndisplayed - 1) {
7990 first = got_tree_entry_get_index(*fte);
7991 first += off;
7992 s->selected = g - first;
7994 } else if (i > g)
7995 tree_scroll_up(s, i - g);
7997 if (g < nlines &&
7998 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7999 s->selected = g - 1;
8001 return NULL;
8004 static const struct got_error *
8005 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
8007 const struct got_error *err = NULL;
8008 struct tog_tree_view_state *s = &view->state.tree;
8009 struct got_tree_entry *te;
8010 int n, nscroll = view->nlines - 3;
8012 if (view->gline)
8013 return tree_goto_line(view, nscroll);
8015 switch (ch) {
8016 case '0':
8017 case '$':
8018 case KEY_RIGHT:
8019 case 'l':
8020 case KEY_LEFT:
8021 case 'h':
8022 horizontal_scroll_input(view, ch);
8023 break;
8024 case 'i':
8025 s->show_ids = !s->show_ids;
8026 view->count = 0;
8027 break;
8028 case 'L':
8029 view->count = 0;
8030 if (!s->selected_entry)
8031 break;
8032 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8033 break;
8034 case 'R':
8035 view->count = 0;
8036 err = view_request_new(new_view, view, TOG_VIEW_REF);
8037 break;
8038 case 'g':
8039 case '=':
8040 case KEY_HOME:
8041 s->selected = 0;
8042 view->count = 0;
8043 if (s->tree == s->root)
8044 s->first_displayed_entry =
8045 got_object_tree_get_first_entry(s->tree);
8046 else
8047 s->first_displayed_entry = NULL;
8048 break;
8049 case 'G':
8050 case '*':
8051 case KEY_END: {
8052 int eos = view->nlines - 3;
8054 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8055 --eos; /* border */
8056 s->selected = 0;
8057 view->count = 0;
8058 te = got_object_tree_get_last_entry(s->tree);
8059 for (n = 0; n < eos; n++) {
8060 if (te == NULL) {
8061 if (s->tree != s->root) {
8062 s->first_displayed_entry = NULL;
8063 n++;
8065 break;
8067 s->first_displayed_entry = te;
8068 te = got_tree_entry_get_prev(s->tree, te);
8070 if (n > 0)
8071 s->selected = n - 1;
8072 break;
8074 case 'k':
8075 case KEY_UP:
8076 case CTRL('p'):
8077 if (s->selected > 0) {
8078 s->selected--;
8079 break;