Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
24 #include <curses.h>
25 #include <panel.h>
26 #include <locale.h>
27 #include <sha1.h>
28 #include <sha2.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #include <string.h>
35 #include <err.h>
36 #include <unistd.h>
37 #include <limits.h>
38 #include <wchar.h>
39 #include <time.h>
40 #include <pthread.h>
41 #include <libgen.h>
42 #include <regex.h>
43 #include <sched.h>
45 #include "got_version.h"
46 #include "got_error.h"
47 #include "got_object.h"
48 #include "got_reference.h"
49 #include "got_repository.h"
50 #include "got_diff.h"
51 #include "got_opentemp.h"
52 #include "got_utf8.h"
53 #include "got_cancel.h"
54 #include "got_commit_graph.h"
55 #include "got_blame.h"
56 #include "got_privsep.h"
57 #include "got_path.h"
58 #include "got_worktree.h"
59 #include "got_keyword.h"
61 #ifndef MIN
62 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
63 #endif
65 #ifndef MAX
66 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
67 #endif
69 #define CTRL(x) ((x) & 0x1f)
71 #ifndef nitems
72 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
73 #endif
75 struct tog_cmd {
76 const char *name;
77 const struct got_error *(*cmd_main)(int, char *[]);
78 void (*cmd_usage)(void);
79 };
81 __dead static void usage(int, int);
82 __dead static void usage_log(void);
83 __dead static void usage_diff(void);
84 __dead static void usage_blame(void);
85 __dead static void usage_tree(void);
86 __dead static void usage_ref(void);
88 static const struct got_error* cmd_log(int, char *[]);
89 static const struct got_error* cmd_diff(int, char *[]);
90 static const struct got_error* cmd_blame(int, char *[]);
91 static const struct got_error* cmd_tree(int, char *[]);
92 static const struct got_error* cmd_ref(int, char *[]);
94 static const struct tog_cmd tog_commands[] = {
95 { "log", cmd_log, usage_log },
96 { "diff", cmd_diff, usage_diff },
97 { "blame", cmd_blame, usage_blame },
98 { "tree", cmd_tree, usage_tree },
99 { "ref", cmd_ref, usage_ref },
100 };
102 enum tog_view_type {
103 TOG_VIEW_DIFF,
104 TOG_VIEW_LOG,
105 TOG_VIEW_BLAME,
106 TOG_VIEW_TREE,
107 TOG_VIEW_REF,
108 TOG_VIEW_HELP
109 };
111 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
112 enum tog_keymap_type {
113 TOG_KEYMAP_KEYS = -2,
114 TOG_KEYMAP_GLOBAL,
115 TOG_KEYMAP_DIFF,
116 TOG_KEYMAP_LOG,
117 TOG_KEYMAP_BLAME,
118 TOG_KEYMAP_TREE,
119 TOG_KEYMAP_REF,
120 TOG_KEYMAP_HELP
121 };
123 enum tog_view_mode {
124 TOG_VIEW_SPLIT_NONE,
125 TOG_VIEW_SPLIT_VERT,
126 TOG_VIEW_SPLIT_HRZN
127 };
129 #define HSPLIT_SCALE 0.3f /* default horizontal split scale */
131 #define TOG_EOF_STRING "(END)"
133 struct commit_queue_entry {
134 TAILQ_ENTRY(commit_queue_entry) entry;
135 struct got_object_id *id;
136 struct got_commit_object *commit;
137 int idx;
138 };
139 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
140 struct commit_queue {
141 int ncommits;
142 struct commit_queue_head head;
143 };
145 struct tog_color {
146 STAILQ_ENTRY(tog_color) entry;
147 regex_t regex;
148 short colorpair;
149 };
150 STAILQ_HEAD(tog_colors, tog_color);
152 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
153 static struct got_reflist_object_id_map *tog_refs_idmap;
154 static struct {
155 struct got_object_id *id;
156 int idx;
157 char marker;
158 } tog_base_commit;
159 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
161 static const struct got_error *
162 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
163 struct got_reference* re2)
165 const char *name1 = got_ref_get_name(re1);
166 const char *name2 = got_ref_get_name(re2);
167 int isbackup1, isbackup2;
169 /* Sort backup refs towards the bottom of the list. */
170 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
171 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
172 if (!isbackup1 && isbackup2) {
173 *cmp = -1;
174 return NULL;
175 } else if (isbackup1 && !isbackup2) {
176 *cmp = 1;
177 return NULL;
180 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
181 return NULL;
184 static const struct got_error *
185 tog_load_refs(struct got_repository *repo, int sort_by_date)
187 const struct got_error *err;
189 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
190 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
191 repo);
192 if (err)
193 return err;
195 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
196 repo);
199 static void
200 tog_free_refs(void)
202 if (tog_refs_idmap) {
203 got_reflist_object_id_map_free(tog_refs_idmap);
204 tog_refs_idmap = NULL;
206 got_ref_list_free(&tog_refs);
209 static const struct got_error *
210 add_color(struct tog_colors *colors, const char *pattern,
211 int idx, short color)
213 const struct got_error *err = NULL;
214 struct tog_color *tc;
215 int regerr = 0;
217 if (idx < 1 || idx > COLOR_PAIRS - 1)
218 return NULL;
220 init_pair(idx, color, -1);
222 tc = calloc(1, sizeof(*tc));
223 if (tc == NULL)
224 return got_error_from_errno("calloc");
225 regerr = regcomp(&tc->regex, pattern,
226 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
227 if (regerr) {
228 static char regerr_msg[512];
229 static char err_msg[512];
230 regerror(regerr, &tc->regex, regerr_msg,
231 sizeof(regerr_msg));
232 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
233 regerr_msg);
234 err = got_error_msg(GOT_ERR_REGEX, err_msg);
235 free(tc);
236 return err;
238 tc->colorpair = idx;
239 STAILQ_INSERT_HEAD(colors, tc, entry);
240 return NULL;
243 static void
244 free_colors(struct tog_colors *colors)
246 struct tog_color *tc;
248 while (!STAILQ_EMPTY(colors)) {
249 tc = STAILQ_FIRST(colors);
250 STAILQ_REMOVE_HEAD(colors, entry);
251 regfree(&tc->regex);
252 free(tc);
256 static struct tog_color *
257 get_color(struct tog_colors *colors, int colorpair)
259 struct tog_color *tc = NULL;
261 STAILQ_FOREACH(tc, colors, entry) {
262 if (tc->colorpair == colorpair)
263 return tc;
266 return NULL;
269 static int
270 default_color_value(const char *envvar)
272 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
273 return COLOR_MAGENTA;
274 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
275 return COLOR_CYAN;
276 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
277 return COLOR_YELLOW;
278 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
279 return COLOR_GREEN;
280 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
281 return COLOR_MAGENTA;
282 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
283 return COLOR_MAGENTA;
284 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
285 return COLOR_CYAN;
286 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
287 return COLOR_GREEN;
288 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
289 return COLOR_GREEN;
290 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
291 return COLOR_CYAN;
292 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
293 return COLOR_YELLOW;
294 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
295 return COLOR_GREEN;
296 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
297 return COLOR_MAGENTA;
298 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
299 return COLOR_YELLOW;
300 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
301 return COLOR_CYAN;
303 return -1;
306 static int
307 get_color_value(const char *envvar)
309 const char *val = getenv(envvar);
311 if (val == NULL)
312 return default_color_value(envvar);
314 if (strcasecmp(val, "black") == 0)
315 return COLOR_BLACK;
316 if (strcasecmp(val, "red") == 0)
317 return COLOR_RED;
318 if (strcasecmp(val, "green") == 0)
319 return COLOR_GREEN;
320 if (strcasecmp(val, "yellow") == 0)
321 return COLOR_YELLOW;
322 if (strcasecmp(val, "blue") == 0)
323 return COLOR_BLUE;
324 if (strcasecmp(val, "magenta") == 0)
325 return COLOR_MAGENTA;
326 if (strcasecmp(val, "cyan") == 0)
327 return COLOR_CYAN;
328 if (strcasecmp(val, "white") == 0)
329 return COLOR_WHITE;
330 if (strcasecmp(val, "default") == 0)
331 return -1;
333 return default_color_value(envvar);
336 struct tog_diff_view_state {
337 struct got_object_id *id1, *id2;
338 const char *label1, *label2;
339 char *action;
340 FILE *f, *f1, *f2;
341 int fd1, fd2;
342 int lineno;
343 int first_displayed_line;
344 int last_displayed_line;
345 int eof;
346 int diff_context;
347 int ignore_whitespace;
348 int force_text_diff;
349 struct got_repository *repo;
350 struct got_diff_line *lines;
351 size_t nlines;
352 int matched_line;
353 int selected_line;
355 /* passed from log or blame view; may be NULL */
356 struct tog_view *parent_view;
357 };
359 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
360 static volatile sig_atomic_t tog_thread_error;
362 struct tog_log_thread_args {
363 pthread_cond_t need_commits;
364 pthread_cond_t commit_loaded;
365 int commits_needed;
366 int load_all;
367 struct got_commit_graph *graph;
368 struct commit_queue *real_commits;
369 const char *in_repo_path;
370 struct got_object_id *start_id;
371 struct got_repository *repo;
372 int *pack_fds;
373 int log_complete;
374 pthread_cond_t log_loaded;
375 sig_atomic_t *quit;
376 struct commit_queue_entry **first_displayed_entry;
377 struct commit_queue_entry **selected_entry;
378 int *searching;
379 int *search_next_done;
380 regex_t *regex;
381 int *limiting;
382 int limit_match;
383 regex_t *limit_regex;
384 struct commit_queue *limit_commits;
385 struct got_worktree *worktree;
386 int need_commit_marker;
387 };
389 struct tog_log_view_state {
390 struct commit_queue *commits;
391 struct commit_queue_entry *first_displayed_entry;
392 struct commit_queue_entry *last_displayed_entry;
393 struct commit_queue_entry *selected_entry;
394 struct commit_queue_entry *marked_entry;
395 struct commit_queue real_commits;
396 int selected;
397 char *in_repo_path;
398 char *head_ref_name;
399 int log_branches;
400 struct got_repository *repo;
401 struct got_object_id *start_id;
402 sig_atomic_t quit;
403 pthread_t thread;
404 struct tog_log_thread_args thread_args;
405 struct commit_queue_entry *matched_entry;
406 struct commit_queue_entry *search_entry;
407 struct tog_colors colors;
408 int use_committer;
409 int limit_view;
410 regex_t limit_regex;
411 struct commit_queue limit_commits;
412 };
414 #define TOG_COLOR_DIFF_MINUS 1
415 #define TOG_COLOR_DIFF_PLUS 2
416 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
417 #define TOG_COLOR_DIFF_META 4
418 #define TOG_COLOR_TREE_SUBMODULE 5
419 #define TOG_COLOR_TREE_SYMLINK 6
420 #define TOG_COLOR_TREE_DIRECTORY 7
421 #define TOG_COLOR_TREE_EXECUTABLE 8
422 #define TOG_COLOR_COMMIT 9
423 #define TOG_COLOR_AUTHOR 10
424 #define TOG_COLOR_DATE 11
425 #define TOG_COLOR_REFS_HEADS 12
426 #define TOG_COLOR_REFS_TAGS 13
427 #define TOG_COLOR_REFS_REMOTES 14
428 #define TOG_COLOR_REFS_BACKUP 15
430 struct tog_blame_cb_args {
431 struct tog_blame_line *lines; /* one per line */
432 int nlines;
434 struct tog_view *view;
435 struct got_object_id *commit_id;
436 int *quit;
437 };
439 struct tog_blame_thread_args {
440 const char *path;
441 struct got_repository *repo;
442 struct tog_blame_cb_args *cb_args;
443 int *complete;
444 got_cancel_cb cancel_cb;
445 void *cancel_arg;
446 pthread_cond_t blame_complete;
447 };
449 struct tog_blame {
450 FILE *f;
451 off_t filesize;
452 struct tog_blame_line *lines;
453 int nlines;
454 off_t *line_offsets;
455 pthread_t thread;
456 struct tog_blame_thread_args thread_args;
457 struct tog_blame_cb_args cb_args;
458 const char *path;
459 int *pack_fds;
460 };
462 struct tog_blame_view_state {
463 int first_displayed_line;
464 int last_displayed_line;
465 int selected_line;
466 int last_diffed_line;
467 int blame_complete;
468 int eof;
469 int done;
470 struct got_object_id_queue blamed_commits;
471 struct got_object_qid *blamed_commit;
472 char *path;
473 struct got_repository *repo;
474 struct got_object_id *commit_id;
475 struct got_object_id *id_to_log;
476 struct tog_blame blame;
477 int matched_line;
478 struct tog_colors colors;
479 };
481 struct tog_parent_tree {
482 TAILQ_ENTRY(tog_parent_tree) entry;
483 struct got_tree_object *tree;
484 struct got_tree_entry *first_displayed_entry;
485 struct got_tree_entry *selected_entry;
486 int selected;
487 };
489 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
491 struct tog_tree_view_state {
492 char *tree_label;
493 struct got_object_id *commit_id;/* commit which this tree belongs to */
494 struct got_tree_object *root; /* the commit's root tree entry */
495 struct got_tree_object *tree; /* currently displayed (sub-)tree */
496 struct got_tree_entry *first_displayed_entry;
497 struct got_tree_entry *last_displayed_entry;
498 struct got_tree_entry *selected_entry;
499 int ndisplayed, selected, show_ids;
500 struct tog_parent_trees parents; /* parent trees of current sub-tree */
501 char *head_ref_name;
502 struct got_repository *repo;
503 struct got_tree_entry *matched_entry;
504 struct tog_colors colors;
505 };
507 struct tog_reflist_entry {
508 TAILQ_ENTRY(tog_reflist_entry) entry;
509 struct got_reference *ref;
510 int idx;
511 };
513 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
515 struct tog_ref_view_state {
516 struct tog_reflist_head refs;
517 struct tog_reflist_entry *first_displayed_entry;
518 struct tog_reflist_entry *last_displayed_entry;
519 struct tog_reflist_entry *selected_entry;
520 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
521 struct got_repository *repo;
522 struct tog_reflist_entry *matched_entry;
523 struct tog_colors colors;
524 };
526 struct tog_help_view_state {
527 FILE *f;
528 off_t *line_offsets;
529 size_t nlines;
530 int lineno;
531 int first_displayed_line;
532 int last_displayed_line;
533 int eof;
534 int matched_line;
535 int selected_line;
536 int all;
537 enum tog_keymap_type type;
538 };
540 #define GENERATE_HELP \
541 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
542 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
543 KEY_("k C-p Up", "Move cursor or page up one line"), \
544 KEY_("j C-n Down", "Move cursor or page down one line"), \
545 KEY_("C-b b PgUp", "Scroll the view up one page"), \
546 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
547 KEY_("C-u u", "Scroll the view up one half page"), \
548 KEY_("C-d d", "Scroll the view down one half page"), \
549 KEY_("g", "Go to line N (default: first line)"), \
550 KEY_("Home =", "Go to the first line"), \
551 KEY_("G", "Go to line N (default: last line)"), \
552 KEY_("End *", "Go to the last line"), \
553 KEY_("l Right", "Scroll the view right"), \
554 KEY_("h Left", "Scroll the view left"), \
555 KEY_("$", "Scroll view to the rightmost position"), \
556 KEY_("0", "Scroll view to the leftmost position"), \
557 KEY_("-", "Decrease size of the focussed split"), \
558 KEY_("+", "Increase size of the focussed split"), \
559 KEY_("Tab", "Switch focus between views"), \
560 KEY_("F", "Toggle fullscreen mode"), \
561 KEY_("S", "Switch split-screen layout"), \
562 KEY_("/", "Open prompt to enter search term"), \
563 KEY_("n", "Find next line/token matching the current search term"), \
564 KEY_("N", "Find previous line/token matching the current search term"),\
565 KEY_("q", "Quit the focussed view; Quit help screen"), \
566 KEY_("Q", "Quit tog"), \
568 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
569 KEY_("< ,", "Move cursor up one commit"), \
570 KEY_("> .", "Move cursor down one commit"), \
571 KEY_("Enter", "Open diff view of the selected commit"), \
572 KEY_("B", "Reload the log view and toggle display of merged commits"), \
573 KEY_("R", "Open ref view of all repository references"), \
574 KEY_("T", "Display tree view of the repository from the selected" \
575 " commit"), \
576 KEY_("m", "Mark or unmark the selected entry for diffing with the " \
577 "next selected commit"), \
578 KEY_("@", "Toggle between displaying author and committer name"), \
579 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
580 KEY_("C-g Backspace", "Cancel current search or log operation"), \
581 KEY_("C-l", "Reload the log view with new commits in the repository"), \
583 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
584 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
585 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
586 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
587 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
588 " data"), \
589 KEY_("p", "Write diff to a patch file in /tmp"), \
590 KEY_("(", "Go to the previous file in the diff"), \
591 KEY_(")", "Go to the next file in the diff"), \
592 KEY_("{", "Go to the previous hunk in the diff"), \
593 KEY_("}", "Go to the next hunk in the diff"), \
594 KEY_("[", "Decrease the number of context lines"), \
595 KEY_("]", "Increase the number of context lines"), \
596 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
598 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
599 KEY_("Enter", "Display diff view of the selected line's commit"), \
600 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
601 KEY_("L", "Open log view for the currently selected annotated line"), \
602 KEY_("C", "Reload view with the previously blamed commit"), \
603 KEY_("c", "Reload view with the version of the file found in the" \
604 " selected line's commit"), \
605 KEY_("p", "Reload view with the version of the file found in the" \
606 " selected line's parent commit"), \
608 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
609 KEY_("Enter", "Enter selected directory or open blame view of the" \
610 " selected file"), \
611 KEY_("L", "Open log view for the selected entry"), \
612 KEY_("R", "Open ref view of all repository references"), \
613 KEY_("i", "Show object IDs for all tree entries"), \
614 KEY_("Backspace", "Return to the parent directory"), \
616 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
617 KEY_("Enter", "Display log view of the selected reference"), \
618 KEY_("T", "Display tree view of the selected reference"), \
619 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
620 KEY_("m", "Toggle display of last modified date for each reference"), \
621 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
622 KEY_("C-l", "Reload view with all repository references")
624 struct tog_key_map {
625 const char *keys;
626 const char *info;
627 enum tog_keymap_type type;
628 };
630 /* curses io for tog regress */
631 struct tog_io {
632 FILE *cin;
633 FILE *cout;
634 FILE *f;
635 FILE *sdump;
636 char *input_str;
637 int wait_for_ui;
638 } tog_io;
639 static int using_mock_io;
641 #define TOG_KEY_SCRDUMP SHRT_MIN
643 /*
644 * We implement two types of views: parent views and child views.
646 * The 'Tab' key switches focus between a parent view and its child view.
647 * Child views are shown side-by-side to their parent view, provided
648 * there is enough screen estate.
650 * When a new view is opened from within a parent view, this new view
651 * becomes a child view of the parent view, replacing any existing child.
653 * When a new view is opened from within a child view, this new view
654 * becomes a parent view which will obscure the views below until the
655 * user quits the new parent view by typing 'q'.
657 * This list of views contains parent views only.
658 * Child views are only pointed to by their parent view.
659 */
660 TAILQ_HEAD(tog_view_list_head, tog_view);
662 struct tog_view {
663 TAILQ_ENTRY(tog_view) entry;
664 WINDOW *window;
665 PANEL *panel;
666 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
667 int resized_y, resized_x; /* begin_y/x based on user resizing */
668 int maxx, x; /* max column and current start column */
669 int lines, cols; /* copies of LINES and COLS */
670 int nscrolled, offset; /* lines scrolled and hsplit line offset */
671 int gline, hiline; /* navigate to and highlight this nG line */
672 int ch, count; /* current keymap and count prefix */
673 int resized; /* set when in a resize event */
674 int focussed; /* Only set on one parent or child view at a time. */
675 int dying;
676 struct tog_view *parent;
677 struct tog_view *child;
679 /*
680 * This flag is initially set on parent views when a new child view
681 * is created. It gets toggled when the 'Tab' key switches focus
682 * between parent and child.
683 * The flag indicates whether focus should be passed on to our child
684 * view if this parent view gets picked for focus after another parent
685 * view was closed. This prevents child views from losing focus in such
686 * situations.
687 */
688 int focus_child;
690 enum tog_view_mode mode;
691 /* type-specific state */
692 enum tog_view_type type;
693 union {
694 struct tog_diff_view_state diff;
695 struct tog_log_view_state log;
696 struct tog_blame_view_state blame;
697 struct tog_tree_view_state tree;
698 struct tog_ref_view_state ref;
699 struct tog_help_view_state help;
700 } state;
702 const struct got_error *(*show)(struct tog_view *);
703 const struct got_error *(*input)(struct tog_view **,
704 struct tog_view *, int);
705 const struct got_error *(*reset)(struct tog_view *);
706 const struct got_error *(*resize)(struct tog_view *, int);
707 const struct got_error *(*close)(struct tog_view *);
709 const struct got_error *(*search_start)(struct tog_view *);
710 const struct got_error *(*search_next)(struct tog_view *);
711 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
712 int **, int **, int **, int **);
713 int search_started;
714 int searching;
715 #define TOG_SEARCH_FORWARD 1
716 #define TOG_SEARCH_BACKWARD 2
717 int search_next_done;
718 #define TOG_SEARCH_HAVE_MORE 1
719 #define TOG_SEARCH_NO_MORE 2
720 #define TOG_SEARCH_HAVE_NONE 3
721 regex_t regex;
722 regmatch_t regmatch;
723 const char *action;
724 };
726 static const struct got_error *open_diff_view(struct tog_view *,
727 struct got_object_id *, struct got_object_id *,
728 const char *, const char *, int, int, int, struct tog_view *,
729 struct got_repository *);
730 static const struct got_error *show_diff_view(struct tog_view *);
731 static const struct got_error *input_diff_view(struct tog_view **,
732 struct tog_view *, int);
733 static const struct got_error *reset_diff_view(struct tog_view *);
734 static const struct got_error* close_diff_view(struct tog_view *);
735 static const struct got_error *search_start_diff_view(struct tog_view *);
736 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
737 size_t *, int **, int **, int **, int **);
738 static const struct got_error *search_next_view_match(struct tog_view *);
740 static const struct got_error *open_log_view(struct tog_view *,
741 struct got_object_id *, struct got_repository *,
742 const char *, const char *, int, struct got_worktree *);
743 static const struct got_error * show_log_view(struct tog_view *);
744 static const struct got_error *input_log_view(struct tog_view **,
745 struct tog_view *, int);
746 static const struct got_error *resize_log_view(struct tog_view *, int);
747 static const struct got_error *close_log_view(struct tog_view *);
748 static const struct got_error *search_start_log_view(struct tog_view *);
749 static const struct got_error *search_next_log_view(struct tog_view *);
751 static const struct got_error *open_blame_view(struct tog_view *, char *,
752 struct got_object_id *, struct got_repository *);
753 static const struct got_error *show_blame_view(struct tog_view *);
754 static const struct got_error *input_blame_view(struct tog_view **,
755 struct tog_view *, int);
756 static const struct got_error *reset_blame_view(struct tog_view *);
757 static const struct got_error *close_blame_view(struct tog_view *);
758 static const struct got_error *search_start_blame_view(struct tog_view *);
759 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
760 size_t *, int **, int **, int **, int **);
762 static const struct got_error *open_tree_view(struct tog_view *,
763 struct got_object_id *, const char *, struct got_repository *);
764 static const struct got_error *show_tree_view(struct tog_view *);
765 static const struct got_error *input_tree_view(struct tog_view **,
766 struct tog_view *, int);
767 static const struct got_error *close_tree_view(struct tog_view *);
768 static const struct got_error *search_start_tree_view(struct tog_view *);
769 static const struct got_error *search_next_tree_view(struct tog_view *);
771 static const struct got_error *open_ref_view(struct tog_view *,
772 struct got_repository *);
773 static const struct got_error *show_ref_view(struct tog_view *);
774 static const struct got_error *input_ref_view(struct tog_view **,
775 struct tog_view *, int);
776 static const struct got_error *close_ref_view(struct tog_view *);
777 static const struct got_error *search_start_ref_view(struct tog_view *);
778 static const struct got_error *search_next_ref_view(struct tog_view *);
780 static const struct got_error *open_help_view(struct tog_view *,
781 struct tog_view *);
782 static const struct got_error *show_help_view(struct tog_view *);
783 static const struct got_error *input_help_view(struct tog_view **,
784 struct tog_view *, int);
785 static const struct got_error *reset_help_view(struct tog_view *);
786 static const struct got_error* close_help_view(struct tog_view *);
787 static const struct got_error *search_start_help_view(struct tog_view *);
788 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
789 size_t *, int **, int **, int **, int **);
791 static volatile sig_atomic_t tog_sigwinch_received;
792 static volatile sig_atomic_t tog_sigpipe_received;
793 static volatile sig_atomic_t tog_sigcont_received;
794 static volatile sig_atomic_t tog_sigint_received;
795 static volatile sig_atomic_t tog_sigterm_received;
797 static void
798 tog_sigwinch(int signo)
800 tog_sigwinch_received = 1;
803 static void
804 tog_sigpipe(int signo)
806 tog_sigpipe_received = 1;
809 static void
810 tog_sigcont(int signo)
812 tog_sigcont_received = 1;
815 static void
816 tog_sigint(int signo)
818 tog_sigint_received = 1;
821 static void
822 tog_sigterm(int signo)
824 tog_sigterm_received = 1;
827 static int
828 tog_fatal_signal_received(void)
830 return (tog_sigpipe_received ||
831 tog_sigint_received || tog_sigterm_received);
834 static const struct got_error *
835 view_close(struct tog_view *view)
837 const struct got_error *err = NULL, *child_err = NULL;
839 if (view->child) {
840 child_err = view_close(view->child);
841 view->child = NULL;
843 if (view->close)
844 err = view->close(view);
845 if (view->panel) {
846 del_panel(view->panel);
847 view->panel = NULL;
849 if (view->window) {
850 delwin(view->window);
851 view->window = NULL;
853 free(view);
854 return err ? err : child_err;
857 static struct tog_view *
858 view_open(int nlines, int ncols, int begin_y, int begin_x,
859 enum tog_view_type type)
861 struct tog_view *view = calloc(1, sizeof(*view));
863 if (view == NULL)
864 return NULL;
866 view->type = type;
867 view->lines = LINES;
868 view->cols = COLS;
869 view->nlines = nlines ? nlines : LINES - begin_y;
870 view->ncols = ncols ? ncols : COLS - begin_x;
871 view->begin_y = begin_y;
872 view->begin_x = begin_x;
873 view->window = newwin(nlines, ncols, begin_y, begin_x);
874 if (view->window == NULL) {
875 view_close(view);
876 return NULL;
878 view->panel = new_panel(view->window);
879 if (view->panel == NULL ||
880 set_panel_userptr(view->panel, view) != OK) {
881 view_close(view);
882 return NULL;
885 keypad(view->window, TRUE);
886 return view;
889 static int
890 view_split_begin_x(int begin_x)
892 if (begin_x > 0 || COLS < 120)
893 return 0;
894 return (COLS - MAX(COLS / 2, 80));
897 /* XXX Stub till we decide what to do. */
898 static int
899 view_split_begin_y(int lines)
901 return lines * HSPLIT_SCALE;
904 static const struct got_error *view_resize(struct tog_view *);
906 static const struct got_error *
907 view_splitscreen(struct tog_view *view)
909 const struct got_error *err = NULL;
911 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
912 if (view->resized_y && view->resized_y < view->lines)
913 view->begin_y = view->resized_y;
914 else
915 view->begin_y = view_split_begin_y(view->nlines);
916 view->begin_x = 0;
917 } else if (!view->resized) {
918 if (view->resized_x && view->resized_x < view->cols - 1 &&
919 view->cols > 119)
920 view->begin_x = view->resized_x;
921 else
922 view->begin_x = view_split_begin_x(0);
923 view->begin_y = 0;
925 view->nlines = LINES - view->begin_y;
926 view->ncols = COLS - view->begin_x;
927 view->lines = LINES;
928 view->cols = COLS;
929 err = view_resize(view);
930 if (err)
931 return err;
933 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
934 view->parent->nlines = view->begin_y;
936 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
937 return got_error_from_errno("mvwin");
939 return NULL;
942 static const struct got_error *
943 view_fullscreen(struct tog_view *view)
945 const struct got_error *err = NULL;
947 view->begin_x = 0;
948 view->begin_y = view->resized ? view->begin_y : 0;
949 view->nlines = view->resized ? view->nlines : LINES;
950 view->ncols = COLS;
951 view->lines = LINES;
952 view->cols = COLS;
953 err = view_resize(view);
954 if (err)
955 return err;
957 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
958 return got_error_from_errno("mvwin");
960 return NULL;
963 static int
964 view_is_parent_view(struct tog_view *view)
966 return view->parent == NULL;
969 static int
970 view_is_splitscreen(struct tog_view *view)
972 return view->begin_x > 0 || view->begin_y > 0;
975 static int
976 view_is_fullscreen(struct tog_view *view)
978 return view->nlines == LINES && view->ncols == COLS;
981 static int
982 view_is_hsplit_top(struct tog_view *view)
984 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
985 view_is_splitscreen(view->child);
988 static void
989 view_border(struct tog_view *view)
991 PANEL *panel;
992 const struct tog_view *view_above;
994 if (view->parent)
995 return view_border(view->parent);
997 panel = panel_above(view->panel);
998 if (panel == NULL)
999 return;
1001 view_above = panel_userptr(panel);
1002 if (view->mode == TOG_VIEW_SPLIT_HRZN)
1003 mvwhline(view->window, view_above->begin_y - 1,
1004 view->begin_x, ACS_HLINE, view->ncols);
1005 else
1006 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
1007 ACS_VLINE, view->nlines);
1010 static const struct got_error *view_init_hsplit(struct tog_view *, int);
1011 static const struct got_error *request_log_commits(struct tog_view *);
1012 static const struct got_error *offset_selection_down(struct tog_view *);
1013 static void offset_selection_up(struct tog_view *);
1014 static void view_get_split(struct tog_view *, int *, int *);
1016 static const struct got_error *
1017 view_resize(struct tog_view *view)
1019 const struct got_error *err = NULL;
1020 int dif, nlines, ncols;
1022 dif = LINES - view->lines; /* line difference */
1024 if (view->lines > LINES)
1025 nlines = view->nlines - (view->lines - LINES);
1026 else
1027 nlines = view->nlines + (LINES - view->lines);
1028 if (view->cols > COLS)
1029 ncols = view->ncols - (view->cols - COLS);
1030 else
1031 ncols = view->ncols + (COLS - view->cols);
1033 if (view->child) {
1034 int hs = view->child->begin_y;
1036 if (!view_is_fullscreen(view))
1037 view->child->begin_x = view_split_begin_x(view->begin_x);
1038 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1039 view->child->begin_x == 0) {
1040 ncols = COLS;
1042 view_fullscreen(view->child);
1043 if (view->child->focussed)
1044 show_panel(view->child->panel);
1045 else
1046 show_panel(view->panel);
1047 } else {
1048 ncols = view->child->begin_x;
1050 view_splitscreen(view->child);
1051 show_panel(view->child->panel);
1054 * XXX This is ugly and needs to be moved into the above
1055 * logic but "works" for now and my attempts at moving it
1056 * break either 'tab' or 'F' key maps in horizontal splits.
1058 if (hs) {
1059 err = view_splitscreen(view->child);
1060 if (err)
1061 return err;
1062 if (dif < 0) { /* top split decreased */
1063 err = offset_selection_down(view);
1064 if (err)
1065 return err;
1067 view_border(view);
1068 update_panels();
1069 doupdate();
1070 show_panel(view->child->panel);
1071 nlines = view->nlines;
1073 } else if (view->parent == NULL)
1074 ncols = COLS;
1076 if (view->resize && dif > 0) {
1077 err = view->resize(view, dif);
1078 if (err)
1079 return err;
1082 if (wresize(view->window, nlines, ncols) == ERR)
1083 return got_error_from_errno("wresize");
1084 if (replace_panel(view->panel, view->window) == ERR)
1085 return got_error_from_errno("replace_panel");
1086 wclear(view->window);
1088 view->nlines = nlines;
1089 view->ncols = ncols;
1090 view->lines = LINES;
1091 view->cols = COLS;
1093 return NULL;
1096 static const struct got_error *
1097 resize_log_view(struct tog_view *view, int increase)
1099 struct tog_log_view_state *s = &view->state.log;
1100 const struct got_error *err = NULL;
1101 int n = 0;
1103 if (s->selected_entry)
1104 n = s->selected_entry->idx + view->lines - s->selected;
1107 * Request commits to account for the increased
1108 * height so we have enough to populate the view.
1110 if (s->commits->ncommits < n) {
1111 view->nscrolled = n - s->commits->ncommits + increase + 1;
1112 err = request_log_commits(view);
1115 return err;
1118 static void
1119 view_adjust_offset(struct tog_view *view, int n)
1121 if (n == 0)
1122 return;
1124 if (view->parent && view->parent->offset) {
1125 if (view->parent->offset + n >= 0)
1126 view->parent->offset += n;
1127 else
1128 view->parent->offset = 0;
1129 } else if (view->offset) {
1130 if (view->offset - n >= 0)
1131 view->offset -= n;
1132 else
1133 view->offset = 0;
1137 static const struct got_error *
1138 view_resize_split(struct tog_view *view, int resize)
1140 const struct got_error *err = NULL;
1141 struct tog_view *v = NULL;
1143 if (view->parent)
1144 v = view->parent;
1145 else
1146 v = view;
1148 if (!v->child || !view_is_splitscreen(v->child))
1149 return NULL;
1151 v->resized = v->child->resized = resize; /* lock for resize event */
1153 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1154 if (v->child->resized_y)
1155 v->child->begin_y = v->child->resized_y;
1156 if (view->parent)
1157 v->child->begin_y -= resize;
1158 else
1159 v->child->begin_y += resize;
1160 if (v->child->begin_y < 3) {
1161 view->count = 0;
1162 v->child->begin_y = 3;
1163 } else if (v->child->begin_y > LINES - 1) {
1164 view->count = 0;
1165 v->child->begin_y = LINES - 1;
1167 v->ncols = COLS;
1168 v->child->ncols = COLS;
1169 view_adjust_offset(view, resize);
1170 err = view_init_hsplit(v, v->child->begin_y);
1171 if (err)
1172 return err;
1173 v->child->resized_y = v->child->begin_y;
1174 } else {
1175 if (v->child->resized_x)
1176 v->child->begin_x = v->child->resized_x;
1177 if (view->parent)
1178 v->child->begin_x -= resize;
1179 else
1180 v->child->begin_x += resize;
1181 if (v->child->begin_x < 11) {
1182 view->count = 0;
1183 v->child->begin_x = 11;
1184 } else if (v->child->begin_x > COLS - 1) {
1185 view->count = 0;
1186 v->child->begin_x = COLS - 1;
1188 v->child->resized_x = v->child->begin_x;
1191 v->child->mode = v->mode;
1192 v->child->nlines = v->lines - v->child->begin_y;
1193 v->child->ncols = v->cols - v->child->begin_x;
1194 v->focus_child = 1;
1196 err = view_fullscreen(v);
1197 if (err)
1198 return err;
1199 err = view_splitscreen(v->child);
1200 if (err)
1201 return err;
1203 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1204 err = offset_selection_down(v->child);
1205 if (err)
1206 return err;
1209 if (v->resize)
1210 err = v->resize(v, 0);
1211 else if (v->child->resize)
1212 err = v->child->resize(v->child, 0);
1214 v->resized = v->child->resized = 0;
1216 return err;
1219 static void
1220 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1222 struct tog_view *v = src->child ? src->child : src;
1224 dst->resized_x = v->resized_x;
1225 dst->resized_y = v->resized_y;
1228 static const struct got_error *
1229 view_close_child(struct tog_view *view)
1231 const struct got_error *err = NULL;
1233 if (view->child == NULL)
1234 return NULL;
1236 err = view_close(view->child);
1237 view->child = NULL;
1238 return err;
1241 static const struct got_error *
1242 view_set_child(struct tog_view *view, struct tog_view *child)
1244 const struct got_error *err = NULL;
1246 view->child = child;
1247 child->parent = view;
1249 err = view_resize(view);
1250 if (err)
1251 return err;
1253 if (view->child->resized_x || view->child->resized_y)
1254 err = view_resize_split(view, 0);
1256 return err;
1259 static const struct got_error *view_dispatch_request(struct tog_view **,
1260 struct tog_view *, enum tog_view_type, int, int);
1262 static const struct got_error *
1263 view_request_new(struct tog_view **requested, struct tog_view *view,
1264 enum tog_view_type request)
1266 struct tog_view *new_view = NULL;
1267 const struct got_error *err;
1268 int y = 0, x = 0;
1270 *requested = NULL;
1272 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1273 view_get_split(view, &y, &x);
1275 err = view_dispatch_request(&new_view, view, request, y, x);
1276 if (err)
1277 return err;
1279 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1280 request != TOG_VIEW_HELP) {
1281 err = view_init_hsplit(view, y);
1282 if (err)
1283 return err;
1286 view->focussed = 0;
1287 new_view->focussed = 1;
1288 new_view->mode = view->mode;
1289 new_view->nlines = request == TOG_VIEW_HELP ?
1290 view->lines : view->lines - y;
1292 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1293 view_transfer_size(new_view, view);
1294 err = view_close_child(view);
1295 if (err)
1296 return err;
1297 err = view_set_child(view, new_view);
1298 if (err)
1299 return err;
1300 view->focus_child = 1;
1301 } else
1302 *requested = new_view;
1304 return NULL;
1307 static void
1308 tog_resizeterm(void)
1310 int cols, lines;
1311 struct winsize size;
1313 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1314 cols = 80; /* Default */
1315 lines = 24;
1316 } else {
1317 cols = size.ws_col;
1318 lines = size.ws_row;
1320 resize_term(lines, cols);
1323 static const struct got_error *
1324 view_search_start(struct tog_view *view, int fast_refresh)
1326 const struct got_error *err = NULL;
1327 struct tog_view *v = view;
1328 char pattern[1024];
1329 int ret;
1331 if (view->search_started) {
1332 regfree(&view->regex);
1333 view->searching = 0;
1334 memset(&view->regmatch, 0, sizeof(view->regmatch));
1336 view->search_started = 0;
1338 if (view->nlines < 1)
1339 return NULL;
1341 if (view_is_hsplit_top(view))
1342 v = view->child;
1343 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1344 v = view->parent;
1346 if (tog_io.input_str != NULL) {
1347 if (strlcpy(pattern, tog_io.input_str, sizeof(pattern)) >=
1348 sizeof(pattern))
1349 return got_error(GOT_ERR_NO_SPACE);
1350 } else {
1351 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1352 wclrtoeol(v->window);
1353 nodelay(v->window, FALSE); /* block for search term input */
1354 nocbreak();
1355 echo();
1356 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1357 wrefresh(v->window);
1358 cbreak();
1359 noecho();
1360 nodelay(v->window, TRUE);
1361 if (!fast_refresh && !using_mock_io)
1362 halfdelay(10);
1363 if (ret == ERR)
1364 return NULL;
1367 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1368 err = view->search_start(view);
1369 if (err) {
1370 regfree(&view->regex);
1371 return err;
1373 view->search_started = 1;
1374 view->searching = TOG_SEARCH_FORWARD;
1375 view->search_next_done = 0;
1376 view->search_next(view);
1379 return NULL;
1382 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1383 static const struct got_error *
1384 switch_split(struct tog_view *view)
1386 const struct got_error *err = NULL;
1387 struct tog_view *v = NULL;
1389 if (view->parent)
1390 v = view->parent;
1391 else
1392 v = view;
1394 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1395 v->mode = TOG_VIEW_SPLIT_VERT;
1396 else
1397 v->mode = TOG_VIEW_SPLIT_HRZN;
1399 if (!v->child)
1400 return NULL;
1401 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1402 v->mode = TOG_VIEW_SPLIT_NONE;
1404 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1405 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1406 v->child->begin_y = v->child->resized_y;
1407 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1408 v->child->begin_x = v->child->resized_x;
1411 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1412 v->ncols = COLS;
1413 v->child->ncols = COLS;
1414 v->child->nscrolled = LINES - v->child->nlines;
1416 err = view_init_hsplit(v, v->child->begin_y);
1417 if (err)
1418 return err;
1420 v->child->mode = v->mode;
1421 v->child->nlines = v->lines - v->child->begin_y;
1422 v->focus_child = 1;
1424 err = view_fullscreen(v);
1425 if (err)
1426 return err;
1427 err = view_splitscreen(v->child);
1428 if (err)
1429 return err;
1431 if (v->mode == TOG_VIEW_SPLIT_NONE)
1432 v->mode = TOG_VIEW_SPLIT_VERT;
1433 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1434 err = offset_selection_down(v);
1435 if (err)
1436 return err;
1437 err = offset_selection_down(v->child);
1438 if (err)
1439 return err;
1440 } else {
1441 offset_selection_up(v);
1442 offset_selection_up(v->child);
1444 if (v->resize)
1445 err = v->resize(v, 0);
1446 else if (v->child->resize)
1447 err = v->child->resize(v->child, 0);
1449 return err;
1453 * Strip trailing whitespace from str starting at byte *n;
1454 * if *n < 0, use strlen(str). Return new str length in *n.
1456 static void
1457 strip_trailing_ws(char *str, int *n)
1459 size_t x = *n;
1461 if (str == NULL || *str == '\0')
1462 return;
1464 if (x < 0)
1465 x = strlen(str);
1467 while (x-- > 0 && isspace((unsigned char)str[x]))
1468 str[x] = '\0';
1470 *n = x + 1;
1474 * Extract visible substring of line y from the curses screen
1475 * and strip trailing whitespace. If vline is set, overwrite
1476 * line[vline] with '|' because the ACS_VLINE character is
1477 * written out as 'x'. Write the line to file f.
1479 static const struct got_error *
1480 view_write_line(FILE *f, int y, int vline)
1482 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1483 int r, w;
1485 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1486 if (r == ERR)
1487 return got_error_fmt(GOT_ERR_RANGE,
1488 "failed to extract line %d", y);
1491 * In some views, lines are padded with blanks to COLS width.
1492 * Strip them so we can diff without the -b flag when testing.
1494 strip_trailing_ws(line, &r);
1496 if (vline > 0)
1497 line[vline] = '|';
1499 w = fprintf(f, "%s\n", line);
1500 if (w != r + 1) /* \n */
1501 return got_ferror(f, GOT_ERR_IO);
1503 return NULL;
1507 * Capture the visible curses screen by writing each line to the
1508 * file at the path set via the TOG_SCR_DUMP environment variable.
1510 static const struct got_error *
1511 screendump(struct tog_view *view)
1513 const struct got_error *err;
1514 int i;
1516 err = got_opentemp_truncate(tog_io.sdump);
1517 if (err)
1518 return err;
1520 if ((view->child && view->child->begin_x) ||
1521 (view->parent && view->begin_x)) {
1522 int ncols = view->child ? view->ncols : view->parent->ncols;
1524 /* vertical splitscreen */
1525 for (i = 0; i < view->nlines; ++i) {
1526 err = view_write_line(tog_io.sdump, i, ncols - 1);
1527 if (err)
1528 goto done;
1530 } else {
1531 int hline = 0;
1533 /* fullscreen or horizontal splitscreen */
1534 if ((view->child && view->child->begin_y) ||
1535 (view->parent && view->begin_y)) /* hsplit */
1536 hline = view->child ?
1537 view->child->begin_y : view->begin_y;
1539 for (i = 0; i < view->lines; i++) {
1540 if (hline && i == hline - 1) {
1541 int c;
1543 /* ACS_HLINE writes out as 'q', overwrite it */
1544 for (c = 0; c < view->cols; ++c)
1545 fputc('-', tog_io.sdump);
1546 fputc('\n', tog_io.sdump);
1547 continue;
1550 err = view_write_line(tog_io.sdump, i, 0);
1551 if (err)
1552 goto done;
1556 done:
1557 return err;
1561 * Compute view->count from numeric input. Assign total to view->count and
1562 * return first non-numeric key entered.
1564 static int
1565 get_compound_key(struct tog_view *view, int c)
1567 struct tog_view *v = view;
1568 int x, n = 0;
1570 if (view_is_hsplit_top(view))
1571 v = view->child;
1572 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1573 v = view->parent;
1575 view->count = 0;
1576 cbreak(); /* block for input */
1577 nodelay(view->window, FALSE);
1578 wmove(v->window, v->nlines - 1, 0);
1579 wclrtoeol(v->window);
1580 waddch(v->window, ':');
1582 do {
1583 x = getcurx(v->window);
1584 if (x != ERR && x < view->ncols) {
1585 waddch(v->window, c);
1586 wrefresh(v->window);
1590 * Don't overflow. Max valid request should be the greatest
1591 * between the longest and total lines; cap at 10 million.
1593 if (n >= 9999999)
1594 n = 9999999;
1595 else
1596 n = n * 10 + (c - '0');
1597 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1599 if (c == 'G' || c == 'g') { /* nG key map */
1600 view->gline = view->hiline = n;
1601 n = 0;
1602 c = 0;
1605 /* Massage excessive or inapplicable values at the input handler. */
1606 view->count = n;
1608 return c;
1611 static void
1612 action_report(struct tog_view *view)
1614 struct tog_view *v = view;
1616 if (view_is_hsplit_top(view))
1617 v = view->child;
1618 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1619 v = view->parent;
1621 wmove(v->window, v->nlines - 1, 0);
1622 wclrtoeol(v->window);
1623 wprintw(v->window, ":%s", view->action);
1624 wrefresh(v->window);
1627 * Clear action status report. Only clear in blame view
1628 * once annotating is complete, otherwise it's too fast.
1629 * In diff view, let its state control view->action lifetime.
1631 if (view->type == TOG_VIEW_BLAME) {
1632 if (view->state.blame.blame_complete)
1633 view->action = NULL;
1634 } else if (view->type == TOG_VIEW_DIFF) {
1635 view->action = view->state.diff.action;
1636 } else
1637 view->action = NULL;
1641 * Read the next line from the test script and assign
1642 * key instruction to *ch. If at EOF, set the *done flag.
1644 static const struct got_error *
1645 tog_read_script_key(FILE *script, struct tog_view *view, int *ch, int *done)
1647 const struct got_error *err = NULL;
1648 char *line = NULL;
1649 size_t linesz = 0;
1650 ssize_t n;
1653 if (view->count && --view->count) {
1654 *ch = view->ch;
1655 return NULL;
1656 } else
1657 *ch = -1;
1659 if ((n = getline(&line, &linesz, script)) == -1) {
1660 if (feof(script)) {
1661 *done = 1;
1662 goto done;
1663 } else {
1664 err = got_ferror(script, GOT_ERR_IO);
1665 goto done;
1669 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1670 tog_io.wait_for_ui = 1;
1671 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1672 *ch = KEY_ENTER;
1673 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1674 *ch = KEY_RIGHT;
1675 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1676 *ch = KEY_LEFT;
1677 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1678 *ch = KEY_DOWN;
1679 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1680 *ch = KEY_UP;
1681 else if (strncasecmp(line, "TAB", 3) == 0)
1682 *ch = '\t';
1683 else if (strncasecmp(line, "SCREENDUMP", 10) == 0)
1684 *ch = TOG_KEY_SCRDUMP;
1685 else if (isdigit((unsigned char)*line)) {
1686 char *t = line;
1688 while (isdigit((unsigned char)*t))
1689 ++t;
1690 view->ch = *ch = *t;
1691 *t = '\0';
1692 /* ignore error, view->count is 0 if instruction is invalid */
1693 view->count = strtonum(line, 0, INT_MAX, NULL);
1694 } else {
1695 *ch = *line;
1696 if (n > 2 && (*ch == '/' || *ch == '&')) {
1697 /* skip leading keymap and trim trailing newline */
1698 tog_io.input_str = strndup(line + 1, n - 2);
1699 if (tog_io.input_str == NULL) {
1700 err = got_error_from_errno("strndup");
1701 goto done;
1706 done:
1707 free(line);
1708 return err;
1711 static void
1712 log_mark_clear(struct tog_log_view_state *s)
1714 s->marked_entry = NULL;
1717 static const struct got_error *
1718 view_input(struct tog_view **new, int *done, struct tog_view *view,
1719 struct tog_view_list_head *views, int fast_refresh)
1721 const struct got_error *err = NULL;
1722 struct tog_view *v;
1723 int ch, errcode;
1725 *new = NULL;
1727 if (view->action)
1728 action_report(view);
1730 /* Clear "no matches" indicator. */
1731 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1732 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1733 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1734 view->count = 0;
1737 if (view->searching && !view->search_next_done) {
1738 errcode = pthread_mutex_unlock(&tog_mutex);
1739 if (errcode)
1740 return got_error_set_errno(errcode,
1741 "pthread_mutex_unlock");
1742 sched_yield();
1743 errcode = pthread_mutex_lock(&tog_mutex);
1744 if (errcode)
1745 return got_error_set_errno(errcode,
1746 "pthread_mutex_lock");
1747 view->search_next(view);
1748 return NULL;
1751 /* Allow threads to make progress while we are waiting for input. */
1752 errcode = pthread_mutex_unlock(&tog_mutex);
1753 if (errcode)
1754 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1756 if (using_mock_io) {
1757 err = tog_read_script_key(tog_io.f, view, &ch, done);
1758 if (err) {
1759 errcode = pthread_mutex_lock(&tog_mutex);
1760 return err;
1762 } else if (view->count && --view->count) {
1763 cbreak();
1764 nodelay(view->window, TRUE);
1765 ch = wgetch(view->window);
1766 /* let C-g or backspace abort unfinished count */
1767 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1768 view->count = 0;
1769 else
1770 ch = view->ch;
1771 } else {
1772 ch = wgetch(view->window);
1773 if (ch >= '1' && ch <= '9')
1774 view->ch = ch = get_compound_key(view, ch);
1776 if (view->hiline && ch != ERR && ch != 0)
1777 view->hiline = 0; /* key pressed, clear line highlight */
1778 nodelay(view->window, TRUE);
1779 errcode = pthread_mutex_lock(&tog_mutex);
1780 if (errcode)
1781 return got_error_set_errno(errcode, "pthread_mutex_lock");
1783 if (tog_sigwinch_received || tog_sigcont_received) {
1784 tog_resizeterm();
1785 tog_sigwinch_received = 0;
1786 tog_sigcont_received = 0;
1787 TAILQ_FOREACH(v, views, entry) {
1788 err = view_resize(v);
1789 if (err)
1790 return err;
1791 err = v->input(new, v, KEY_RESIZE);
1792 if (err)
1793 return err;
1794 if (v->child) {
1795 err = view_resize(v->child);
1796 if (err)
1797 return err;
1798 err = v->child->input(new, v->child,
1799 KEY_RESIZE);
1800 if (err)
1801 return err;
1802 if (v->child->resized_x || v->child->resized_y) {
1803 err = view_resize_split(v, 0);
1804 if (err)
1805 return err;
1811 switch (ch) {
1812 case '?':
1813 case 'H':
1814 case KEY_F(1):
1815 if (view->type == TOG_VIEW_HELP)
1816 err = view->reset(view);
1817 else
1818 err = view_request_new(new, view, TOG_VIEW_HELP);
1819 break;
1820 case '\t':
1821 view->count = 0;
1822 if (view->child) {
1823 view->focussed = 0;
1824 view->child->focussed = 1;
1825 view->focus_child = 1;
1826 } else if (view->parent) {
1827 view->focussed = 0;
1828 view->parent->focussed = 1;
1829 view->parent->focus_child = 0;
1830 if (!view_is_splitscreen(view)) {
1831 if (view->parent->resize) {
1832 err = view->parent->resize(view->parent,
1833 0);
1834 if (err)
1835 return err;
1837 offset_selection_up(view->parent);
1838 err = view_fullscreen(view->parent);
1839 if (err)
1840 return err;
1843 break;
1844 case 'q':
1845 if (view->parent != NULL) {
1846 if (view->parent->type == TOG_VIEW_LOG)
1847 log_mark_clear(&view->parent->state.log);
1849 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1850 if (view->parent->resize) {
1852 * Might need more commits
1853 * to fill fullscreen.
1855 err = view->parent->resize(
1856 view->parent, 0);
1857 if (err)
1858 break;
1860 offset_selection_up(view->parent);
1863 err = view->input(new, view, ch);
1864 view->dying = 1;
1865 break;
1866 case 'Q':
1867 *done = 1;
1868 break;
1869 case 'F':
1870 view->count = 0;
1871 if (view_is_parent_view(view)) {
1872 if (view->child == NULL)
1873 break;
1874 if (view_is_splitscreen(view->child)) {
1875 view->focussed = 0;
1876 view->child->focussed = 1;
1877 err = view_fullscreen(view->child);
1878 } else {
1879 err = view_splitscreen(view->child);
1880 if (!err)
1881 err = view_resize_split(view, 0);
1883 if (err)
1884 break;
1885 err = view->child->input(new, view->child,
1886 KEY_RESIZE);
1887 } else {
1888 if (view_is_splitscreen(view)) {
1889 view->parent->focussed = 0;
1890 view->focussed = 1;
1891 err = view_fullscreen(view);
1892 } else {
1893 err = view_splitscreen(view);
1894 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1895 err = view_resize(view->parent);
1896 if (!err)
1897 err = view_resize_split(view, 0);
1899 if (err)
1900 break;
1901 err = view->input(new, view, KEY_RESIZE);
1903 if (err)
1904 break;
1905 if (view->resize) {
1906 err = view->resize(view, 0);
1907 if (err)
1908 break;
1910 if (view->parent) {
1911 if (view->parent->resize) {
1912 err = view->parent->resize(view->parent, 0);
1913 if (err != NULL)
1914 break;
1916 err = offset_selection_down(view->parent);
1917 if (err != NULL)
1918 break;
1920 err = offset_selection_down(view);
1921 break;
1922 case 'S':
1923 view->count = 0;
1924 err = switch_split(view);
1925 break;
1926 case '-':
1927 err = view_resize_split(view, -1);
1928 break;
1929 case '+':
1930 err = view_resize_split(view, 1);
1931 break;
1932 case KEY_RESIZE:
1933 break;
1934 case '/':
1935 view->count = 0;
1936 if (view->search_start)
1937 view_search_start(view, fast_refresh);
1938 else
1939 err = view->input(new, view, ch);
1940 break;
1941 case 'N':
1942 case 'n':
1943 if (view->search_started && view->search_next) {
1944 view->searching = (ch == 'n' ?
1945 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1946 view->search_next_done = 0;
1947 view->search_next(view);
1948 } else
1949 err = view->input(new, view, ch);
1950 break;
1951 case 'A':
1952 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1953 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1954 view->action = "Patience diff algorithm";
1955 } else {
1956 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1957 view->action = "Myers diff algorithm";
1959 TAILQ_FOREACH(v, views, entry) {
1960 if (v->reset) {
1961 err = v->reset(v);
1962 if (err)
1963 return err;
1965 if (v->child && v->child->reset) {
1966 err = v->child->reset(v->child);
1967 if (err)
1968 return err;
1971 break;
1972 case TOG_KEY_SCRDUMP:
1973 err = screendump(view);
1974 break;
1975 default:
1976 err = view->input(new, view, ch);
1977 break;
1980 return err;
1983 static int
1984 view_needs_focus_indication(struct tog_view *view)
1986 if (view_is_parent_view(view)) {
1987 if (view->child == NULL || view->child->focussed)
1988 return 0;
1989 if (!view_is_splitscreen(view->child))
1990 return 0;
1991 } else if (!view_is_splitscreen(view))
1992 return 0;
1994 return view->focussed;
1997 static const struct got_error *
1998 tog_io_close(void)
2000 const struct got_error *err = NULL;
2002 if (tog_io.cin && fclose(tog_io.cin) == EOF)
2003 err = got_ferror(tog_io.cin, GOT_ERR_IO);
2004 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
2005 err = got_ferror(tog_io.cout, GOT_ERR_IO);
2006 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
2007 err = got_ferror(tog_io.f, GOT_ERR_IO);
2008 if (tog_io.sdump && fclose(tog_io.sdump) == EOF && err == NULL)
2009 err = got_ferror(tog_io.sdump, GOT_ERR_IO);
2010 if (tog_io.input_str != NULL)
2011 free(tog_io.input_str);
2013 return err;
2016 static const struct got_error *
2017 view_loop(struct tog_view *view)
2019 const struct got_error *err = NULL;
2020 struct tog_view_list_head views;
2021 struct tog_view *new_view;
2022 char *mode;
2023 int fast_refresh = 10;
2024 int done = 0, errcode;
2026 mode = getenv("TOG_VIEW_SPLIT_MODE");
2027 if (!mode || !(*mode == 'h' || *mode == 'H'))
2028 view->mode = TOG_VIEW_SPLIT_VERT;
2029 else
2030 view->mode = TOG_VIEW_SPLIT_HRZN;
2032 errcode = pthread_mutex_lock(&tog_mutex);
2033 if (errcode)
2034 return got_error_set_errno(errcode, "pthread_mutex_lock");
2036 TAILQ_INIT(&views);
2037 TAILQ_INSERT_HEAD(&views, view, entry);
2039 view->focussed = 1;
2040 err = view->show(view);
2041 if (err)
2042 return err;
2043 update_panels();
2044 doupdate();
2045 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
2046 !tog_fatal_signal_received()) {
2047 /* Refresh fast during initialization, then become slower. */
2048 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
2049 halfdelay(10); /* switch to once per second */
2051 err = view_input(&new_view, &done, view, &views, fast_refresh);
2052 if (err)
2053 break;
2055 if (view->dying && view == TAILQ_FIRST(&views) &&
2056 TAILQ_NEXT(view, entry) == NULL)
2057 done = 1;
2058 if (done) {
2059 struct tog_view *v;
2062 * When we quit, scroll the screen up a single line
2063 * so we don't lose any information.
2065 TAILQ_FOREACH(v, &views, entry) {
2066 wmove(v->window, 0, 0);
2067 wdeleteln(v->window);
2068 wnoutrefresh(v->window);
2069 if (v->child && !view_is_fullscreen(v)) {
2070 wmove(v->child->window, 0, 0);
2071 wdeleteln(v->child->window);
2072 wnoutrefresh(v->child->window);
2075 doupdate();
2078 if (view->dying) {
2079 struct tog_view *v, *prev = NULL;
2081 if (view_is_parent_view(view))
2082 prev = TAILQ_PREV(view, tog_view_list_head,
2083 entry);
2084 else if (view->parent)
2085 prev = view->parent;
2087 if (view->parent) {
2088 view->parent->child = NULL;
2089 view->parent->focus_child = 0;
2090 /* Restore fullscreen line height. */
2091 view->parent->nlines = view->parent->lines;
2092 err = view_resize(view->parent);
2093 if (err)
2094 break;
2095 /* Make resized splits persist. */
2096 view_transfer_size(view->parent, view);
2097 } else
2098 TAILQ_REMOVE(&views, view, entry);
2100 err = view_close(view);
2101 if (err)
2102 goto done;
2104 view = NULL;
2105 TAILQ_FOREACH(v, &views, entry) {
2106 if (v->focussed)
2107 break;
2109 if (view == NULL && new_view == NULL) {
2110 /* No view has focus. Try to pick one. */
2111 if (prev)
2112 view = prev;
2113 else if (!TAILQ_EMPTY(&views)) {
2114 view = TAILQ_LAST(&views,
2115 tog_view_list_head);
2117 if (view) {
2118 if (view->focus_child) {
2119 view->child->focussed = 1;
2120 view = view->child;
2121 } else
2122 view->focussed = 1;
2126 if (new_view) {
2127 struct tog_view *v, *t;
2128 /* Only allow one parent view per type. */
2129 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2130 if (v->type != new_view->type)
2131 continue;
2132 TAILQ_REMOVE(&views, v, entry);
2133 err = view_close(v);
2134 if (err)
2135 goto done;
2136 break;
2138 TAILQ_INSERT_TAIL(&views, new_view, entry);
2139 view = new_view;
2141 if (view && !done) {
2142 if (view_is_parent_view(view)) {
2143 if (view->child && view->child->focussed)
2144 view = view->child;
2145 } else {
2146 if (view->parent && view->parent->focussed)
2147 view = view->parent;
2149 show_panel(view->panel);
2150 if (view->child && view_is_splitscreen(view->child))
2151 show_panel(view->child->panel);
2152 if (view->parent && view_is_splitscreen(view)) {
2153 err = view->parent->show(view->parent);
2154 if (err)
2155 goto done;
2157 err = view->show(view);
2158 if (err)
2159 goto done;
2160 if (view->child) {
2161 err = view->child->show(view->child);
2162 if (err)
2163 goto done;
2165 update_panels();
2166 doupdate();
2169 done:
2170 while (!TAILQ_EMPTY(&views)) {
2171 const struct got_error *close_err;
2172 view = TAILQ_FIRST(&views);
2173 TAILQ_REMOVE(&views, view, entry);
2174 close_err = view_close(view);
2175 if (close_err && err == NULL)
2176 err = close_err;
2179 errcode = pthread_mutex_unlock(&tog_mutex);
2180 if (errcode && err == NULL)
2181 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2183 return err;
2186 __dead static void
2187 usage_log(void)
2189 endwin();
2190 fprintf(stderr,
2191 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2192 getprogname());
2193 exit(1);
2196 /* Create newly allocated wide-character string equivalent to a byte string. */
2197 static const struct got_error *
2198 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2200 char *vis = NULL;
2201 const struct got_error *err = NULL;
2203 *ws = NULL;
2204 *wlen = mbstowcs(NULL, s, 0);
2205 if (*wlen == (size_t)-1) {
2206 int vislen;
2207 if (errno != EILSEQ)
2208 return got_error_from_errno("mbstowcs");
2210 /* byte string invalid in current encoding; try to "fix" it */
2211 err = got_mbsavis(&vis, &vislen, s);
2212 if (err)
2213 return err;
2214 *wlen = mbstowcs(NULL, vis, 0);
2215 if (*wlen == (size_t)-1) {
2216 err = got_error_from_errno("mbstowcs"); /* give up */
2217 goto done;
2221 *ws = calloc(*wlen + 1, sizeof(**ws));
2222 if (*ws == NULL) {
2223 err = got_error_from_errno("calloc");
2224 goto done;
2227 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2228 err = got_error_from_errno("mbstowcs");
2229 done:
2230 free(vis);
2231 if (err) {
2232 free(*ws);
2233 *ws = NULL;
2234 *wlen = 0;
2236 return err;
2239 static const struct got_error *
2240 expand_tab(char **ptr, const char *src)
2242 char *dst;
2243 size_t len, n, idx = 0, sz = 0;
2245 *ptr = NULL;
2246 n = len = strlen(src);
2247 dst = malloc(n + 1);
2248 if (dst == NULL)
2249 return got_error_from_errno("malloc");
2251 while (idx < len && src[idx]) {
2252 const char c = src[idx];
2254 if (c == '\t') {
2255 size_t nb = TABSIZE - sz % TABSIZE;
2256 char *p;
2258 p = realloc(dst, n + nb);
2259 if (p == NULL) {
2260 free(dst);
2261 return got_error_from_errno("realloc");
2264 dst = p;
2265 n += nb;
2266 memset(dst + sz, ' ', nb);
2267 sz += nb;
2268 } else
2269 dst[sz++] = src[idx];
2270 ++idx;
2273 dst[sz] = '\0';
2274 *ptr = dst;
2275 return NULL;
2279 * Advance at most n columns from wline starting at offset off.
2280 * Return the index to the first character after the span operation.
2281 * Return the combined column width of all spanned wide characters in
2282 * *rcol.
2284 static int
2285 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2287 int width, i, cols = 0;
2289 if (n == 0) {
2290 *rcol = cols;
2291 return off;
2294 for (i = off; wline[i] != L'\0'; ++i) {
2295 if (wline[i] == L'\t')
2296 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2297 else
2298 width = wcwidth(wline[i]);
2300 if (width == -1) {
2301 width = 1;
2302 wline[i] = L'.';
2305 if (cols + width > n)
2306 break;
2307 cols += width;
2310 *rcol = cols;
2311 return i;
2315 * Format a line for display, ensuring that it won't overflow a width limit.
2316 * With scrolling, the width returned refers to the scrolled version of the
2317 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2319 static const struct got_error *
2320 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2321 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2323 const struct got_error *err = NULL;
2324 int cols;
2325 wchar_t *wline = NULL;
2326 char *exstr = NULL;
2327 size_t wlen;
2328 int i, scrollx;
2330 *wlinep = NULL;
2331 *widthp = 0;
2333 if (expand) {
2334 err = expand_tab(&exstr, line);
2335 if (err)
2336 return err;
2339 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2340 free(exstr);
2341 if (err)
2342 return err;
2344 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2345 wline[wlen - 1] = L'\0';
2346 wlen--;
2348 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2349 wline[wlen - 1] = L'\0';
2350 wlen--;
2353 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2355 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2356 wline[i] = L'\0';
2358 if (widthp)
2359 *widthp = cols;
2360 if (scrollxp)
2361 *scrollxp = scrollx;
2362 if (err)
2363 free(wline);
2364 else
2365 *wlinep = wline;
2366 return err;
2369 static const struct got_error*
2370 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2371 struct got_object_id *id, struct got_repository *repo)
2373 static const struct got_error *err = NULL;
2374 struct got_reflist_entry *re;
2375 char *s;
2376 const char *name;
2378 *refs_str = NULL;
2380 if (refs == NULL)
2381 return NULL;
2383 TAILQ_FOREACH(re, refs, entry) {
2384 struct got_tag_object *tag = NULL;
2385 struct got_object_id *ref_id;
2386 int cmp;
2388 name = got_ref_get_name(re->ref);
2389 if (strcmp(name, GOT_REF_HEAD) == 0)
2390 continue;
2391 if (strncmp(name, "refs/", 5) == 0)
2392 name += 5;
2393 if (strncmp(name, "got/", 4) == 0)
2394 continue;
2395 if (strncmp(name, "heads/", 6) == 0)
2396 name += 6;
2397 if (strncmp(name, "remotes/", 8) == 0) {
2398 name += 8;
2399 s = strstr(name, "/" GOT_REF_HEAD);
2400 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
2401 continue;
2403 err = got_ref_resolve(&ref_id, repo, re->ref);
2404 if (err)
2405 break;
2406 if (strncmp(name, "tags/", 5) == 0) {
2407 err = got_object_open_as_tag(&tag, repo, ref_id);
2408 if (err) {
2409 if (err->code != GOT_ERR_OBJ_TYPE) {
2410 free(ref_id);
2411 break;
2413 /* Ref points at something other than a tag. */
2414 err = NULL;
2415 tag = NULL;
2418 cmp = got_object_id_cmp(tag ?
2419 got_object_tag_get_object_id(tag) : ref_id, id);
2420 free(ref_id);
2421 if (tag)
2422 got_object_tag_close(tag);
2423 if (cmp != 0)
2424 continue;
2425 s = *refs_str;
2426 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2427 s ? ", " : "", name) == -1) {
2428 err = got_error_from_errno("asprintf");
2429 free(s);
2430 *refs_str = NULL;
2431 break;
2433 free(s);
2436 return err;
2439 static const struct got_error *
2440 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2441 int col_tab_align)
2443 char *smallerthan;
2445 smallerthan = strchr(author, '<');
2446 if (smallerthan && smallerthan[1] != '\0')
2447 author = smallerthan + 1;
2448 author[strcspn(author, "@>")] = '\0';
2449 return format_line(wauthor, author_width, NULL, author, 0, limit,
2450 col_tab_align, 0);
2453 static const struct got_error *
2454 draw_commit_marker(struct tog_view *view, char c)
2456 struct tog_color *tc;
2458 if (view->type != TOG_VIEW_LOG)
2459 return got_error_msg(GOT_ERR_NOT_IMPL, "view not supported");
2461 tc = get_color(&view->state.log.colors, TOG_COLOR_COMMIT);
2462 if (tc != NULL)
2463 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2464 if (waddch(view->window, c) == ERR)
2465 return got_error_msg(GOT_ERR_IO, "waddch");
2466 if (tc != NULL)
2467 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2469 return NULL;
2472 static const struct got_error *
2473 draw_commit(struct tog_view *view, struct commit_queue_entry *entry,
2474 const size_t date_display_cols, int author_display_cols)
2476 struct tog_log_view_state *s = &view->state.log;
2477 const struct got_error *err = NULL;
2478 struct got_commit_object *commit = entry->commit;
2479 struct got_object_id *id = entry->id;
2480 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2481 char *refs_str = NULL;
2482 char *logmsg0 = NULL, *logmsg = NULL;
2483 char *author = NULL;
2484 wchar_t *wrefstr = NULL, *wlogmsg = NULL, *wauthor = NULL;
2485 int author_width, refstr_width, logmsg_width;
2486 char *newline, *line = NULL;
2487 int col, limit, scrollx, logmsg_x;
2488 const int avail = view->ncols, marker_column = author_display_cols + 1;
2489 struct tm tm;
2490 time_t committer_time;
2491 struct tog_color *tc;
2492 struct got_reflist_head *refs;
2494 if (tog_base_commit.id != NULL && tog_base_commit.idx == -1 &&
2495 got_object_id_cmp(id, tog_base_commit.id) == 0)
2496 tog_base_commit.idx = entry->idx;
2497 if (tog_io.wait_for_ui && s->thread_args.need_commit_marker) {
2498 int rc;
2500 rc = pthread_cond_wait(&s->thread_args.log_loaded, &tog_mutex);
2501 if (rc)
2502 return got_error_set_errno(rc, "pthread_cond_wait");
2505 committer_time = got_object_commit_get_committer_time(commit);
2506 if (gmtime_r(&committer_time, &tm) == NULL)
2507 return got_error_from_errno("gmtime_r");
2508 if (strftime(datebuf, sizeof(datebuf), "%F ", &tm) == 0)
2509 return got_error(GOT_ERR_NO_SPACE);
2511 if (avail <= date_display_cols)
2512 limit = MIN(sizeof(datebuf) - 1, avail);
2513 else
2514 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2515 tc = get_color(&s->colors, TOG_COLOR_DATE);
2516 if (tc)
2517 wattr_on(view->window,
2518 COLOR_PAIR(tc->colorpair), NULL);
2519 waddnstr(view->window, datebuf, limit);
2520 if (tc)
2521 wattr_off(view->window,
2522 COLOR_PAIR(tc->colorpair), NULL);
2523 col = limit;
2524 if (col > avail)
2525 goto done;
2527 if (avail >= 120) {
2528 char *id_str;
2529 err = got_object_id_str(&id_str, id);
2530 if (err)
2531 goto done;
2532 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2533 if (tc)
2534 wattr_on(view->window,
2535 COLOR_PAIR(tc->colorpair), NULL);
2536 wprintw(view->window, "%.8s ", id_str);
2537 if (tc)
2538 wattr_off(view->window,
2539 COLOR_PAIR(tc->colorpair), NULL);
2540 free(id_str);
2541 col += 9;
2542 if (col > avail)
2543 goto done;
2546 if (s->use_committer)
2547 author = strdup(got_object_commit_get_committer(commit));
2548 else
2549 author = strdup(got_object_commit_get_author(commit));
2550 if (author == NULL) {
2551 err = got_error_from_errno("strdup");
2552 goto done;
2554 err = format_author(&wauthor, &author_width, author, avail - col, col);
2555 if (err)
2556 goto done;
2557 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2558 if (tc)
2559 wattr_on(view->window,
2560 COLOR_PAIR(tc->colorpair), NULL);
2561 waddwstr(view->window, wauthor);
2562 col += author_width;
2563 while (col < avail && author_width < author_display_cols + 2) {
2564 if (s->marked_entry == entry && author_width == marker_column) {
2565 err = draw_commit_marker(view, '>');
2566 if (err != NULL)
2567 goto done;
2568 } else if (tog_base_commit.marker != GOT_WORKTREE_STATE_UNKNOWN
2569 && author_width == marker_column &&
2570 entry->idx == tog_base_commit.idx && !s->limit_view) {
2571 err = draw_commit_marker(view, tog_base_commit.marker);
2572 if (err != NULL)
2573 goto done;
2574 } else
2575 waddch(view->window, ' ');
2576 col++;
2577 author_width++;
2579 if (tc)
2580 wattr_off(view->window,
2581 COLOR_PAIR(tc->colorpair), NULL);
2582 if (col > avail)
2583 goto done;
2585 err = got_object_commit_get_logmsg(&logmsg0, commit);
2586 if (err)
2587 goto done;
2588 logmsg = logmsg0;
2589 while (*logmsg == '\n')
2590 logmsg++;
2591 newline = strchr(logmsg, '\n');
2592 if (newline)
2593 *newline = '\0';
2595 limit = avail - col;
2596 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2597 limit--; /* for the border */
2599 /* Prepend reference labels to log message if possible .*/
2600 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, id);
2601 err = build_refs_str(&refs_str, refs, id, s->repo);
2602 if (err)
2603 goto done;
2604 if (refs_str) {
2605 char *rs;
2607 if (asprintf(&rs, "[%s]", refs_str) == -1) {
2608 err = got_error_from_errno("asprintf");
2609 goto done;
2611 err = format_line(&wrefstr, &refstr_width,
2612 &scrollx, rs, view->x, limit, col, 1);
2613 free(rs);
2614 if (err)
2615 goto done;
2616 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2617 if (tc)
2618 wattr_on(view->window,
2619 COLOR_PAIR(tc->colorpair), NULL);
2620 waddwstr(view->window, &wrefstr[scrollx]);
2621 if (tc)
2622 wattr_off(view->window,
2623 COLOR_PAIR(tc->colorpair), NULL);
2624 col += MAX(refstr_width, 0);
2625 if (col > avail)
2626 goto done;
2628 if (col < avail) {
2629 waddch(view->window, ' ');
2630 col++;
2633 if (refstr_width > 0)
2634 logmsg_x = 0;
2635 else {
2636 int unscrolled_refstr_width;
2637 size_t len = wcslen(wrefstr);
2640 * No need to check for -1 return value here since
2641 * unprintables have been replaced by span_wline().
2643 unscrolled_refstr_width = wcswidth(wrefstr, len);
2644 unscrolled_refstr_width += 1; /* trailing space */
2645 logmsg_x = view->x - unscrolled_refstr_width;
2648 limit = avail - col;
2649 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2650 limit--; /* for the border */
2651 } else
2652 logmsg_x = view->x;
2654 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, logmsg_x,
2655 limit, col, 1);
2656 if (err)
2657 goto done;
2658 waddwstr(view->window, &wlogmsg[scrollx]);
2659 col += MAX(logmsg_width, 0);
2660 while (col < avail) {
2661 waddch(view->window, ' ');
2662 col++;
2664 done:
2665 free(logmsg0);
2666 free(wlogmsg);
2667 free(wrefstr);
2668 free(refs_str);
2669 free(author);
2670 free(wauthor);
2671 free(line);
2672 return err;
2675 static struct commit_queue_entry *
2676 alloc_commit_queue_entry(struct got_commit_object *commit,
2677 struct got_object_id *id)
2679 struct commit_queue_entry *entry;
2680 struct got_object_id *dup;
2682 entry = calloc(1, sizeof(*entry));
2683 if (entry == NULL)
2684 return NULL;
2686 dup = got_object_id_dup(id);
2687 if (dup == NULL) {
2688 free(entry);
2689 return NULL;
2692 entry->id = dup;
2693 entry->commit = commit;
2694 return entry;
2697 static void
2698 pop_commit(struct commit_queue *commits)
2700 struct commit_queue_entry *entry;
2702 entry = TAILQ_FIRST(&commits->head);
2703 TAILQ_REMOVE(&commits->head, entry, entry);
2704 got_object_commit_close(entry->commit);
2705 commits->ncommits--;
2706 free(entry->id);
2707 free(entry);
2710 static void
2711 free_commits(struct commit_queue *commits)
2713 while (!TAILQ_EMPTY(&commits->head))
2714 pop_commit(commits);
2717 static const struct got_error *
2718 match_commit(int *have_match, struct got_object_id *id,
2719 struct got_commit_object *commit, regex_t *regex)
2721 const struct got_error *err = NULL;
2722 regmatch_t regmatch;
2723 char *id_str = NULL, *logmsg = NULL;
2725 *have_match = 0;
2727 err = got_object_id_str(&id_str, id);
2728 if (err)
2729 return err;
2731 err = got_object_commit_get_logmsg(&logmsg, commit);
2732 if (err)
2733 goto done;
2735 if (regexec(regex, got_object_commit_get_author(commit), 1,
2736 &regmatch, 0) == 0 ||
2737 regexec(regex, got_object_commit_get_committer(commit), 1,
2738 &regmatch, 0) == 0 ||
2739 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2740 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2741 *have_match = 1;
2742 done:
2743 free(id_str);
2744 free(logmsg);
2745 return err;
2748 static const struct got_error *
2749 queue_commits(struct tog_log_thread_args *a)
2751 const struct got_error *err = NULL;
2754 * We keep all commits open throughout the lifetime of the log
2755 * view in order to avoid having to re-fetch commits from disk
2756 * while updating the display.
2758 do {
2759 struct got_object_id id;
2760 struct got_commit_object *commit;
2761 struct commit_queue_entry *entry;
2762 int limit_match = 0;
2763 int errcode;
2765 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2766 NULL, NULL);
2767 if (err)
2768 break;
2770 err = got_object_open_as_commit(&commit, a->repo, &id);
2771 if (err)
2772 break;
2773 entry = alloc_commit_queue_entry(commit, &id);
2774 if (entry == NULL) {
2775 err = got_error_from_errno("alloc_commit_queue_entry");
2776 break;
2779 errcode = pthread_mutex_lock(&tog_mutex);
2780 if (errcode) {
2781 err = got_error_set_errno(errcode,
2782 "pthread_mutex_lock");
2783 break;
2786 entry->idx = a->real_commits->ncommits;
2787 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2788 a->real_commits->ncommits++;
2790 if (*a->limiting) {
2791 err = match_commit(&limit_match, &id, commit,
2792 a->limit_regex);
2793 if (err)
2794 break;
2796 if (limit_match) {
2797 struct commit_queue_entry *matched;
2799 matched = alloc_commit_queue_entry(
2800 entry->commit, entry->id);
2801 if (matched == NULL) {
2802 err = got_error_from_errno(
2803 "alloc_commit_queue_entry");
2804 break;
2806 matched->commit = entry->commit;
2807 got_object_commit_retain(entry->commit);
2809 matched->idx = a->limit_commits->ncommits;
2810 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2811 matched, entry);
2812 a->limit_commits->ncommits++;
2816 * This is how we signal log_thread() that we
2817 * have found a match, and that it should be
2818 * counted as a new entry for the view.
2820 a->limit_match = limit_match;
2823 if (*a->searching == TOG_SEARCH_FORWARD &&
2824 !*a->search_next_done) {
2825 int have_match;
2826 err = match_commit(&have_match, &id, commit, a->regex);
2827 if (err)
2828 break;
2830 if (*a->limiting) {
2831 if (limit_match && have_match)
2832 *a->search_next_done =
2833 TOG_SEARCH_HAVE_MORE;
2834 } else if (have_match)
2835 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2838 errcode = pthread_mutex_unlock(&tog_mutex);
2839 if (errcode && err == NULL)
2840 err = got_error_set_errno(errcode,
2841 "pthread_mutex_unlock");
2842 if (err)
2843 break;
2844 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2846 return err;
2849 static void
2850 select_commit(struct tog_log_view_state *s)
2852 struct commit_queue_entry *entry;
2853 int ncommits = 0;
2855 entry = s->first_displayed_entry;
2856 while (entry) {
2857 if (ncommits == s->selected) {
2858 s->selected_entry = entry;
2859 break;
2861 entry = TAILQ_NEXT(entry, entry);
2862 ncommits++;
2866 static const struct got_error *
2867 draw_commits(struct tog_view *view)
2869 const struct got_error *err = NULL;
2870 struct tog_log_view_state *s = &view->state.log;
2871 struct commit_queue_entry *entry = s->selected_entry;
2872 int limit = view->nlines;
2873 int width;
2874 int ncommits, author_cols = 4, refstr_cols;
2875 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2876 char *refs_str = NULL;
2877 wchar_t *wline;
2878 struct tog_color *tc;
2879 static const size_t date_display_cols = 12;
2880 struct got_reflist_head *refs;
2882 if (view_is_hsplit_top(view))
2883 --limit; /* account for border */
2885 if (s->selected_entry &&
2886 !(view->searching && view->search_next_done == 0)) {
2887 err = got_object_id_str(&id_str, s->selected_entry->id);
2888 if (err)
2889 return err;
2890 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2891 s->selected_entry->id);
2892 err = build_refs_str(&refs_str, refs, s->selected_entry->id,
2893 s->repo);
2894 if (err)
2895 goto done;
2898 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2899 halfdelay(10); /* disable fast refresh */
2901 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2902 if (asprintf(&ncommits_str, " [%d/%d] %s",
2903 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2904 (view->searching && !view->search_next_done) ?
2905 "searching..." : "loading...") == -1) {
2906 err = got_error_from_errno("asprintf");
2907 goto done;
2909 } else {
2910 const char *search_str = NULL;
2911 const char *limit_str = NULL;
2913 if (view->searching) {
2914 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2915 search_str = "no more matches";
2916 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2917 search_str = "no matches found";
2918 else if (!view->search_next_done)
2919 search_str = "searching...";
2922 if (s->limit_view && s->commits->ncommits == 0)
2923 limit_str = "no matches found";
2925 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2926 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2927 search_str ? search_str : (refs_str ? refs_str : ""),
2928 limit_str ? limit_str : "") == -1) {
2929 err = got_error_from_errno("asprintf");
2930 goto done;
2934 free(refs_str);
2935 refs_str = NULL;
2937 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2938 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2939 "........................................",
2940 s->in_repo_path, ncommits_str) == -1) {
2941 err = got_error_from_errno("asprintf");
2942 header = NULL;
2943 goto done;
2945 } else if (asprintf(&header, "commit %s%s",
2946 id_str ? id_str : "........................................",
2947 ncommits_str) == -1) {
2948 err = got_error_from_errno("asprintf");
2949 header = NULL;
2950 goto done;
2952 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2953 if (err)
2954 goto done;
2956 werase(view->window);
2958 if (view_needs_focus_indication(view))
2959 wstandout(view->window);
2960 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2961 if (tc)
2962 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2963 waddwstr(view->window, wline);
2964 while (width < view->ncols) {
2965 waddch(view->window, ' ');
2966 width++;
2968 if (tc)
2969 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2970 if (view_needs_focus_indication(view))
2971 wstandend(view->window);
2972 free(wline);
2973 if (limit <= 1)
2974 goto done;
2976 /* Grow author column size if necessary, and set view->maxx. */
2977 entry = s->first_displayed_entry;
2978 ncommits = 0;
2979 view->maxx = 0;
2980 while (entry) {
2981 struct got_commit_object *c = entry->commit;
2982 char *author, *eol, *msg, *msg0;
2983 wchar_t *wauthor, *wmsg;
2984 int width;
2985 if (ncommits >= limit - 1)
2986 break;
2987 if (s->use_committer)
2988 author = strdup(got_object_commit_get_committer(c));
2989 else
2990 author = strdup(got_object_commit_get_author(c));
2991 if (author == NULL) {
2992 err = got_error_from_errno("strdup");
2993 goto done;
2995 err = format_author(&wauthor, &width, author, COLS,
2996 date_display_cols);
2997 if (author_cols < width)
2998 author_cols = width;
2999 free(wauthor);
3000 free(author);
3001 if (err)
3002 goto done;
3003 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
3004 entry->id);
3005 err = build_refs_str(&refs_str, refs, entry->id, s->repo);
3006 if (err)
3007 goto done;
3008 if (refs_str) {
3009 wchar_t *ws;
3010 err = format_line(&ws, &width, NULL, refs_str,
3011 0, INT_MAX, date_display_cols + author_cols, 0);
3012 free(ws);
3013 free(refs_str);
3014 refs_str = NULL;
3015 if (err)
3016 goto done;
3017 refstr_cols = width + 3; /* account for [ ] + space */
3018 } else
3019 refstr_cols = 0;
3020 err = got_object_commit_get_logmsg(&msg0, c);
3021 if (err)
3022 goto done;
3023 msg = msg0;
3024 while (*msg == '\n')
3025 ++msg;
3026 if ((eol = strchr(msg, '\n')))
3027 *eol = '\0';
3028 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
3029 date_display_cols + author_cols + refstr_cols, 0);
3030 if (err)
3031 goto done;
3032 view->maxx = MAX(view->maxx, width + refstr_cols);
3033 free(msg0);
3034 free(wmsg);
3035 ncommits++;
3036 entry = TAILQ_NEXT(entry, entry);
3039 entry = s->first_displayed_entry;
3040 s->last_displayed_entry = s->first_displayed_entry;
3041 ncommits = 0;
3042 while (entry) {
3043 if (ncommits >= limit - 1)
3044 break;
3045 if (ncommits == s->selected)
3046 wstandout(view->window);
3047 err = draw_commit(view, entry, date_display_cols, author_cols);
3048 if (ncommits == s->selected)
3049 wstandend(view->window);
3050 if (err)
3051 goto done;
3052 ncommits++;
3053 s->last_displayed_entry = entry;
3054 entry = TAILQ_NEXT(entry, entry);
3057 view_border(view);
3058 done:
3059 free(id_str);
3060 free(refs_str);
3061 free(ncommits_str);
3062 free(header);
3063 return err;
3066 static void
3067 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
3069 struct commit_queue_entry *entry;
3070 int nscrolled = 0;
3072 entry = TAILQ_FIRST(&s->commits->head);
3073 if (s->first_displayed_entry == entry)
3074 return;
3076 entry = s->first_displayed_entry;
3077 while (entry && nscrolled < maxscroll) {
3078 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3079 if (entry) {
3080 s->first_displayed_entry = entry;
3081 nscrolled++;
3086 static const struct got_error *
3087 trigger_log_thread(struct tog_view *view, int wait)
3089 struct tog_log_thread_args *ta = &view->state.log.thread_args;
3090 int errcode;
3092 if (!using_mock_io)
3093 halfdelay(1); /* fast refresh while loading commits */
3095 while (!ta->log_complete && !tog_thread_error &&
3096 (ta->commits_needed > 0 || ta->load_all)) {
3097 /* Wake the log thread. */
3098 errcode = pthread_cond_signal(&ta->need_commits);
3099 if (errcode)
3100 return got_error_set_errno(errcode,
3101 "pthread_cond_signal");
3104 * The mutex will be released while the view loop waits
3105 * in wgetch(), at which time the log thread will run.
3107 if (!wait)
3108 break;
3110 /* Display progress update in log view. */
3111 show_log_view(view);
3112 update_panels();
3113 doupdate();
3115 /* Wait right here while next commit is being loaded. */
3116 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
3117 if (errcode)
3118 return got_error_set_errno(errcode,
3119 "pthread_cond_wait");
3121 /* Display progress update in log view. */
3122 show_log_view(view);
3123 update_panels();
3124 doupdate();
3127 return NULL;
3130 static const struct got_error *
3131 request_log_commits(struct tog_view *view)
3133 struct tog_log_view_state *state = &view->state.log;
3134 const struct got_error *err = NULL;
3136 if (state->thread_args.log_complete)
3137 return NULL;
3139 state->thread_args.commits_needed += view->nscrolled;
3140 err = trigger_log_thread(view, 1);
3141 view->nscrolled = 0;
3143 return err;
3146 static const struct got_error *
3147 log_scroll_down(struct tog_view *view, int maxscroll)
3149 struct tog_log_view_state *s = &view->state.log;
3150 const struct got_error *err = NULL;
3151 struct commit_queue_entry *pentry;
3152 int nscrolled = 0, ncommits_needed;
3154 if (s->last_displayed_entry == NULL)
3155 return NULL;
3157 ncommits_needed = s->last_displayed_entry->idx + 2 + maxscroll;
3158 if (s->commits->ncommits < ncommits_needed &&
3159 !s->thread_args.log_complete) {
3161 * Ask the log thread for required amount of commits.
3163 s->thread_args.commits_needed +=
3164 ncommits_needed - s->commits->ncommits;
3165 err = trigger_log_thread(view, 1);
3166 if (err)
3167 return err;
3170 do {
3171 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
3172 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
3173 break;
3175 s->last_displayed_entry = pentry ?
3176 pentry : s->last_displayed_entry;
3178 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3179 if (pentry == NULL)
3180 break;
3181 s->first_displayed_entry = pentry;
3182 } while (++nscrolled < maxscroll);
3184 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3185 view->nscrolled += nscrolled;
3186 else
3187 view->nscrolled = 0;
3189 return err;
3192 static const struct got_error *
3193 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3194 struct got_commit_object *commit, struct got_object_id *commit_id,
3195 struct tog_view *log_view, struct got_repository *repo)
3197 const struct got_error *err;
3198 struct got_object_qid *p;
3199 struct got_object_id *parent_id;
3200 struct tog_view *diff_view;
3201 struct tog_log_view_state *ls = NULL;
3203 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3204 if (diff_view == NULL)
3205 return got_error_from_errno("view_open");
3207 if (log_view != NULL)
3208 ls = &log_view->state.log;
3210 if (ls != NULL && ls->marked_entry != NULL &&
3211 ls->marked_entry != ls->selected_entry)
3212 parent_id = ls->marked_entry->id;
3213 else if ((p = STAILQ_FIRST(got_object_commit_get_parent_ids(commit))))
3214 parent_id = &p->id;
3215 else
3216 parent_id = NULL;
3218 err = open_diff_view(diff_view, parent_id, commit_id,
3219 NULL, NULL, 3, 0, 0, log_view, repo);
3220 if (err == NULL)
3221 *new_view = diff_view;
3222 return err;
3225 static const struct got_error *
3226 tree_view_visit_subtree(struct tog_tree_view_state *s,
3227 struct got_tree_object *subtree)
3229 struct tog_parent_tree *parent;
3231 parent = calloc(1, sizeof(*parent));
3232 if (parent == NULL)
3233 return got_error_from_errno("calloc");
3235 parent->tree = s->tree;
3236 parent->first_displayed_entry = s->first_displayed_entry;
3237 parent->selected_entry = s->selected_entry;
3238 parent->selected = s->selected;
3239 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3240 s->tree = subtree;
3241 s->selected = 0;
3242 s->first_displayed_entry = NULL;
3243 return NULL;
3246 static const struct got_error *
3247 tree_view_walk_path(struct tog_tree_view_state *s,
3248 struct got_commit_object *commit, const char *path)
3250 const struct got_error *err = NULL;
3251 struct got_tree_object *tree = NULL;
3252 const char *p;
3253 char *slash, *subpath = NULL;
3255 /* Walk the path and open corresponding tree objects. */
3256 p = path;
3257 while (*p) {
3258 struct got_tree_entry *te;
3259 struct got_object_id *tree_id;
3260 char *te_name;
3262 while (p[0] == '/')
3263 p++;
3265 /* Ensure the correct subtree entry is selected. */
3266 slash = strchr(p, '/');
3267 if (slash == NULL)
3268 te_name = strdup(p);
3269 else
3270 te_name = strndup(p, slash - p);
3271 if (te_name == NULL) {
3272 err = got_error_from_errno("strndup");
3273 break;
3275 te = got_object_tree_find_entry(s->tree, te_name);
3276 if (te == NULL) {
3277 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3278 free(te_name);
3279 break;
3281 free(te_name);
3282 s->first_displayed_entry = s->selected_entry = te;
3284 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3285 break; /* jump to this file's entry */
3287 slash = strchr(p, '/');
3288 if (slash)
3289 subpath = strndup(path, slash - path);
3290 else
3291 subpath = strdup(path);
3292 if (subpath == NULL) {
3293 err = got_error_from_errno("strdup");
3294 break;
3297 err = got_object_id_by_path(&tree_id, s->repo, commit,
3298 subpath);
3299 if (err)
3300 break;
3302 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3303 free(tree_id);
3304 if (err)
3305 break;
3307 err = tree_view_visit_subtree(s, tree);
3308 if (err) {
3309 got_object_tree_close(tree);
3310 break;
3312 if (slash == NULL)
3313 break;
3314 free(subpath);
3315 subpath = NULL;
3316 p = slash;
3319 free(subpath);
3320 return err;
3323 static const struct got_error *
3324 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3325 struct commit_queue_entry *entry, const char *path,
3326 const char *head_ref_name, struct got_repository *repo)
3328 const struct got_error *err = NULL;
3329 struct tog_tree_view_state *s;
3330 struct tog_view *tree_view;
3332 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3333 if (tree_view == NULL)
3334 return got_error_from_errno("view_open");
3336 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3337 if (err)
3338 return err;
3339 s = &tree_view->state.tree;
3341 *new_view = tree_view;
3343 if (got_path_is_root_dir(path))
3344 return NULL;
3346 return tree_view_walk_path(s, entry->commit, path);
3349 static const struct got_error *
3350 block_signals_used_by_main_thread(void)
3352 sigset_t sigset;
3353 int errcode;
3355 if (sigemptyset(&sigset) == -1)
3356 return got_error_from_errno("sigemptyset");
3358 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3359 if (sigaddset(&sigset, SIGWINCH) == -1)
3360 return got_error_from_errno("sigaddset");
3361 if (sigaddset(&sigset, SIGCONT) == -1)
3362 return got_error_from_errno("sigaddset");
3363 if (sigaddset(&sigset, SIGINT) == -1)
3364 return got_error_from_errno("sigaddset");
3365 if (sigaddset(&sigset, SIGTERM) == -1)
3366 return got_error_from_errno("sigaddset");
3368 /* ncurses handles SIGTSTP */
3369 if (sigaddset(&sigset, SIGTSTP) == -1)
3370 return got_error_from_errno("sigaddset");
3372 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3373 if (errcode)
3374 return got_error_set_errno(errcode, "pthread_sigmask");
3376 return NULL;
3379 static void *
3380 log_thread(void *arg)
3382 const struct got_error *err = NULL;
3383 int errcode = 0;
3384 struct tog_log_thread_args *a = arg;
3385 int done = 0;
3388 * Sync startup with main thread such that we begin our
3389 * work once view_input() has released the mutex.
3391 errcode = pthread_mutex_lock(&tog_mutex);
3392 if (errcode) {
3393 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3394 return (void *)err;
3397 err = block_signals_used_by_main_thread();
3398 if (err) {
3399 pthread_mutex_unlock(&tog_mutex);
3400 goto done;
3403 while (!done && !err && !tog_fatal_signal_received()) {
3404 errcode = pthread_mutex_unlock(&tog_mutex);
3405 if (errcode) {
3406 err = got_error_set_errno(errcode,
3407 "pthread_mutex_unlock");
3408 goto done;
3410 err = queue_commits(a);
3411 if (err) {
3412 if (err->code != GOT_ERR_ITER_COMPLETED)
3413 goto done;
3414 err = NULL;
3415 done = 1;
3416 a->commits_needed = 0;
3417 } else if (a->commits_needed > 0 && !a->load_all) {
3418 if (*a->limiting) {
3419 if (a->limit_match)
3420 a->commits_needed--;
3421 } else
3422 a->commits_needed--;
3425 errcode = pthread_mutex_lock(&tog_mutex);
3426 if (errcode) {
3427 err = got_error_set_errno(errcode,
3428 "pthread_mutex_lock");
3429 goto done;
3430 } else if (*a->quit)
3431 done = 1;
3432 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3433 *a->first_displayed_entry =
3434 TAILQ_FIRST(&a->limit_commits->head);
3435 *a->selected_entry = *a->first_displayed_entry;
3436 } else if (*a->first_displayed_entry == NULL) {
3437 *a->first_displayed_entry =
3438 TAILQ_FIRST(&a->real_commits->head);
3439 *a->selected_entry = *a->first_displayed_entry;
3442 errcode = pthread_cond_signal(&a->commit_loaded);
3443 if (errcode) {
3444 err = got_error_set_errno(errcode,
3445 "pthread_cond_signal");
3446 pthread_mutex_unlock(&tog_mutex);
3447 goto done;
3450 if (a->commits_needed == 0 &&
3451 a->need_commit_marker && a->worktree) {
3452 errcode = pthread_mutex_unlock(&tog_mutex);
3453 if (errcode) {
3454 err = got_error_set_errno(errcode,
3455 "pthread_mutex_unlock");
3456 goto done;
3458 err = got_worktree_get_state(&tog_base_commit.marker,
3459 a->repo, a->worktree, NULL, NULL);
3460 if (err)
3461 goto done;
3462 errcode = pthread_mutex_lock(&tog_mutex);
3463 if (errcode) {
3464 err = got_error_set_errno(errcode,
3465 "pthread_mutex_lock");
3466 goto done;
3468 a->need_commit_marker = 0;
3470 * The main thread did not close this
3471 * work tree yet. Close it now.
3473 got_worktree_close(a->worktree);
3474 a->worktree = NULL;
3476 if (*a->quit)
3477 done = 1;
3480 if (done)
3481 a->commits_needed = 0;
3482 else {
3483 if (a->commits_needed == 0 && !a->load_all) {
3484 if (tog_io.wait_for_ui) {
3485 errcode = pthread_cond_signal(
3486 &a->log_loaded);
3487 if (errcode && err == NULL)
3488 err = got_error_set_errno(
3489 errcode,
3490 "pthread_cond_signal");
3493 errcode = pthread_cond_wait(&a->need_commits,
3494 &tog_mutex);
3495 if (errcode) {
3496 err = got_error_set_errno(errcode,
3497 "pthread_cond_wait");
3498 pthread_mutex_unlock(&tog_mutex);
3499 goto done;
3501 if (*a->quit)
3502 done = 1;
3506 a->log_complete = 1;
3507 if (tog_io.wait_for_ui) {
3508 errcode = pthread_cond_signal(&a->log_loaded);
3509 if (errcode && err == NULL)
3510 err = got_error_set_errno(errcode,
3511 "pthread_cond_signal");
3514 errcode = pthread_mutex_unlock(&tog_mutex);
3515 if (errcode)
3516 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3517 done:
3518 if (err) {
3519 tog_thread_error = 1;
3520 pthread_cond_signal(&a->commit_loaded);
3521 if (a->worktree) {
3522 got_worktree_close(a->worktree);
3523 a->worktree = NULL;
3526 return (void *)err;
3529 static const struct got_error *
3530 stop_log_thread(struct tog_log_view_state *s)
3532 const struct got_error *err = NULL, *thread_err = NULL;
3533 int errcode;
3535 if (s->thread) {
3536 s->quit = 1;
3537 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3538 if (errcode)
3539 return got_error_set_errno(errcode,
3540 "pthread_cond_signal");
3541 errcode = pthread_mutex_unlock(&tog_mutex);
3542 if (errcode)
3543 return got_error_set_errno(errcode,
3544 "pthread_mutex_unlock");
3545 errcode = pthread_join(s->thread, (void **)&thread_err);
3546 if (errcode)
3547 return got_error_set_errno(errcode, "pthread_join");
3548 errcode = pthread_mutex_lock(&tog_mutex);
3549 if (errcode)
3550 return got_error_set_errno(errcode,
3551 "pthread_mutex_lock");
3552 s->thread = NULL;
3555 if (s->thread_args.repo) {
3556 err = got_repo_close(s->thread_args.repo);
3557 s->thread_args.repo = NULL;
3560 if (s->thread_args.pack_fds) {
3561 const struct got_error *pack_err =
3562 got_repo_pack_fds_close(s->thread_args.pack_fds);
3563 if (err == NULL)
3564 err = pack_err;
3565 s->thread_args.pack_fds = NULL;
3568 if (s->thread_args.graph) {
3569 got_commit_graph_close(s->thread_args.graph);
3570 s->thread_args.graph = NULL;
3573 return err ? err : thread_err;
3576 static const struct got_error *
3577 close_log_view(struct tog_view *view)
3579 const struct got_error *err = NULL;
3580 struct tog_log_view_state *s = &view->state.log;
3581 int errcode;
3583 log_mark_clear(s);
3585 err = stop_log_thread(s);
3587 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3588 if (errcode && err == NULL)
3589 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3591 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3592 if (errcode && err == NULL)
3593 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3595 free_commits(&s->limit_commits);
3596 free_commits(&s->real_commits);
3597 free_colors(&s->colors);
3598 free(s->in_repo_path);
3599 s->in_repo_path = NULL;
3600 free(s->start_id);
3601 s->start_id = NULL;
3602 free(s->head_ref_name);
3603 s->head_ref_name = NULL;
3604 return err;
3608 * We use two queues to implement the limit feature: first consists of
3609 * commits matching the current limit_regex; second is the real queue
3610 * of all known commits (real_commits). When the user starts limiting,
3611 * we swap queues such that all movement and displaying functionality
3612 * works with very slight change.
3614 static const struct got_error *
3615 limit_log_view(struct tog_view *view)
3617 struct tog_log_view_state *s = &view->state.log;
3618 struct commit_queue_entry *entry;
3619 struct tog_view *v = view;
3620 const struct got_error *err = NULL;
3621 char pattern[1024];
3622 int ret;
3624 if (view_is_hsplit_top(view))
3625 v = view->child;
3626 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3627 v = view->parent;
3629 if (tog_io.input_str != NULL) {
3630 if (strlcpy(pattern, tog_io.input_str, sizeof(pattern)) >=
3631 sizeof(pattern))
3632 return got_error(GOT_ERR_NO_SPACE);
3633 } else {
3634 wmove(v->window, v->nlines - 1, 0);
3635 wclrtoeol(v->window);
3636 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3637 nodelay(v->window, FALSE);
3638 nocbreak();
3639 echo();
3640 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3641 cbreak();
3642 noecho();
3643 nodelay(v->window, TRUE);
3644 if (ret == ERR)
3645 return NULL;
3648 if (*pattern == '\0') {
3650 * Safety measure for the situation where the user
3651 * resets limit without previously limiting anything.
3653 if (!s->limit_view)
3654 return NULL;
3657 * User could have pressed Ctrl+L, which refreshed the
3658 * commit queues, it means we can't save previously
3659 * (before limit took place) displayed entries,
3660 * because they would point to already free'ed memory,
3661 * so we are forced to always select first entry of
3662 * the queue.
3664 s->commits = &s->real_commits;
3665 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3666 s->selected_entry = s->first_displayed_entry;
3667 s->selected = 0;
3668 s->limit_view = 0;
3670 return NULL;
3673 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3674 return NULL;
3676 s->limit_view = 1;
3678 /* Clear the screen while loading limit view */
3679 s->first_displayed_entry = NULL;
3680 s->last_displayed_entry = NULL;
3681 s->selected_entry = NULL;
3682 s->commits = &s->limit_commits;
3684 /* Prepare limit queue for new search */
3685 free_commits(&s->limit_commits);
3686 s->limit_commits.ncommits = 0;
3688 /* First process commits, which are in queue already */
3689 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3690 int have_match = 0;
3692 err = match_commit(&have_match, entry->id,
3693 entry->commit, &s->limit_regex);
3694 if (err)
3695 return err;
3697 if (have_match) {
3698 struct commit_queue_entry *matched;
3700 matched = alloc_commit_queue_entry(entry->commit,
3701 entry->id);
3702 if (matched == NULL) {
3703 err = got_error_from_errno(
3704 "alloc_commit_queue_entry");
3705 break;
3707 matched->commit = entry->commit;
3708 got_object_commit_retain(entry->commit);
3710 matched->idx = s->limit_commits.ncommits;
3711 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3712 matched, entry);
3713 s->limit_commits.ncommits++;
3717 /* Second process all the commits, until we fill the screen */
3718 if (s->limit_commits.ncommits < view->nlines - 1 &&
3719 !s->thread_args.log_complete) {
3720 s->thread_args.commits_needed +=
3721 view->nlines - s->limit_commits.ncommits - 1;
3722 err = trigger_log_thread(view, 1);
3723 if (err)
3724 return err;
3727 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3728 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3729 s->selected = 0;
3731 return NULL;
3734 static const struct got_error *
3735 search_start_log_view(struct tog_view *view)
3737 struct tog_log_view_state *s = &view->state.log;
3739 s->matched_entry = NULL;
3740 s->search_entry = NULL;
3741 return NULL;
3744 static const struct got_error *
3745 search_next_log_view(struct tog_view *view)
3747 const struct got_error *err = NULL;
3748 struct tog_log_view_state *s = &view->state.log;
3749 struct commit_queue_entry *entry;
3751 /* Display progress update in log view. */
3752 show_log_view(view);
3753 update_panels();
3754 doupdate();
3756 if (s->search_entry) {
3757 if (!using_mock_io) {
3758 int errcode, ch;
3760 errcode = pthread_mutex_unlock(&tog_mutex);
3761 if (errcode)
3762 return got_error_set_errno(errcode,
3763 "pthread_mutex_unlock");
3764 ch = wgetch(view->window);
3765 errcode = pthread_mutex_lock(&tog_mutex);
3766 if (errcode)
3767 return got_error_set_errno(errcode,
3768 "pthread_mutex_lock");
3769 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3770 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3771 return NULL;
3774 if (view->searching == TOG_SEARCH_FORWARD)
3775 entry = TAILQ_NEXT(s->search_entry, entry);
3776 else
3777 entry = TAILQ_PREV(s->search_entry,
3778 commit_queue_head, entry);
3779 } else if (s->matched_entry) {
3781 * If the user has moved the cursor after we hit a match,
3782 * the position from where we should continue searching
3783 * might have changed.
3785 if (view->searching == TOG_SEARCH_FORWARD)
3786 entry = TAILQ_NEXT(s->selected_entry, entry);
3787 else
3788 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3789 entry);
3790 } else {
3791 entry = s->selected_entry;
3794 while (1) {
3795 int have_match = 0;
3797 if (entry == NULL) {
3798 if (s->thread_args.log_complete ||
3799 view->searching == TOG_SEARCH_BACKWARD) {
3800 view->search_next_done =
3801 (s->matched_entry == NULL ?
3802 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3803 s->search_entry = NULL;
3804 return NULL;
3807 * Poke the log thread for more commits and return,
3808 * allowing the main loop to make progress. Search
3809 * will resume at s->search_entry once we come back.
3811 s->search_entry = s->selected_entry;
3812 s->thread_args.commits_needed++;
3813 return trigger_log_thread(view, 0);
3816 err = match_commit(&have_match, entry->id, entry->commit,
3817 &view->regex);
3818 if (err)
3819 break;
3820 if (have_match) {
3821 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3822 s->matched_entry = entry;
3823 break;
3826 s->search_entry = entry;
3827 if (view->searching == TOG_SEARCH_FORWARD)
3828 entry = TAILQ_NEXT(entry, entry);
3829 else
3830 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3833 if (s->matched_entry) {
3834 int cur = s->selected_entry->idx;
3835 while (cur < s->matched_entry->idx) {
3836 err = input_log_view(NULL, view, KEY_DOWN);
3837 if (err)
3838 return err;
3839 cur++;
3841 while (cur > s->matched_entry->idx) {
3842 err = input_log_view(NULL, view, KEY_UP);
3843 if (err)
3844 return err;
3845 cur--;
3849 s->search_entry = NULL;
3851 return NULL;
3854 static const struct got_error *
3855 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3856 struct got_repository *repo, const char *head_ref_name,
3857 const char *in_repo_path, int log_branches,
3858 struct got_worktree *worktree)
3860 const struct got_error *err = NULL;
3861 struct tog_log_view_state *s = &view->state.log;
3862 struct got_repository *thread_repo = NULL;
3863 struct got_commit_graph *thread_graph = NULL;
3864 int errcode;
3866 if (in_repo_path != s->in_repo_path) {
3867 free(s->in_repo_path);
3868 s->in_repo_path = strdup(in_repo_path);
3869 if (s->in_repo_path == NULL) {
3870 err = got_error_from_errno("strdup");
3871 goto done;
3875 /* The commit queue only contains commits being displayed. */
3876 TAILQ_INIT(&s->real_commits.head);
3877 s->real_commits.ncommits = 0;
3878 s->commits = &s->real_commits;
3880 TAILQ_INIT(&s->limit_commits.head);
3881 s->limit_view = 0;
3882 s->limit_commits.ncommits = 0;
3884 s->repo = repo;
3885 if (head_ref_name) {
3886 s->head_ref_name = strdup(head_ref_name);
3887 if (s->head_ref_name == NULL) {
3888 err = got_error_from_errno("strdup");
3889 goto done;
3892 s->start_id = got_object_id_dup(start_id);
3893 if (s->start_id == NULL) {
3894 err = got_error_from_errno("got_object_id_dup");
3895 goto done;
3897 s->log_branches = log_branches;
3898 s->use_committer = 1;
3900 STAILQ_INIT(&s->colors);
3901 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3902 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3903 get_color_value("TOG_COLOR_COMMIT"));
3904 if (err)
3905 goto done;
3906 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3907 get_color_value("TOG_COLOR_AUTHOR"));
3908 if (err)
3909 goto done;
3910 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3911 get_color_value("TOG_COLOR_DATE"));
3912 if (err)
3913 goto done;
3916 view->show = show_log_view;
3917 view->input = input_log_view;
3918 view->resize = resize_log_view;
3919 view->close = close_log_view;
3920 view->search_start = search_start_log_view;
3921 view->search_next = search_next_log_view;
3923 if (s->thread_args.pack_fds == NULL) {
3924 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3925 if (err)
3926 goto done;
3928 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3929 s->thread_args.pack_fds);
3930 if (err)
3931 goto done;
3932 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3933 !s->log_branches);
3934 if (err)
3935 goto done;
3936 err = got_commit_graph_bfsort(thread_graph, s->start_id,
3937 s->repo, NULL, NULL);
3938 if (err)
3939 goto done;
3941 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3942 if (errcode) {
3943 err = got_error_set_errno(errcode, "pthread_cond_init");
3944 goto done;
3946 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3947 if (errcode) {
3948 err = got_error_set_errno(errcode, "pthread_cond_init");
3949 goto done;
3952 if (using_mock_io) {
3953 int rc;
3955 rc = pthread_cond_init(&s->thread_args.log_loaded, NULL);
3956 if (rc)
3957 return got_error_set_errno(rc, "pthread_cond_init");
3960 s->thread_args.commits_needed = view->nlines;
3961 s->thread_args.graph = thread_graph;
3962 s->thread_args.real_commits = &s->real_commits;
3963 s->thread_args.limit_commits = &s->limit_commits;
3964 s->thread_args.in_repo_path = s->in_repo_path;
3965 s->thread_args.start_id = s->start_id;
3966 s->thread_args.repo = thread_repo;
3967 s->thread_args.log_complete = 0;
3968 s->thread_args.quit = &s->quit;
3969 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3970 s->thread_args.selected_entry = &s->selected_entry;
3971 s->thread_args.searching = &view->searching;
3972 s->thread_args.search_next_done = &view->search_next_done;
3973 s->thread_args.regex = &view->regex;
3974 s->thread_args.limiting = &s->limit_view;
3975 s->thread_args.limit_regex = &s->limit_regex;
3976 s->thread_args.limit_commits = &s->limit_commits;
3977 s->thread_args.worktree = worktree;
3978 if (worktree)
3979 s->thread_args.need_commit_marker = 1;
3980 done:
3981 if (err) {
3982 if (view->close == NULL)
3983 close_log_view(view);
3984 view_close(view);
3986 return err;
3989 static const struct got_error *
3990 show_log_view(struct tog_view *view)
3992 const struct got_error *err;
3993 struct tog_log_view_state *s = &view->state.log;
3995 if (s->thread == NULL) {
3996 int errcode = pthread_create(&s->thread, NULL, log_thread,
3997 &s->thread_args);
3998 if (errcode)
3999 return got_error_set_errno(errcode, "pthread_create");
4000 if (s->thread_args.commits_needed > 0) {
4001 err = trigger_log_thread(view, 1);
4002 if (err)
4003 return err;
4007 return draw_commits(view);
4010 static void
4011 log_move_cursor_up(struct tog_view *view, int page, int home)
4013 struct tog_log_view_state *s = &view->state.log;
4015 if (s->first_displayed_entry == NULL)
4016 return;
4017 if (s->selected_entry->idx == 0)
4018 view->count = 0;
4020 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
4021 || home)
4022 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
4024 if (!page && !home && s->selected > 0)
4025 --s->selected;
4026 else
4027 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
4029 select_commit(s);
4030 return;
4033 static const struct got_error *
4034 log_move_cursor_down(struct tog_view *view, int page)
4036 struct tog_log_view_state *s = &view->state.log;
4037 const struct got_error *err = NULL;
4038 int eos = view->nlines - 2;
4040 if (s->first_displayed_entry == NULL)
4041 return NULL;
4043 if (s->thread_args.log_complete &&
4044 s->selected_entry->idx >= s->commits->ncommits - 1)
4045 return NULL;
4047 if (view_is_hsplit_top(view))
4048 --eos; /* border consumes the last line */
4050 if (!page) {
4051 if (s->selected < MIN(eos, s->commits->ncommits - 1))
4052 ++s->selected;
4053 else
4054 err = log_scroll_down(view, 1);
4055 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
4056 struct commit_queue_entry *entry;
4057 int n;
4059 s->selected = 0;
4060 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
4061 s->last_displayed_entry = entry;
4062 for (n = 0; n <= eos; n++) {
4063 if (entry == NULL)
4064 break;
4065 s->first_displayed_entry = entry;
4066 entry = TAILQ_PREV(entry, commit_queue_head, entry);
4068 if (n > 0)
4069 s->selected = n - 1;
4070 } else {
4071 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
4072 s->thread_args.log_complete)
4073 s->selected += MIN(page,
4074 s->commits->ncommits - s->selected_entry->idx - 1);
4075 else
4076 err = log_scroll_down(view, page);
4078 if (err)
4079 return err;
4082 * We might necessarily overshoot in horizontal
4083 * splits; if so, select the last displayed commit.
4085 if (view_is_hsplit_top(view) && s->first_displayed_entry &&
4086 s->last_displayed_entry) {
4087 s->selected = MIN(s->selected,
4088 s->last_displayed_entry->idx -
4089 s->first_displayed_entry->idx);
4092 select_commit(s);
4094 if (s->thread_args.log_complete &&
4095 s->selected_entry->idx == s->commits->ncommits - 1)
4096 view->count = 0;
4098 return NULL;
4101 static void
4102 view_get_split(struct tog_view *view, int *y, int *x)
4104 *x = 0;
4105 *y = 0;
4107 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
4108 if (view->child && view->child->resized_y)
4109 *y = view->child->resized_y;
4110 else if (view->resized_y)
4111 *y = view->resized_y;
4112 else
4113 *y = view_split_begin_y(view->lines);
4114 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
4115 if (view->child && view->child->resized_x)
4116 *x = view->child->resized_x;
4117 else if (view->resized_x)
4118 *x = view->resized_x;
4119 else
4120 *x = view_split_begin_x(view->begin_x);
4124 /* Split view horizontally at y and offset view->state->selected line. */
4125 static const struct got_error *
4126 view_init_hsplit(struct tog_view *view, int y)
4128 const struct got_error *err = NULL;
4130 view->nlines = y;
4131 view->ncols = COLS;
4132 err = view_resize(view);
4133 if (err)
4134 return err;
4136 err = offset_selection_down(view);
4138 return err;
4141 static const struct got_error *
4142 log_goto_line(struct tog_view *view, int nlines)
4144 const struct got_error *err = NULL;
4145 struct tog_log_view_state *s = &view->state.log;
4146 int g, idx = s->selected_entry->idx;
4148 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
4149 return NULL;
4151 g = view->gline;
4152 view->gline = 0;
4154 if (g >= s->first_displayed_entry->idx + 1 &&
4155 g <= s->last_displayed_entry->idx + 1 &&
4156 g - s->first_displayed_entry->idx - 1 < nlines) {
4157 s->selected = g - s->first_displayed_entry->idx - 1;
4158 select_commit(s);
4159 return NULL;
4162 if (idx + 1 < g) {
4163 err = log_move_cursor_down(view, g - idx - 1);
4164 if (!err && g > s->selected_entry->idx + 1)
4165 err = log_move_cursor_down(view,
4166 g - s->first_displayed_entry->idx - 1);
4167 if (err)
4168 return err;
4169 } else if (idx + 1 > g)
4170 log_move_cursor_up(view, idx - g + 1, 0);
4172 if (g < nlines && s->first_displayed_entry->idx == 0)
4173 s->selected = g - 1;
4175 select_commit(s);
4176 return NULL;
4180 static void
4181 horizontal_scroll_input(struct tog_view *view, int ch)
4184 switch (ch) {
4185 case KEY_LEFT:
4186 case 'h':
4187 view->x -= MIN(view->x, 2);
4188 if (view->x <= 0)
4189 view->count = 0;
4190 break;
4191 case KEY_RIGHT:
4192 case 'l':
4193 if (view->x + view->ncols / 2 < view->maxx)
4194 view->x += 2;
4195 else
4196 view->count = 0;
4197 break;
4198 case '0':
4199 view->x = 0;
4200 break;
4201 case '$':
4202 view->x = MAX(view->maxx - view->ncols / 2, 0);
4203 view->count = 0;
4204 break;
4205 default:
4206 break;
4210 static void
4211 log_mark_commit(struct tog_log_view_state *s)
4213 if (s->selected_entry == s->marked_entry)
4214 s->marked_entry = NULL;
4215 else
4216 s->marked_entry = s->selected_entry;
4219 static const struct got_error *
4220 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
4222 const struct got_error *err = NULL;
4223 struct tog_log_view_state *s = &view->state.log;
4224 int eos, nscroll;
4226 if (s->thread_args.load_all) {
4227 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
4228 s->thread_args.load_all = 0;
4229 else if (s->thread_args.log_complete) {
4230 err = log_move_cursor_down(view, s->commits->ncommits);
4231 s->thread_args.load_all = 0;
4233 if (err)
4234 return err;
4237 eos = nscroll = view->nlines - 1;
4238 if (view_is_hsplit_top(view))
4239 --eos; /* border */
4241 if (view->gline)
4242 return log_goto_line(view, eos);
4244 switch (ch) {
4245 case '&':
4246 err = limit_log_view(view);
4247 break;
4248 case 'q':
4249 s->quit = 1;
4250 break;
4251 case '0':
4252 case '$':
4253 case KEY_RIGHT:
4254 case 'l':
4255 case KEY_LEFT:
4256 case 'h':
4257 horizontal_scroll_input(view, ch);
4258 break;
4259 case 'k':
4260 case KEY_UP:
4261 case '<':
4262 case ',':
4263 case CTRL('p'):
4264 log_move_cursor_up(view, 0, 0);
4265 break;
4266 case 'g':
4267 case '=':
4268 case KEY_HOME:
4269 log_move_cursor_up(view, 0, 1);
4270 view->count = 0;
4271 break;
4272 case CTRL('u'):
4273 case 'u':
4274 nscroll /= 2;
4275 /* FALL THROUGH */
4276 case KEY_PPAGE:
4277 case CTRL('b'):
4278 case 'b':
4279 log_move_cursor_up(view, nscroll, 0);
4280 break;
4281 case 'j':
4282 case KEY_DOWN:
4283 case '>':
4284 case '.':
4285 case CTRL('n'):
4286 err = log_move_cursor_down(view, 0);
4287 break;
4288 case '@':
4289 s->use_committer = !s->use_committer;
4290 view->action = s->use_committer ?
4291 "show committer" : "show commit author";
4292 break;
4293 case 'G':
4294 case '*':
4295 case KEY_END: {
4296 /* We don't know yet how many commits, so we're forced to
4297 * traverse them all. */
4298 view->count = 0;
4299 s->thread_args.load_all = 1;
4300 if (!s->thread_args.log_complete)
4301 return trigger_log_thread(view, 0);
4302 err = log_move_cursor_down(view, s->commits->ncommits);
4303 s->thread_args.load_all = 0;
4304 break;
4306 case CTRL('d'):
4307 case 'd':
4308 nscroll /= 2;
4309 /* FALL THROUGH */
4310 case KEY_NPAGE:
4311 case CTRL('f'):
4312 case 'f':
4313 case ' ':
4314 err = log_move_cursor_down(view, nscroll);
4315 break;
4316 case KEY_RESIZE:
4317 if (s->selected > view->nlines - 2)
4318 s->selected = view->nlines - 2;
4319 if (s->selected > s->commits->ncommits - 1)
4320 s->selected = s->commits->ncommits - 1;
4321 select_commit(s);
4322 if (s->commits->ncommits < view->nlines - 1 &&
4323 !s->thread_args.log_complete) {
4324 s->thread_args.commits_needed += (view->nlines - 1) -
4325 s->commits->ncommits;
4326 err = trigger_log_thread(view, 1);
4328 break;
4329 case KEY_ENTER:
4330 case '\r':
4331 view->count = 0;
4332 if (s->selected_entry == NULL)
4333 break;
4334 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4335 break;
4336 case 'T':
4337 view->count = 0;
4338 if (s->selected_entry == NULL)
4339 break;
4340 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4341 break;
4342 case KEY_BACKSPACE:
4343 case CTRL('l'):
4344 case 'B':
4345 view->count = 0;
4346 if (ch == KEY_BACKSPACE &&
4347 got_path_is_root_dir(s->in_repo_path))
4348 break;
4349 err = stop_log_thread(s);
4350 if (err)
4351 return err;
4352 if (ch == KEY_BACKSPACE) {
4353 char *parent_path;
4354 err = got_path_dirname(&parent_path, s->in_repo_path);
4355 if (err)
4356 return err;
4357 free(s->in_repo_path);
4358 s->in_repo_path = parent_path;
4359 s->thread_args.in_repo_path = s->in_repo_path;
4360 } else if (ch == CTRL('l')) {
4361 struct got_object_id *start_id;
4362 err = got_repo_match_object_id(&start_id, NULL,
4363 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4364 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4365 if (err) {
4366 if (s->head_ref_name == NULL ||
4367 err->code != GOT_ERR_NOT_REF)
4368 return err;
4369 /* Try to cope with deleted references. */
4370 free(s->head_ref_name);
4371 s->head_ref_name = NULL;
4372 err = got_repo_match_object_id(&start_id,
4373 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4374 &tog_refs, s->repo);
4375 if (err)
4376 return err;
4378 free(s->start_id);
4379 s->start_id = start_id;
4380 s->thread_args.start_id = s->start_id;
4381 } else /* 'B' */
4382 s->log_branches = !s->log_branches;
4384 if (s->thread_args.pack_fds == NULL) {
4385 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4386 if (err)
4387 return err;
4389 err = got_repo_open(&s->thread_args.repo,
4390 got_repo_get_path(s->repo), NULL,
4391 s->thread_args.pack_fds);
4392 if (err)
4393 return err;
4394 tog_free_refs();
4395 err = tog_load_refs(s->repo, 0);
4396 if (err)
4397 return err;
4398 err = got_commit_graph_open(&s->thread_args.graph,
4399 s->in_repo_path, !s->log_branches);
4400 if (err)
4401 return err;
4402 err = got_commit_graph_bfsort(s->thread_args.graph,
4403 s->start_id, s->repo, NULL, NULL);
4404 if (err)
4405 return err;
4406 free_commits(&s->real_commits);
4407 free_commits(&s->limit_commits);
4408 s->first_displayed_entry = NULL;
4409 s->last_displayed_entry = NULL;
4410 s->selected_entry = NULL;
4411 s->selected = 0;
4412 s->thread_args.log_complete = 0;
4413 s->quit = 0;
4414 s->thread_args.commits_needed = view->lines;
4415 s->matched_entry = NULL;
4416 s->search_entry = NULL;
4417 view->offset = 0;
4418 break;
4419 case 'm':
4420 log_mark_commit(s);
4421 break;
4422 case 'R':
4423 view->count = 0;
4424 err = view_request_new(new_view, view, TOG_VIEW_REF);
4425 break;
4426 default:
4427 view->count = 0;
4428 break;
4431 return err;
4434 static const struct got_error *
4435 apply_unveil(const char *repo_path, const char *worktree_path)
4437 const struct got_error *error;
4439 #ifdef PROFILE
4440 if (unveil("gmon.out", "rwc") != 0)
4441 return got_error_from_errno2("unveil", "gmon.out");
4442 #endif
4443 if (repo_path && unveil(repo_path, "r") != 0)
4444 return got_error_from_errno2("unveil", repo_path);
4446 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4447 return got_error_from_errno2("unveil", worktree_path);
4449 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4450 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4452 error = got_privsep_unveil_exec_helpers();
4453 if (error != NULL)
4454 return error;
4456 if (unveil(NULL, NULL) != 0)
4457 return got_error_from_errno("unveil");
4459 return NULL;
4462 static const struct got_error *
4463 init_mock_term(const char *test_script_path)
4465 const struct got_error *err = NULL;
4466 const char *screen_dump_path;
4467 int in;
4469 if (test_script_path == NULL || *test_script_path == '\0')
4470 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4472 tog_io.f = fopen(test_script_path, "re");
4473 if (tog_io.f == NULL) {
4474 err = got_error_from_errno_fmt("fopen: %s",
4475 test_script_path);
4476 goto done;
4479 /* test mode, we don't want any output */
4480 tog_io.cout = fopen("/dev/null", "w+");
4481 if (tog_io.cout == NULL) {
4482 err = got_error_from_errno2("fopen", "/dev/null");
4483 goto done;
4486 in = dup(fileno(tog_io.cout));
4487 if (in == -1) {
4488 err = got_error_from_errno("dup");
4489 goto done;
4491 tog_io.cin = fdopen(in, "r");
4492 if (tog_io.cin == NULL) {
4493 err = got_error_from_errno("fdopen");
4494 close(in);
4495 goto done;
4498 screen_dump_path = getenv("TOG_SCR_DUMP");
4499 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4500 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4501 tog_io.sdump = fopen(screen_dump_path, "we");
4502 if (tog_io.sdump == NULL) {
4503 err = got_error_from_errno2("fopen", screen_dump_path);
4504 goto done;
4507 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4508 err = got_error_from_errno("fseeko");
4509 goto done;
4512 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4513 err = got_error_msg(GOT_ERR_IO,
4514 "newterm: failed to initialise curses");
4516 using_mock_io = 1;
4518 done:
4519 if (err)
4520 tog_io_close();
4521 return err;
4524 static void
4525 init_curses(void)
4527 if (using_mock_io) /* In test mode we use a fake terminal */
4528 return;
4530 initscr();
4532 cbreak();
4533 halfdelay(1); /* Fast refresh while initial view is loading. */
4534 noecho();
4535 nonl();
4536 intrflush(stdscr, FALSE);
4537 keypad(stdscr, TRUE);
4538 curs_set(0);
4539 if (getenv("TOG_COLORS") != NULL) {
4540 start_color();
4541 use_default_colors();
4544 return;
4547 static const struct got_error *
4548 set_tog_base_commit(struct got_repository *repo, struct got_worktree *worktree)
4550 tog_base_commit.id = got_object_id_dup(
4551 got_worktree_get_base_commit_id(worktree));
4552 if (tog_base_commit.id == NULL)
4553 return got_error_from_errno( "got_object_id_dup");
4555 return NULL;
4558 static const struct got_error *
4559 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4560 struct got_repository *repo, struct got_worktree *worktree)
4562 const struct got_error *err = NULL;
4564 if (argc == 0) {
4565 *in_repo_path = strdup("/");
4566 if (*in_repo_path == NULL)
4567 return got_error_from_errno("strdup");
4568 return NULL;
4571 if (worktree) {
4572 const char *prefix = got_worktree_get_path_prefix(worktree);
4573 char *p;
4575 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4576 if (err)
4577 return err;
4578 if (asprintf(in_repo_path, "%s%s%s", prefix,
4579 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4580 p) == -1) {
4581 err = got_error_from_errno("asprintf");
4582 *in_repo_path = NULL;
4584 free(p);
4585 } else
4586 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4588 return err;
4591 static const struct got_error *
4592 cmd_log(int argc, char *argv[])
4594 const struct got_error *error;
4595 struct got_repository *repo = NULL;
4596 struct got_worktree *worktree = NULL;
4597 struct got_object_id *start_id = NULL;
4598 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4599 char *keyword_idstr = NULL, *start_commit = NULL, *label = NULL;
4600 struct got_reference *ref = NULL;
4601 const char *head_ref_name = NULL;
4602 int ch, log_branches = 0;
4603 struct tog_view *view;
4604 int *pack_fds = NULL;
4606 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4607 switch (ch) {
4608 case 'b':
4609 log_branches = 1;
4610 break;
4611 case 'c':
4612 start_commit = optarg;
4613 break;
4614 case 'r':
4615 repo_path = realpath(optarg, NULL);
4616 if (repo_path == NULL)
4617 return got_error_from_errno2("realpath",
4618 optarg);
4619 break;
4620 default:
4621 usage_log();
4622 /* NOTREACHED */
4626 argc -= optind;
4627 argv += optind;
4629 if (argc > 1)
4630 usage_log();
4632 error = got_repo_pack_fds_open(&pack_fds);
4633 if (error != NULL)
4634 goto done;
4636 if (repo_path == NULL) {
4637 cwd = getcwd(NULL, 0);
4638 if (cwd == NULL) {
4639 error = got_error_from_errno("getcwd");
4640 goto done;
4642 error = got_worktree_open(&worktree, cwd, NULL);
4643 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4644 goto done;
4645 if (worktree)
4646 repo_path =
4647 strdup(got_worktree_get_repo_path(worktree));
4648 else
4649 repo_path = strdup(cwd);
4650 if (repo_path == NULL) {
4651 error = got_error_from_errno("strdup");
4652 goto done;
4656 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4657 if (error != NULL)
4658 goto done;
4660 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4661 repo, worktree);
4662 if (error)
4663 goto done;
4665 init_curses();
4667 error = apply_unveil(got_repo_get_path(repo),
4668 worktree ? got_worktree_get_root_path(worktree) : NULL);
4669 if (error)
4670 goto done;
4672 /* already loaded by tog_log_with_path()? */
4673 if (TAILQ_EMPTY(&tog_refs)) {
4674 error = tog_load_refs(repo, 0);
4675 if (error)
4676 goto done;
4679 if (start_commit == NULL) {
4680 error = got_repo_match_object_id(&start_id, &label,
4681 worktree ? got_worktree_get_head_ref_name(worktree) :
4682 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4683 if (error)
4684 goto done;
4685 head_ref_name = label;
4686 } else {
4687 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4688 repo, worktree);
4689 if (error != NULL)
4690 goto done;
4691 if (keyword_idstr != NULL)
4692 start_commit = keyword_idstr;
4694 error = got_ref_open(&ref, repo, start_commit, 0);
4695 if (error == NULL)
4696 head_ref_name = got_ref_get_name(ref);
4697 else if (error->code != GOT_ERR_NOT_REF)
4698 goto done;
4699 error = got_repo_match_object_id(&start_id, NULL,
4700 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4701 if (error)
4702 goto done;
4705 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4706 if (view == NULL) {
4707 error = got_error_from_errno("view_open");
4708 goto done;
4711 if (worktree) {
4712 error = set_tog_base_commit(repo, worktree);
4713 if (error != NULL)
4714 goto done;
4717 error = open_log_view(view, start_id, repo, head_ref_name,
4718 in_repo_path, log_branches, worktree);
4719 if (error)
4720 goto done;
4722 if (worktree) {
4723 /* The work tree will be closed by the log thread. */
4724 worktree = NULL;
4727 error = view_loop(view);
4729 done:
4730 free(tog_base_commit.id);
4731 free(keyword_idstr);
4732 free(in_repo_path);
4733 free(repo_path);
4734 free(cwd);
4735 free(start_id);
4736 free(label);
4737 if (ref)
4738 got_ref_close(ref);
4739 if (repo) {
4740 const struct got_error *close_err = got_repo_close(repo);
4741 if (error == NULL)
4742 error = close_err;
4744 if (worktree)
4745 got_worktree_close(worktree);
4746 if (pack_fds) {
4747 const struct got_error *pack_err =
4748 got_repo_pack_fds_close(pack_fds);
4749 if (error == NULL)
4750 error = pack_err;
4752 tog_free_refs();
4753 return error;
4756 __dead static void
4757 usage_diff(void)
4759 endwin();
4760 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4761 "object1 object2\n", getprogname());
4762 exit(1);
4765 static int
4766 match_line(const char *line, regex_t *regex, size_t nmatch,
4767 regmatch_t *regmatch)
4769 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4772 static struct tog_color *
4773 match_color(struct tog_colors *colors, const char *line)
4775 struct tog_color *tc = NULL;
4777 STAILQ_FOREACH(tc, colors, entry) {
4778 if (match_line(line, &tc->regex, 0, NULL))
4779 return tc;
4782 return NULL;
4785 static const struct got_error *
4786 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4787 WINDOW *window, int skipcol, regmatch_t *regmatch)
4789 const struct got_error *err = NULL;
4790 char *exstr = NULL;
4791 wchar_t *wline = NULL;
4792 int rme, rms, n, width, scrollx;
4793 int width0 = 0, width1 = 0, width2 = 0;
4794 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4796 *wtotal = 0;
4798 rms = regmatch->rm_so;
4799 rme = regmatch->rm_eo;
4801 err = expand_tab(&exstr, line);
4802 if (err)
4803 return err;
4805 /* Split the line into 3 segments, according to match offsets. */
4806 seg0 = strndup(exstr, rms);
4807 if (seg0 == NULL) {
4808 err = got_error_from_errno("strndup");
4809 goto done;
4811 seg1 = strndup(exstr + rms, rme - rms);
4812 if (seg1 == NULL) {
4813 err = got_error_from_errno("strndup");
4814 goto done;
4816 seg2 = strdup(exstr + rme);
4817 if (seg2 == NULL) {
4818 err = got_error_from_errno("strndup");
4819 goto done;
4822 /* draw up to matched token if we haven't scrolled past it */
4823 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4824 col_tab_align, 1);
4825 if (err)
4826 goto done;
4827 n = MAX(width0 - skipcol, 0);
4828 if (n) {
4829 free(wline);
4830 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4831 wlimit, col_tab_align, 1);
4832 if (err)
4833 goto done;
4834 waddwstr(window, &wline[scrollx]);
4835 wlimit -= width;
4836 *wtotal += width;
4839 if (wlimit > 0) {
4840 int i = 0, w = 0;
4841 size_t wlen;
4843 free(wline);
4844 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4845 col_tab_align, 1);
4846 if (err)
4847 goto done;
4848 wlen = wcslen(wline);
4849 while (i < wlen) {
4850 width = wcwidth(wline[i]);
4851 if (width == -1) {
4852 /* should not happen, tabs are expanded */
4853 err = got_error(GOT_ERR_RANGE);
4854 goto done;
4856 if (width0 + w + width > skipcol)
4857 break;
4858 w += width;
4859 i++;
4861 /* draw (visible part of) matched token (if scrolled into it) */
4862 if (width1 - w > 0) {
4863 wattron(window, A_STANDOUT);
4864 waddwstr(window, &wline[i]);
4865 wattroff(window, A_STANDOUT);
4866 wlimit -= (width1 - w);
4867 *wtotal += (width1 - w);
4871 if (wlimit > 0) { /* draw rest of line */
4872 free(wline);
4873 if (skipcol > width0 + width1) {
4874 err = format_line(&wline, &width2, &scrollx, seg2,
4875 skipcol - (width0 + width1), wlimit,
4876 col_tab_align, 1);
4877 if (err)
4878 goto done;
4879 waddwstr(window, &wline[scrollx]);
4880 } else {
4881 err = format_line(&wline, &width2, NULL, seg2, 0,
4882 wlimit, col_tab_align, 1);
4883 if (err)
4884 goto done;
4885 waddwstr(window, wline);
4887 *wtotal += width2;
4889 done:
4890 free(wline);
4891 free(exstr);
4892 free(seg0);
4893 free(seg1);
4894 free(seg2);
4895 return err;
4898 static int
4899 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4901 FILE *f = NULL;
4902 int *eof, *first, *selected;
4904 if (view->type == TOG_VIEW_DIFF) {
4905 struct tog_diff_view_state *s = &view->state.diff;
4907 first = &s->first_displayed_line;
4908 selected = first;
4909 eof = &s->eof;
4910 f = s->f;
4911 } else if (view->type == TOG_VIEW_HELP) {
4912 struct tog_help_view_state *s = &view->state.help;
4914 first = &s->first_displayed_line;
4915 selected = first;
4916 eof = &s->eof;
4917 f = s->f;
4918 } else if (view->type == TOG_VIEW_BLAME) {
4919 struct tog_blame_view_state *s = &view->state.blame;
4921 first = &s->first_displayed_line;
4922 selected = &s->selected_line;
4923 eof = &s->eof;
4924 f = s->blame.f;
4925 } else
4926 return 0;
4928 /* Center gline in the middle of the page like vi(1). */
4929 if (*lineno < view->gline - (view->nlines - 3) / 2)
4930 return 0;
4931 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4932 rewind(f);
4933 *eof = 0;
4934 *first = 1;
4935 *lineno = 0;
4936 *nprinted = 0;
4937 return 0;
4940 *selected = view->gline <= (view->nlines - 3) / 2 ?
4941 view->gline : (view->nlines - 3) / 2 + 1;
4942 view->gline = 0;
4944 return 1;
4947 static const struct got_error *
4948 draw_file(struct tog_view *view, const char *header)
4950 struct tog_diff_view_state *s = &view->state.diff;
4951 regmatch_t *regmatch = &view->regmatch;
4952 const struct got_error *err;
4953 int nprinted = 0;
4954 char *line;
4955 size_t linesize = 0;
4956 ssize_t linelen;
4957 wchar_t *wline;
4958 int width;
4959 int max_lines = view->nlines;
4960 int nlines = s->nlines;
4961 off_t line_offset;
4963 s->lineno = s->first_displayed_line - 1;
4964 line_offset = s->lines[s->first_displayed_line - 1].offset;
4965 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4966 return got_error_from_errno("fseek");
4968 werase(view->window);
4970 if (view->gline > s->nlines - 1)
4971 view->gline = s->nlines - 1;
4973 if (header) {
4974 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4975 1 : view->gline - (view->nlines - 3) / 2 :
4976 s->lineno + s->selected_line;
4978 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4979 return got_error_from_errno("asprintf");
4980 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4981 0, 0);
4982 free(line);
4983 if (err)
4984 return err;
4986 if (view_needs_focus_indication(view))
4987 wstandout(view->window);
4988 waddwstr(view->window, wline);
4989 free(wline);
4990 wline = NULL;
4991 while (width++ < view->ncols)
4992 waddch(view->window, ' ');
4993 if (view_needs_focus_indication(view))
4994 wstandend(view->window);
4996 if (max_lines <= 1)
4997 return NULL;
4998 max_lines--;
5001 s->eof = 0;
5002 view->maxx = 0;
5003 line = NULL;
5004 while (max_lines > 0 && nprinted < max_lines) {
5005 enum got_diff_line_type linetype;
5006 attr_t attr = 0;
5008 linelen = getline(&line, &linesize, s->f);
5009 if (linelen == -1) {
5010 if (feof(s->f)) {
5011 s->eof = 1;
5012 break;
5014 free(line);
5015 return got_ferror(s->f, GOT_ERR_IO);
5018 if (++s->lineno < s->first_displayed_line)
5019 continue;
5020 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
5021 continue;
5022 if (s->lineno == view->hiline)
5023 attr = A_STANDOUT;
5025 /* Set view->maxx based on full line length. */
5026 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
5027 view->x ? 1 : 0);
5028 if (err) {
5029 free(line);
5030 return err;
5032 view->maxx = MAX(view->maxx, width);
5033 free(wline);
5034 wline = NULL;
5036 linetype = s->lines[s->lineno].type;
5037 if (linetype > GOT_DIFF_LINE_LOGMSG &&
5038 linetype < GOT_DIFF_LINE_CONTEXT)
5039 attr |= COLOR_PAIR(linetype);
5040 if (attr)
5041 wattron(view->window, attr);
5042 if (s->first_displayed_line + nprinted == s->matched_line &&
5043 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5044 err = add_matched_line(&width, line, view->ncols, 0,
5045 view->window, view->x, regmatch);
5046 if (err) {
5047 free(line);
5048 return err;
5050 } else {
5051 int skip;
5052 err = format_line(&wline, &width, &skip, line,
5053 view->x, view->ncols, 0, view->x ? 1 : 0);
5054 if (err) {
5055 free(line);
5056 return err;
5058 waddwstr(view->window, &wline[skip]);
5059 free(wline);
5060 wline = NULL;
5062 if (s->lineno == view->hiline) {
5063 /* highlight full gline length */
5064 while (width++ < view->ncols)
5065 waddch(view->window, ' ');
5066 } else {
5067 if (width <= view->ncols - 1)
5068 waddch(view->window, '\n');
5070 if (attr)
5071 wattroff(view->window, attr);
5072 if (++nprinted == 1)
5073 s->first_displayed_line = s->lineno;
5075 free(line);
5076 if (nprinted >= 1)
5077 s->last_displayed_line = s->first_displayed_line +
5078 (nprinted - 1);
5079 else
5080 s->last_displayed_line = s->first_displayed_line;
5082 view_border(view);
5084 if (s->eof) {
5085 while (nprinted < view->nlines) {
5086 waddch(view->window, '\n');
5087 nprinted++;
5090 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
5091 view->ncols, 0, 0);
5092 if (err) {
5093 return err;
5096 wstandout(view->window);
5097 waddwstr(view->window, wline);
5098 free(wline);
5099 wline = NULL;
5100 wstandend(view->window);
5103 return NULL;
5106 static char *
5107 get_datestr(time_t *time, char *datebuf)
5109 struct tm mytm, *tm;
5110 char *p, *s;
5112 tm = gmtime_r(time, &mytm);
5113 if (tm == NULL)
5114 return NULL;
5115 s = asctime_r(tm, datebuf);
5116 if (s == NULL)
5117 return NULL;
5118 p = strchr(s, '\n');
5119 if (p)
5120 *p = '\0';
5121 return s;
5124 static const struct got_error *
5125 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
5126 off_t off, uint8_t type)
5128 struct got_diff_line *p;
5130 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
5131 if (p == NULL)
5132 return got_error_from_errno("reallocarray");
5133 *lines = p;
5134 (*lines)[*nlines].offset = off;
5135 (*lines)[*nlines].type = type;
5136 (*nlines)++;
5138 return NULL;
5141 static const struct got_error *
5142 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
5143 struct got_diff_line *s_lines, size_t s_nlines)
5145 struct got_diff_line *p;
5146 char buf[BUFSIZ];
5147 size_t i, r;
5149 if (fseeko(src, 0L, SEEK_SET) == -1)
5150 return got_error_from_errno("fseeko");
5152 for (;;) {
5153 r = fread(buf, 1, sizeof(buf), src);
5154 if (r == 0) {
5155 if (ferror(src))
5156 return got_error_from_errno("fread");
5157 if (feof(src))
5158 break;
5160 if (fwrite(buf, 1, r, dst) != r)
5161 return got_ferror(dst, GOT_ERR_IO);
5164 if (s_nlines == 0 && *d_nlines == 0)
5165 return NULL;
5168 * If commit info was in dst, increment line offsets
5169 * of the appended diff content, but skip s_lines[0]
5170 * because offset zero is already in *d_lines.
5172 if (*d_nlines > 0) {
5173 for (i = 1; i < s_nlines; ++i)
5174 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
5176 if (s_nlines > 0) {
5177 --s_nlines;
5178 ++s_lines;
5182 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
5183 if (p == NULL) {
5184 /* d_lines is freed in close_diff_view() */
5185 return got_error_from_errno("reallocarray");
5188 *d_lines = p;
5190 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
5191 *d_nlines += s_nlines;
5193 return NULL;
5196 static const struct got_error *
5197 write_diffstat(FILE *outfile, struct got_diff_line **lines, size_t *nlines,
5198 struct got_diffstat_cb_arg *dsa)
5200 const struct got_error *err;
5201 struct got_pathlist_entry *pe;
5202 off_t offset;
5203 int n;
5205 if (*nlines == 0) {
5206 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
5207 if (err != NULL)
5208 return err;
5209 offset = 0;
5210 } else
5211 offset = (*lines)[*nlines - 1].offset;
5213 TAILQ_FOREACH(pe, dsa->paths, entry) {
5214 struct got_diff_changed_path *cp = pe->data;
5215 int pad = dsa->max_path_len - pe->path_len + 1;
5217 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5218 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5219 dsa->rm_cols + 1, cp->rm);
5220 if (n < 0)
5221 return got_error_from_errno("fprintf");
5223 offset += n;
5224 err = add_line_metadata(lines, nlines, offset,
5225 GOT_DIFF_LINE_CHANGES);
5226 if (err != NULL)
5227 return err;
5230 if (fputc('\n', outfile) == EOF)
5231 return got_error_from_errno("fputc");
5233 offset++;
5234 err = add_line_metadata(lines, nlines, offset, GOT_DIFF_LINE_NONE);
5235 if (err != NULL)
5236 return err;
5238 n = fprintf(outfile,
5239 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5240 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5241 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5242 if (n < 0)
5243 return got_error_from_errno("fprintf");
5245 offset += n;
5246 err = add_line_metadata(lines, nlines, offset, GOT_DIFF_LINE_NONE);
5247 if (err != NULL)
5248 return err;
5250 if (fputc('\n', outfile) == EOF)
5251 return got_error_from_errno("fputc");
5253 offset++;
5254 return add_line_metadata(lines, nlines, offset, GOT_DIFF_LINE_NONE);
5257 static const struct got_error *
5258 write_commit_info(struct got_diff_line **lines, size_t *nlines,
5259 struct got_object_id *commit_id, struct got_reflist_head *refs,
5260 struct got_repository *repo, int ignore_ws, int force_text_diff,
5261 struct got_diffstat_cb_arg *dsa, FILE *outfile)
5263 const struct got_error *err = NULL;
5264 char datebuf[26], *datestr;
5265 struct got_commit_object *commit;
5266 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
5267 time_t committer_time;
5268 const char *author, *committer;
5269 char *refs_str = NULL;
5270 off_t outoff = 0;
5271 int n;
5273 err = build_refs_str(&refs_str, refs, commit_id, repo);
5274 if (err)
5275 return err;
5277 err = got_object_open_as_commit(&commit, repo, commit_id);
5278 if (err)
5279 return err;
5281 err = got_object_id_str(&id_str, commit_id);
5282 if (err) {
5283 err = got_error_from_errno("got_object_id_str");
5284 goto done;
5287 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
5288 if (err)
5289 goto done;
5291 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
5292 refs_str ? refs_str : "", refs_str ? ")" : "");
5293 if (n < 0) {
5294 err = got_error_from_errno("fprintf");
5295 goto done;
5297 outoff += n;
5298 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
5299 if (err)
5300 goto done;
5302 n = fprintf(outfile, "from: %s\n",
5303 got_object_commit_get_author(commit));
5304 if (n < 0) {
5305 err = got_error_from_errno("fprintf");
5306 goto done;
5308 outoff += n;
5309 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
5310 if (err)
5311 goto done;
5313 author = got_object_commit_get_author(commit);
5314 committer = got_object_commit_get_committer(commit);
5315 if (strcmp(author, committer) != 0) {
5316 n = fprintf(outfile, "via: %s\n", committer);
5317 if (n < 0) {
5318 err = got_error_from_errno("fprintf");
5319 goto done;
5321 outoff += n;
5322 err = add_line_metadata(lines, nlines, outoff,
5323 GOT_DIFF_LINE_AUTHOR);
5324 if (err)
5325 goto done;
5327 committer_time = got_object_commit_get_committer_time(commit);
5328 datestr = get_datestr(&committer_time, datebuf);
5329 if (datestr) {
5330 n = fprintf(outfile, "date: %s UTC\n", datestr);
5331 if (n < 0) {
5332 err = got_error_from_errno("fprintf");
5333 goto done;
5335 outoff += n;
5336 err = add_line_metadata(lines, nlines, outoff,
5337 GOT_DIFF_LINE_DATE);
5338 if (err)
5339 goto done;
5341 if (got_object_commit_get_nparents(commit) > 1) {
5342 const struct got_object_id_queue *parent_ids;
5343 struct got_object_qid *qid;
5344 int pn = 1;
5345 parent_ids = got_object_commit_get_parent_ids(commit);
5346 STAILQ_FOREACH(qid, parent_ids, entry) {
5347 err = got_object_id_str(&id_str, &qid->id);
5348 if (err)
5349 goto done;
5350 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5351 if (n < 0) {
5352 err = got_error_from_errno("fprintf");
5353 goto done;
5355 outoff += n;
5356 err = add_line_metadata(lines, nlines, outoff,
5357 GOT_DIFF_LINE_META);
5358 if (err)
5359 goto done;
5360 free(id_str);
5361 id_str = NULL;
5365 err = got_object_commit_get_logmsg(&logmsg, commit);
5366 if (err)
5367 goto done;
5368 s = logmsg;
5369 while ((line = strsep(&s, "\n")) != NULL) {
5370 n = fprintf(outfile, "%s\n", line);
5371 if (n < 0) {
5372 err = got_error_from_errno("fprintf");
5373 goto done;
5375 outoff += n;
5376 err = add_line_metadata(lines, nlines, outoff,
5377 GOT_DIFF_LINE_LOGMSG);
5378 if (err)
5379 goto done;
5382 done:
5383 free(id_str);
5384 free(logmsg);
5385 free(refs_str);
5386 got_object_commit_close(commit);
5387 return err;
5390 static const struct got_error *
5391 create_diff(struct tog_diff_view_state *s)
5393 const struct got_error *err = NULL;
5394 FILE *tmp_diff_file = NULL;
5395 int obj_type;
5396 struct got_diff_line *lines = NULL;
5397 struct got_pathlist_head changed_paths;
5398 struct got_commit_object *commit2 = NULL;
5399 struct got_diffstat_cb_arg dsa;
5400 size_t nlines = 0;
5402 TAILQ_INIT(&changed_paths);
5403 memset(&dsa, 0, sizeof(dsa));
5404 dsa.paths = &changed_paths;
5405 dsa.diff_algo = tog_diff_algo;
5406 dsa.force_text = s->force_text_diff;
5407 dsa.ignore_ws = s->ignore_whitespace;
5409 free(s->lines);
5410 s->lines = malloc(sizeof(*s->lines));
5411 if (s->lines == NULL)
5412 return got_error_from_errno("malloc");
5413 s->nlines = 0;
5415 if (s->f && fclose(s->f) == EOF) {
5416 s->f = NULL;
5417 return got_error_from_errno("fclose");
5420 s->f = got_opentemp();
5421 if (s->f == NULL)
5422 return got_error_from_errno("got_opentemp");
5425 * The diffstat requires the diff to be built first, but we want the
5426 * diffstat to precede the diff when displayed. Build the diff first
5427 * in the temporary file and write the diffstat and/or commit info to
5428 * the persistent file (s->f) from which views are drawn, then append
5429 * the diff from the temp file to the diffstat/commit info in s->f.
5431 tmp_diff_file = got_opentemp();
5432 if (tmp_diff_file == NULL)
5433 return got_error_from_errno("got_opentemp");
5435 lines = malloc(sizeof(*lines));
5436 if (lines == NULL) {
5437 err = got_error_from_errno("malloc");
5438 goto done;
5441 if (s->id1)
5442 err = got_object_get_type(&obj_type, s->repo, s->id1);
5443 else
5444 err = got_object_get_type(&obj_type, s->repo, s->id2);
5445 if (err)
5446 goto done;
5448 switch (obj_type) {
5449 case GOT_OBJ_TYPE_BLOB:
5450 err = got_diff_objects_as_blobs(&lines, &nlines,
5451 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5452 NULL, NULL, tog_diff_algo, s->diff_context,
5453 s->ignore_whitespace, s->force_text_diff, &dsa, s->repo,
5454 tmp_diff_file);
5455 if (err != NULL)
5456 goto done;
5457 break;
5458 case GOT_OBJ_TYPE_TREE:
5459 err = got_diff_objects_as_trees(&lines, &nlines,
5460 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5461 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5462 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5463 if (err != NULL)
5464 goto done;
5465 break;
5466 case GOT_OBJ_TYPE_COMMIT: {
5467 const struct got_object_id_queue *parent_ids;
5468 struct got_object_qid *pid;
5469 struct got_reflist_head *refs;
5471 err = got_diff_objects_as_commits(&lines, &nlines,
5472 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5473 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5474 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5475 if (err)
5476 goto done;
5478 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5479 /* Show commit info if we're diffing to a parent/root commit. */
5480 if (s->id1 == NULL) {
5481 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5482 refs, s->repo, s->ignore_whitespace,
5483 s->force_text_diff, &dsa, s->f);
5484 if (err)
5485 goto done;
5486 } else {
5487 err = got_object_open_as_commit(&commit2, s->repo,
5488 s->id2);
5489 if (err)
5490 goto done;
5492 parent_ids = got_object_commit_get_parent_ids(commit2);
5493 STAILQ_FOREACH(pid, parent_ids, entry) {
5494 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5495 err = write_commit_info(&s->lines,
5496 &s->nlines, s->id2, refs, s->repo,
5497 s->ignore_whitespace,
5498 s->force_text_diff, &dsa, s->f);
5499 if (err)
5500 goto done;
5501 break;
5505 break;
5507 default:
5508 err = got_error(GOT_ERR_OBJ_TYPE);
5509 goto done;
5512 err = write_diffstat(s->f, &s->lines, &s->nlines, &dsa);
5513 if (err != NULL)
5514 goto done;
5516 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5517 lines, nlines);
5519 done:
5520 free(lines);
5521 if (commit2 != NULL)
5522 got_object_commit_close(commit2);
5523 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5524 if (s->f && fflush(s->f) != 0 && err == NULL)
5525 err = got_error_from_errno("fflush");
5526 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5527 err = got_error_from_errno("fclose");
5528 return err;
5531 static void
5532 diff_view_indicate_progress(struct tog_view *view)
5534 mvwaddstr(view->window, 0, 0, "diffing...");
5535 update_panels();
5536 doupdate();
5539 static const struct got_error *
5540 search_start_diff_view(struct tog_view *view)
5542 struct tog_diff_view_state *s = &view->state.diff;
5544 s->matched_line = 0;
5545 return NULL;
5548 static void
5549 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5550 size_t *nlines, int **first, int **last, int **match, int **selected)
5552 struct tog_diff_view_state *s = &view->state.diff;
5554 *f = s->f;
5555 *nlines = s->nlines;
5556 *line_offsets = NULL;
5557 *match = &s->matched_line;
5558 *first = &s->first_displayed_line;
5559 *last = &s->last_displayed_line;
5560 *selected = &s->selected_line;
5563 static const struct got_error *
5564 search_next_view_match(struct tog_view *view)
5566 const struct got_error *err = NULL;
5567 FILE *f;
5568 int lineno;
5569 char *line = NULL;
5570 size_t linesize = 0;
5571 ssize_t linelen;
5572 off_t *line_offsets;
5573 size_t nlines = 0;
5574 int *first, *last, *match, *selected;
5576 if (!view->search_setup)
5577 return got_error_msg(GOT_ERR_NOT_IMPL,
5578 "view search not supported");
5579 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5580 &match, &selected);
5582 if (!view->searching) {
5583 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5584 return NULL;
5587 if (*match) {
5588 if (view->searching == TOG_SEARCH_FORWARD)
5589 lineno = *first + 1;
5590 else
5591 lineno = *first - 1;
5592 } else
5593 lineno = *first - 1 + *selected;
5595 while (1) {
5596 off_t offset;
5598 if (lineno <= 0 || lineno > nlines) {
5599 if (*match == 0) {
5600 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5601 break;
5604 if (view->searching == TOG_SEARCH_FORWARD)
5605 lineno = 1;
5606 else
5607 lineno = nlines;
5610 offset = view->type == TOG_VIEW_DIFF ?
5611 view->state.diff.lines[lineno - 1].offset :
5612 line_offsets[lineno - 1];
5613 if (fseeko(f, offset, SEEK_SET) != 0) {
5614 free(line);
5615 return got_error_from_errno("fseeko");
5617 linelen = getline(&line, &linesize, f);
5618 if (linelen != -1) {
5619 char *exstr;
5620 err = expand_tab(&exstr, line);
5621 if (err)
5622 break;
5623 if (match_line(exstr, &view->regex, 1,
5624 &view->regmatch)) {
5625 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5626 *match = lineno;
5627 free(exstr);
5628 break;
5630 free(exstr);
5632 if (view->searching == TOG_SEARCH_FORWARD)
5633 lineno++;
5634 else
5635 lineno--;
5637 free(line);
5639 if (*match) {
5640 *first = *match;
5641 *selected = 1;
5644 return err;
5647 static const struct got_error *
5648 close_diff_view(struct tog_view *view)
5650 const struct got_error *err = NULL;
5651 struct tog_diff_view_state *s = &view->state.diff;
5653 free(s->id1);
5654 s->id1 = NULL;
5655 free(s->id2);
5656 s->id2 = NULL;
5657 free(s->action);
5658 s->action = NULL;
5659 if (s->f && fclose(s->f) == EOF)
5660 err = got_error_from_errno("fclose");
5661 s->f = NULL;
5662 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5663 err = got_error_from_errno("fclose");
5664 s->f1 = NULL;
5665 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5666 err = got_error_from_errno("fclose");
5667 s->f2 = NULL;
5668 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5669 err = got_error_from_errno("close");
5670 s->fd1 = -1;
5671 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5672 err = got_error_from_errno("close");
5673 s->fd2 = -1;
5674 free(s->lines);
5675 s->lines = NULL;
5676 s->nlines = 0;
5677 return err;
5680 static const struct got_error *
5681 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5682 struct got_object_id *id2, const char *label1, const char *label2,
5683 int diff_context, int ignore_whitespace, int force_text_diff,
5684 struct tog_view *parent_view, struct got_repository *repo)
5686 const struct got_error *err;
5687 struct tog_diff_view_state *s = &view->state.diff;
5689 memset(s, 0, sizeof(*s));
5690 s->fd1 = -1;
5691 s->fd2 = -1;
5693 if (id1 != NULL && id2 != NULL) {
5694 int type1, type2;
5696 err = got_object_get_type(&type1, repo, id1);
5697 if (err)
5698 goto done;
5699 err = got_object_get_type(&type2, repo, id2);
5700 if (err)
5701 goto done;
5703 if (type1 != type2) {
5704 err = got_error(GOT_ERR_OBJ_TYPE);
5705 goto done;
5708 s->first_displayed_line = 1;
5709 s->last_displayed_line = view->nlines;
5710 s->selected_line = 1;
5711 s->repo = repo;
5712 s->label1 = label1;
5713 s->label2 = label2;
5715 if (id1) {
5716 s->id1 = got_object_id_dup(id1);
5717 if (s->id1 == NULL) {
5718 err = got_error_from_errno("got_object_id_dup");
5719 goto done;
5721 } else
5722 s->id1 = NULL;
5724 s->id2 = got_object_id_dup(id2);
5725 if (s->id2 == NULL) {
5726 err = got_error_from_errno("got_object_id_dup");
5727 goto done;
5730 s->f1 = got_opentemp();
5731 if (s->f1 == NULL) {
5732 err = got_error_from_errno("got_opentemp");
5733 goto done;
5736 s->f2 = got_opentemp();
5737 if (s->f2 == NULL) {
5738 err = got_error_from_errno("got_opentemp");
5739 goto done;
5742 s->fd1 = got_opentempfd();
5743 if (s->fd1 == -1) {
5744 err = got_error_from_errno("got_opentempfd");
5745 goto done;
5748 s->fd2 = got_opentempfd();
5749 if (s->fd2 == -1) {
5750 err = got_error_from_errno("got_opentempfd");
5751 goto done;
5754 s->diff_context = diff_context;
5755 s->ignore_whitespace = ignore_whitespace;
5756 s->force_text_diff = force_text_diff;
5757 s->parent_view = parent_view;
5758 s->repo = repo;
5760 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5761 int rc;
5763 rc = init_pair(GOT_DIFF_LINE_MINUS,
5764 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5765 if (rc != ERR)
5766 rc = init_pair(GOT_DIFF_LINE_PLUS,
5767 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5768 if (rc != ERR)
5769 rc = init_pair(GOT_DIFF_LINE_HUNK,
5770 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5771 if (rc != ERR)
5772 rc = init_pair(GOT_DIFF_LINE_META,
5773 get_color_value("TOG_COLOR_DIFF_META"), -1);
5774 if (rc != ERR)
5775 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5776 get_color_value("TOG_COLOR_DIFF_META"), -1);
5777 if (rc != ERR)
5778 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5779 get_color_value("TOG_COLOR_DIFF_META"), -1);
5780 if (rc != ERR)
5781 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5782 get_color_value("TOG_COLOR_DIFF_META"), -1);
5783 if (rc != ERR)
5784 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5785 get_color_value("TOG_COLOR_AUTHOR"), -1);
5786 if (rc != ERR)
5787 rc = init_pair(GOT_DIFF_LINE_DATE,
5788 get_color_value("TOG_COLOR_DATE"), -1);
5789 if (rc == ERR) {
5790 err = got_error(GOT_ERR_RANGE);
5791 goto done;
5795 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5796 view_is_splitscreen(view))
5797 show_log_view(parent_view); /* draw border */
5798 diff_view_indicate_progress(view);
5800 err = create_diff(s);
5802 view->show = show_diff_view;
5803 view->input = input_diff_view;
5804 view->reset = reset_diff_view;
5805 view->close = close_diff_view;
5806 view->search_start = search_start_diff_view;
5807 view->search_setup = search_setup_diff_view;
5808 view->search_next = search_next_view_match;
5809 done:
5810 if (err) {
5811 if (view->close == NULL)
5812 close_diff_view(view);
5813 view_close(view);
5815 return err;
5818 static const struct got_error *
5819 show_diff_view(struct tog_view *view)
5821 const struct got_error *err;
5822 struct tog_diff_view_state *s = &view->state.diff;
5823 char *id_str1 = NULL, *id_str2, *header;
5824 const char *label1, *label2;
5826 if (s->id1) {
5827 err = got_object_id_str(&id_str1, s->id1);
5828 if (err)
5829 return err;
5830 label1 = s->label1 ? s->label1 : id_str1;
5831 } else
5832 label1 = "/dev/null";
5834 err = got_object_id_str(&id_str2, s->id2);
5835 if (err)
5836 return err;
5837 label2 = s->label2 ? s->label2 : id_str2;
5839 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5840 err = got_error_from_errno("asprintf");
5841 free(id_str1);
5842 free(id_str2);
5843 return err;
5845 free(id_str1);
5846 free(id_str2);
5848 err = draw_file(view, header);
5849 free(header);
5850 return err;
5853 static const struct got_error *
5854 diff_write_patch(struct tog_view *view)
5856 const struct got_error *err;
5857 struct tog_diff_view_state *s = &view->state.diff;
5858 FILE *f = NULL;
5859 char buf[BUFSIZ], pathbase[PATH_MAX];
5860 char *idstr2, *idstr1 = NULL, *path = NULL;
5861 size_t r;
5862 off_t pos;
5863 int rc;
5865 if (s->action != NULL) {
5866 free(s->action);
5867 s->action = NULL;
5870 pos = ftello(s->f);
5871 if (pos == -1)
5872 return got_error_from_errno("ftello");
5873 if (fseeko(s->f, 0L, SEEK_SET) == -1)
5874 return got_error_from_errno("fseeko");
5876 if (s->id1 != NULL) {
5877 err = got_object_id_str(&idstr1, s->id1);
5878 if (err != NULL)
5879 return err;
5881 err = got_object_id_str(&idstr2, s->id2);
5882 if (err != NULL)
5883 goto done;
5885 rc = snprintf(pathbase, sizeof(pathbase), "%s/tog-%.8s-%.8s",
5886 GOT_TMPDIR_STR, idstr1 != NULL ? idstr1 : "empty", idstr2);
5887 if (rc < 0 || (size_t)rc >= sizeof(pathbase)) {
5888 err = got_error(rc < 0 ? GOT_ERR_IO : GOT_ERR_NO_SPACE);
5889 goto done;
5892 err = got_opentemp_named(&path, &f, pathbase, ".diff");
5893 if (err != NULL)
5894 goto done;
5896 while ((r = fread(buf, 1, sizeof(buf), s->f)) > 0) {
5897 if (fwrite(buf, 1, r, f) != r) {
5898 err = got_ferror(f, GOT_ERR_IO);
5899 goto done;
5903 if (ferror(s->f)) {
5904 err = got_error_from_errno("fread");
5905 goto done;
5907 if (fseeko(s->f, pos, SEEK_SET) == -1) {
5908 err = got_error_from_errno("fseeko");
5909 goto done;
5912 if (fflush(f) == EOF) {
5913 err = got_error_from_errno2("fflush", path);
5914 goto done;
5917 if (asprintf(&s->action, "patch file written to %s", path) == -1) {
5918 err = got_error_from_errno("asprintf");
5919 goto done;
5922 view->action = s->action;
5924 done:
5925 if (f != NULL && fclose(f) == EOF && err == NULL)
5926 err = got_error_from_errno2("fclose", path);
5927 free(path);
5928 free(idstr1);
5929 free(idstr2);
5930 return err;
5933 static const struct got_error *
5934 set_selected_commit(struct tog_diff_view_state *s,
5935 struct commit_queue_entry *entry)
5937 const struct got_error *err;
5938 const struct got_object_id_queue *parent_ids;
5939 struct got_commit_object *selected_commit;
5940 struct got_object_qid *pid;
5942 free(s->id2);
5943 s->id2 = got_object_id_dup(entry->id);
5944 if (s->id2 == NULL)
5945 return got_error_from_errno("got_object_id_dup");
5947 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5948 if (err)
5949 return err;
5950 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5951 free(s->id1);
5952 pid = STAILQ_FIRST(parent_ids);
5953 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5954 got_object_commit_close(selected_commit);
5955 return NULL;
5958 static const struct got_error *
5959 reset_diff_view(struct tog_view *view)
5961 struct tog_diff_view_state *s = &view->state.diff;
5963 view->count = 0;
5964 wclear(view->window);
5965 s->first_displayed_line = 1;
5966 s->last_displayed_line = view->nlines;
5967 s->matched_line = 0;
5968 if (s->action != NULL) {
5969 free(s->action);
5970 s->action = NULL;
5972 diff_view_indicate_progress(view);
5973 return create_diff(s);
5976 static void
5977 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5979 int start, i;
5981 i = start = s->first_displayed_line - 1;
5983 while (s->lines[i].type != type) {
5984 if (i == 0)
5985 i = s->nlines - 1;
5986 if (--i == start)
5987 return; /* do nothing, requested type not in file */
5990 s->selected_line = 1;
5991 s->first_displayed_line = i;
5994 static void
5995 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5997 int start, i;
5999 i = start = s->first_displayed_line + 1;
6001 while (s->lines[i].type != type) {
6002 if (i == s->nlines - 1)
6003 i = 0;
6004 if (++i == start)
6005 return; /* do nothing, requested type not in file */
6008 s->selected_line = 1;
6009 s->first_displayed_line = i;
6012 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
6013 int, int, int);
6014 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
6015 int, int);
6017 static const struct got_error *
6018 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
6020 const struct got_error *err = NULL;
6021 struct tog_diff_view_state *s = &view->state.diff;
6022 struct tog_log_view_state *ls;
6023 struct commit_queue_entry *old_selected_entry;
6024 char *line = NULL;
6025 size_t linesize = 0;
6026 ssize_t linelen;
6027 int i, nscroll = view->nlines - 1, up = 0;
6029 s->lineno = s->first_displayed_line - 1 + s->selected_line;
6031 if (s->action != NULL && ch != ERR) {
6032 free(s->action);
6033 s->action = NULL;
6034 view->action = NULL;
6037 switch (ch) {
6038 case '0':
6039 case '$':
6040 case KEY_RIGHT:
6041 case 'l':
6042 case KEY_LEFT:
6043 case 'h':
6044 horizontal_scroll_input(view, ch);
6045 break;
6046 case 'a':
6047 case 'w':
6048 if (ch == 'a') {
6049 s->force_text_diff = !s->force_text_diff;
6050 view->action = s->force_text_diff ?
6051 "force ASCII text enabled" :
6052 "force ASCII text disabled";
6054 else if (ch == 'w') {
6055 s->ignore_whitespace = !s->ignore_whitespace;
6056 view->action = s->ignore_whitespace ?
6057 "ignore whitespace enabled" :
6058 "ignore whitespace disabled";
6060 err = reset_diff_view(view);
6061 break;
6062 case 'g':
6063 case KEY_HOME:
6064 s->first_displayed_line = 1;
6065 view->count = 0;
6066 break;
6067 case 'G':
6068 case KEY_END:
6069 view->count = 0;
6070 if (s->eof)
6071 break;
6073 s->first_displayed_line = (s->nlines - view->nlines) + 2;
6074 s->eof = 1;
6075 break;
6076 case 'k':
6077 case KEY_UP:
6078 case CTRL('p'):
6079 if (s->first_displayed_line > 1)
6080 s->first_displayed_line--;
6081 else
6082 view->count = 0;
6083 break;
6084 case CTRL('u'):
6085 case 'u':
6086 nscroll /= 2;
6087 /* FALL THROUGH */
6088 case KEY_PPAGE:
6089 case CTRL('b'):
6090 case 'b':
6091 if (s->first_displayed_line == 1) {
6092 view->count = 0;
6093 break;
6095 i = 0;
6096 while (i++ < nscroll && s->first_displayed_line > 1)
6097 s->first_displayed_line--;
6098 break;
6099 case 'j':
6100 case KEY_DOWN:
6101 case CTRL('n'):
6102 if (!s->eof)
6103 s->first_displayed_line++;
6104 else
6105 view->count = 0;
6106 break;
6107 case CTRL('d'):
6108 case 'd':
6109 nscroll /= 2;
6110 /* FALL THROUGH */
6111 case KEY_NPAGE:
6112 case CTRL('f'):
6113 case 'f':
6114 case ' ':
6115 if (s->eof) {
6116 view->count = 0;
6117 break;
6119 i = 0;
6120 while (!s->eof && i++ < nscroll) {
6121 linelen = getline(&line, &linesize, s->f);
6122 s->first_displayed_line++;
6123 if (linelen == -1) {
6124 if (feof(s->f)) {
6125 s->eof = 1;
6126 } else
6127 err = got_ferror(s->f, GOT_ERR_IO);
6128 break;
6131 free(line);
6132 break;
6133 case '(':
6134 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
6135 break;
6136 case ')':
6137 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
6138 break;
6139 case '{':
6140 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
6141 break;
6142 case '}':
6143 diff_next_index(s, GOT_DIFF_LINE_HUNK);
6144 break;
6145 case '[':
6146 if (s->diff_context > 0) {
6147 s->diff_context--;
6148 s->matched_line = 0;
6149 diff_view_indicate_progress(view);
6150 err = create_diff(s);
6151 if (s->first_displayed_line + view->nlines - 1 >
6152 s->nlines) {
6153 s->first_displayed_line = 1;
6154 s->last_displayed_line = view->nlines;
6156 } else
6157 view->count = 0;
6158 break;
6159 case ']':
6160 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
6161 s->diff_context++;
6162 s->matched_line = 0;
6163 diff_view_indicate_progress(view);
6164 err = create_diff(s);
6165 } else
6166 view->count = 0;
6167 break;
6168 case '<':
6169 case ',':
6170 case 'K':
6171 up = 1;
6172 /* FALL THROUGH */
6173 case '>':
6174 case '.':
6175 case 'J':
6176 if (s->parent_view == NULL) {
6177 view->count = 0;
6178 break;
6180 s->parent_view->count = view->count;
6182 if (s->parent_view->type == TOG_VIEW_LOG) {
6183 ls = &s->parent_view->state.log;
6184 old_selected_entry = ls->selected_entry;
6186 err = input_log_view(NULL, s->parent_view,
6187 up ? KEY_UP : KEY_DOWN);
6188 if (err)
6189 break;
6190 view->count = s->parent_view->count;
6192 if (old_selected_entry == ls->selected_entry)
6193 break;
6195 log_mark_clear(ls);
6197 err = set_selected_commit(s, ls->selected_entry);
6198 if (err)
6199 break;
6200 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
6201 struct tog_blame_view_state *bs;
6202 struct got_object_id *id, *prev_id;
6204 bs = &s->parent_view->state.blame;
6205 prev_id = get_annotation_for_line(bs->blame.lines,
6206 bs->blame.nlines, bs->last_diffed_line);
6208 err = input_blame_view(&view, s->parent_view,
6209 up ? KEY_UP : KEY_DOWN);
6210 if (err)
6211 break;
6212 view->count = s->parent_view->count;
6214 if (prev_id == NULL)
6215 break;
6216 id = get_selected_commit_id(bs->blame.lines,
6217 bs->blame.nlines, bs->first_displayed_line,
6218 bs->selected_line);
6219 if (id == NULL)
6220 break;
6222 if (!got_object_id_cmp(prev_id, id))
6223 break;
6225 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
6226 if (err)
6227 break;
6229 s->first_displayed_line = 1;
6230 s->last_displayed_line = view->nlines;
6231 s->matched_line = 0;
6232 view->x = 0;
6234 diff_view_indicate_progress(view);
6235 err = create_diff(s);
6236 break;
6237 case 'p':
6238 err = diff_write_patch(view);
6239 break;
6240 default:
6241 view->count = 0;
6242 break;
6245 return err;
6248 static const struct got_error *
6249 cmd_diff(int argc, char *argv[])
6251 const struct got_error *error;
6252 struct got_repository *repo = NULL;
6253 struct got_worktree *worktree = NULL;
6254 struct got_object_id *id1 = NULL, *id2 = NULL;
6255 char *repo_path = NULL, *cwd = NULL;
6256 char *id_str1 = NULL, *id_str2 = NULL;
6257 char *keyword_idstr1 = NULL, *keyword_idstr2 = NULL;
6258 char *label1 = NULL, *label2 = NULL;
6259 int diff_context = 3, ignore_whitespace = 0;
6260 int ch, force_text_diff = 0;
6261 const char *errstr;
6262 struct tog_view *view;
6263 int *pack_fds = NULL;
6265 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
6266 switch (ch) {
6267 case 'a':
6268 force_text_diff = 1;
6269 break;
6270 case 'C':
6271 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
6272 &errstr);
6273 if (errstr != NULL)
6274 errx(1, "number of context lines is %s: %s",
6275 errstr, errstr);
6276 break;
6277 case 'r':
6278 repo_path = realpath(optarg, NULL);
6279 if (repo_path == NULL)
6280 return got_error_from_errno2("realpath",
6281 optarg);
6282 got_path_strip_trailing_slashes(repo_path);
6283 break;
6284 case 'w':
6285 ignore_whitespace = 1;
6286 break;
6287 default:
6288 usage_diff();
6289 /* NOTREACHED */
6293 argc -= optind;
6294 argv += optind;
6296 if (argc == 0) {
6297 usage_diff(); /* TODO show local worktree changes */
6298 } else if (argc == 2) {
6299 id_str1 = argv[0];
6300 id_str2 = argv[1];
6301 } else
6302 usage_diff();
6304 error = got_repo_pack_fds_open(&pack_fds);
6305 if (error)
6306 goto done;
6308 if (repo_path == NULL) {
6309 cwd = getcwd(NULL, 0);
6310 if (cwd == NULL)
6311 return got_error_from_errno("getcwd");
6312 error = got_worktree_open(&worktree, cwd, NULL);
6313 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6314 goto done;
6315 if (worktree)
6316 repo_path =
6317 strdup(got_worktree_get_repo_path(worktree));
6318 else
6319 repo_path = strdup(cwd);
6320 if (repo_path == NULL) {
6321 error = got_error_from_errno("strdup");
6322 goto done;
6326 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6327 if (error)
6328 goto done;
6330 init_curses();
6332 error = apply_unveil(got_repo_get_path(repo), NULL);
6333 if (error)
6334 goto done;
6336 error = tog_load_refs(repo, 0);
6337 if (error)
6338 goto done;
6340 if (id_str1 != NULL) {
6341 error = got_keyword_to_idstr(&keyword_idstr1, id_str1,
6342 repo, worktree);
6343 if (error != NULL)
6344 goto done;
6345 if (keyword_idstr1 != NULL)
6346 id_str1 = keyword_idstr1;
6348 if (id_str2 != NULL) {
6349 error = got_keyword_to_idstr(&keyword_idstr2, id_str2,
6350 repo, worktree);
6351 if (error != NULL)
6352 goto done;
6353 if (keyword_idstr2 != NULL)
6354 id_str2 = keyword_idstr2;
6357 error = got_repo_match_object_id(&id1, &label1, id_str1,
6358 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6359 if (error)
6360 goto done;
6362 error = got_repo_match_object_id(&id2, &label2, id_str2,
6363 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6364 if (error)
6365 goto done;
6367 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
6368 if (view == NULL) {
6369 error = got_error_from_errno("view_open");
6370 goto done;
6372 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
6373 ignore_whitespace, force_text_diff, NULL, repo);
6374 if (error)
6375 goto done;
6377 if (worktree) {
6378 error = set_tog_base_commit(repo, worktree);
6379 if (error != NULL)
6380 goto done;
6382 /* Release work tree lock. */
6383 got_worktree_close(worktree);
6384 worktree = NULL;
6387 error = view_loop(view);
6389 done:
6390 free(tog_base_commit.id);
6391 free(keyword_idstr1);
6392 free(keyword_idstr2);
6393 free(label1);
6394 free(label2);
6395 free(id1);
6396 free(id2);
6397 free(repo_path);
6398 free(cwd);
6399 if (repo) {
6400 const struct got_error *close_err = got_repo_close(repo);
6401 if (error == NULL)
6402 error = close_err;
6404 if (worktree)
6405 got_worktree_close(worktree);
6406 if (pack_fds) {
6407 const struct got_error *pack_err =
6408 got_repo_pack_fds_close(pack_fds);
6409 if (error == NULL)
6410 error = pack_err;
6412 tog_free_refs();
6413 return error;
6416 __dead static void
6417 usage_blame(void)
6419 endwin();
6420 fprintf(stderr,
6421 "usage: %s blame [-c commit] [-r repository-path] path\n",
6422 getprogname());
6423 exit(1);
6426 struct tog_blame_line {
6427 int annotated;
6428 struct got_object_id *id;
6431 static const struct got_error *
6432 draw_blame(struct tog_view *view)
6434 struct tog_blame_view_state *s = &view->state.blame;
6435 struct tog_blame *blame = &s->blame;
6436 regmatch_t *regmatch = &view->regmatch;
6437 const struct got_error *err;
6438 int lineno = 0, nprinted = 0;
6439 char *line = NULL;
6440 size_t linesize = 0;
6441 ssize_t linelen;
6442 wchar_t *wline;
6443 int width;
6444 struct tog_blame_line *blame_line;
6445 struct got_object_id *prev_id = NULL;
6446 char *id_str;
6447 struct tog_color *tc;
6449 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6450 if (err)
6451 return err;
6453 rewind(blame->f);
6454 werase(view->window);
6456 if (asprintf(&line, "commit %s", id_str) == -1) {
6457 err = got_error_from_errno("asprintf");
6458 free(id_str);
6459 return err;
6462 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6463 free(line);
6464 line = NULL;
6465 if (err)
6466 return err;
6467 if (view_needs_focus_indication(view))
6468 wstandout(view->window);
6469 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6470 if (tc)
6471 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6472 waddwstr(view->window, wline);
6473 while (width++ < view->ncols)
6474 waddch(view->window, ' ');
6475 if (tc)
6476 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6477 if (view_needs_focus_indication(view))
6478 wstandend(view->window);
6479 free(wline);
6480 wline = NULL;
6482 if (view->gline > blame->nlines)
6483 view->gline = blame->nlines;
6485 if (tog_io.wait_for_ui) {
6486 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6487 int rc;
6489 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6490 if (rc)
6491 return got_error_set_errno(rc, "pthread_cond_wait");
6492 tog_io.wait_for_ui = 0;
6495 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6496 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6497 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6498 free(id_str);
6499 return got_error_from_errno("asprintf");
6501 free(id_str);
6502 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6503 free(line);
6504 line = NULL;
6505 if (err)
6506 return err;
6507 waddwstr(view->window, wline);
6508 free(wline);
6509 wline = NULL;
6510 if (width < view->ncols - 1)
6511 waddch(view->window, '\n');
6513 s->eof = 0;
6514 view->maxx = 0;
6515 while (nprinted < view->nlines - 2) {
6516 linelen = getline(&line, &linesize, blame->f);
6517 if (linelen == -1) {
6518 if (feof(blame->f)) {
6519 s->eof = 1;
6520 break;
6522 free(line);
6523 return got_ferror(blame->f, GOT_ERR_IO);
6525 if (++lineno < s->first_displayed_line)
6526 continue;
6527 if (view->gline && !gotoline(view, &lineno, &nprinted))
6528 continue;
6530 /* Set view->maxx based on full line length. */
6531 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6532 if (err) {
6533 free(line);
6534 return err;
6536 free(wline);
6537 wline = NULL;
6538 view->maxx = MAX(view->maxx, width);
6540 if (nprinted == s->selected_line - 1)
6541 wstandout(view->window);
6543 if (blame->nlines > 0) {
6544 blame_line = &blame->lines[lineno - 1];
6545 if (blame_line->annotated && prev_id &&
6546 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6547 !(nprinted == s->selected_line - 1)) {
6548 waddstr(view->window, " ");
6549 } else if (blame_line->annotated) {
6550 char *id_str;
6551 err = got_object_id_str(&id_str,
6552 blame_line->id);
6553 if (err) {
6554 free(line);
6555 return err;
6557 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6558 if (tc)
6559 wattr_on(view->window,
6560 COLOR_PAIR(tc->colorpair), NULL);
6561 wprintw(view->window, "%.8s", id_str);
6562 if (tc)
6563 wattr_off(view->window,
6564 COLOR_PAIR(tc->colorpair), NULL);
6565 free(id_str);
6566 prev_id = blame_line->id;
6567 } else {
6568 waddstr(view->window, "........");
6569 prev_id = NULL;
6571 } else {
6572 waddstr(view->window, "........");
6573 prev_id = NULL;
6576 if (nprinted == s->selected_line - 1)
6577 wstandend(view->window);
6578 waddstr(view->window, " ");
6580 if (view->ncols <= 9) {
6581 width = 9;
6582 } else if (s->first_displayed_line + nprinted ==
6583 s->matched_line &&
6584 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6585 err = add_matched_line(&width, line, view->ncols - 9, 9,
6586 view->window, view->x, regmatch);
6587 if (err) {
6588 free(line);
6589 return err;
6591 width += 9;
6592 } else {
6593 int skip;
6594 err = format_line(&wline, &width, &skip, line,
6595 view->x, view->ncols - 9, 9, 1);
6596 if (err) {
6597 free(line);
6598 return err;
6600 waddwstr(view->window, &wline[skip]);
6601 width += 9;
6602 free(wline);
6603 wline = NULL;
6606 if (width <= view->ncols - 1)
6607 waddch(view->window, '\n');
6608 if (++nprinted == 1)
6609 s->first_displayed_line = lineno;
6611 free(line);
6612 s->last_displayed_line = lineno;
6614 view_border(view);
6616 return NULL;
6619 static const struct got_error *
6620 blame_cb(void *arg, int nlines, int lineno,
6621 struct got_commit_object *commit, struct got_object_id *id)
6623 const struct got_error *err = NULL;
6624 struct tog_blame_cb_args *a = arg;
6625 struct tog_blame_line *line;
6626 int errcode;
6628 if (nlines != a->nlines ||
6629 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6630 return got_error(GOT_ERR_RANGE);
6632 errcode = pthread_mutex_lock(&tog_mutex);
6633 if (errcode)
6634 return got_error_set_errno(errcode, "pthread_mutex_lock");
6636 if (*a->quit) { /* user has quit the blame view */
6637 err = got_error(GOT_ERR_ITER_COMPLETED);
6638 goto done;
6641 if (lineno == -1)
6642 goto done; /* no change in this commit */
6644 line = &a->lines[lineno - 1];
6645 if (line->annotated)
6646 goto done;
6648 line->id = got_object_id_dup(id);
6649 if (line->id == NULL) {
6650 err = got_error_from_errno("got_object_id_dup");
6651 goto done;
6653 line->annotated = 1;
6654 done:
6655 errcode = pthread_mutex_unlock(&tog_mutex);
6656 if (errcode)
6657 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6658 return err;
6661 static void *
6662 blame_thread(void *arg)
6664 const struct got_error *err, *close_err;
6665 struct tog_blame_thread_args *ta = arg;
6666 struct tog_blame_cb_args *a = ta->cb_args;
6667 int errcode, fd1 = -1, fd2 = -1;
6668 FILE *f1 = NULL, *f2 = NULL;
6670 fd1 = got_opentempfd();
6671 if (fd1 == -1)
6672 return (void *)got_error_from_errno("got_opentempfd");
6674 fd2 = got_opentempfd();
6675 if (fd2 == -1) {
6676 err = got_error_from_errno("got_opentempfd");
6677 goto done;
6680 f1 = got_opentemp();
6681 if (f1 == NULL) {
6682 err = (void *)got_error_from_errno("got_opentemp");
6683 goto done;
6685 f2 = got_opentemp();
6686 if (f2 == NULL) {
6687 err = (void *)got_error_from_errno("got_opentemp");
6688 goto done;
6691 err = block_signals_used_by_main_thread();
6692 if (err)
6693 goto done;
6695 err = got_blame(ta->path, a->commit_id, ta->repo,
6696 tog_diff_algo, blame_cb, ta->cb_args,
6697 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6698 if (err && err->code == GOT_ERR_CANCELLED)
6699 err = NULL;
6701 errcode = pthread_mutex_lock(&tog_mutex);
6702 if (errcode) {
6703 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6704 goto done;
6707 close_err = got_repo_close(ta->repo);
6708 if (err == NULL)
6709 err = close_err;
6710 ta->repo = NULL;
6711 *ta->complete = 1;
6713 if (tog_io.wait_for_ui) {
6714 errcode = pthread_cond_signal(&ta->blame_complete);
6715 if (errcode && err == NULL)
6716 err = got_error_set_errno(errcode,
6717 "pthread_cond_signal");
6720 errcode = pthread_mutex_unlock(&tog_mutex);
6721 if (errcode && err == NULL)
6722 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6724 done:
6725 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6726 err = got_error_from_errno("close");
6727 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6728 err = got_error_from_errno("close");
6729 if (f1 && fclose(f1) == EOF && err == NULL)
6730 err = got_error_from_errno("fclose");
6731 if (f2 && fclose(f2) == EOF && err == NULL)
6732 err = got_error_from_errno("fclose");
6734 return (void *)err;
6737 static struct got_object_id *
6738 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6739 int first_displayed_line, int selected_line)
6741 struct tog_blame_line *line;
6743 if (nlines <= 0)
6744 return NULL;
6746 line = &lines[first_displayed_line - 1 + selected_line - 1];
6747 if (!line->annotated)
6748 return NULL;
6750 return line->id;
6753 static struct got_object_id *
6754 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6755 int lineno)
6757 struct tog_blame_line *line;
6759 if (nlines <= 0 || lineno >= nlines)
6760 return NULL;
6762 line = &lines[lineno - 1];
6763 if (!line->annotated)
6764 return NULL;
6766 return line->id;
6769 static const struct got_error *
6770 stop_blame(struct tog_blame *blame)
6772 const struct got_error *err = NULL;
6773 int i;
6775 if (blame->thread) {
6776 int errcode;
6777 errcode = pthread_mutex_unlock(&tog_mutex);
6778 if (errcode)
6779 return got_error_set_errno(errcode,
6780 "pthread_mutex_unlock");
6781 errcode = pthread_join(blame->thread, (void **)&err);
6782 if (errcode)
6783 return got_error_set_errno(errcode, "pthread_join");
6784 errcode = pthread_mutex_lock(&tog_mutex);
6785 if (errcode)
6786 return got_error_set_errno(errcode,
6787 "pthread_mutex_lock");
6788 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6789 err = NULL;
6790 blame->thread = NULL;
6792 if (blame->thread_args.repo) {
6793 const struct got_error *close_err;
6794 close_err = got_repo_close(blame->thread_args.repo);
6795 if (err == NULL)
6796 err = close_err;
6797 blame->thread_args.repo = NULL;
6799 if (blame->f) {
6800 if (fclose(blame->f) == EOF && err == NULL)
6801 err = got_error_from_errno("fclose");
6802 blame->f = NULL;
6804 if (blame->lines) {
6805 for (i = 0; i < blame->nlines; i++)
6806 free(blame->lines[i].id);
6807 free(blame->lines);
6808 blame->lines = NULL;
6810 free(blame->cb_args.commit_id);
6811 blame->cb_args.commit_id = NULL;
6812 if (blame->pack_fds) {
6813 const struct got_error *pack_err =
6814 got_repo_pack_fds_close(blame->pack_fds);
6815 if (err == NULL)
6816 err = pack_err;
6817 blame->pack_fds = NULL;
6819 free(blame->line_offsets);
6820 blame->line_offsets = NULL;
6821 return err;
6824 static const struct got_error *
6825 cancel_blame_view(void *arg)
6827 const struct got_error *err = NULL;
6828 int *done = arg;
6829 int errcode;
6831 errcode = pthread_mutex_lock(&tog_mutex);
6832 if (errcode)
6833 return got_error_set_errno(errcode,
6834 "pthread_mutex_unlock");
6836 if (*done)
6837 err = got_error(GOT_ERR_CANCELLED);
6839 errcode = pthread_mutex_unlock(&tog_mutex);
6840 if (errcode)
6841 return got_error_set_errno(errcode,
6842 "pthread_mutex_lock");
6844 return err;
6847 static const struct got_error *
6848 run_blame(struct tog_view *view)
6850 struct tog_blame_view_state *s = &view->state.blame;
6851 struct tog_blame *blame = &s->blame;
6852 const struct got_error *err = NULL;
6853 struct got_commit_object *commit = NULL;
6854 struct got_blob_object *blob = NULL;
6855 struct got_repository *thread_repo = NULL;
6856 struct got_object_id *obj_id = NULL;
6857 int obj_type, fd = -1;
6858 int *pack_fds = NULL;
6860 err = got_object_open_as_commit(&commit, s->repo,
6861 &s->blamed_commit->id);
6862 if (err)
6863 return err;
6865 fd = got_opentempfd();
6866 if (fd == -1) {
6867 err = got_error_from_errno("got_opentempfd");
6868 goto done;
6871 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6872 if (err)
6873 goto done;
6875 err = got_object_get_type(&obj_type, s->repo, obj_id);
6876 if (err)
6877 goto done;
6879 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6880 err = got_error(GOT_ERR_OBJ_TYPE);
6881 goto done;
6884 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6885 if (err)
6886 goto done;
6887 blame->f = got_opentemp();
6888 if (blame->f == NULL) {
6889 err = got_error_from_errno("got_opentemp");
6890 goto done;
6892 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6893 &blame->line_offsets, blame->f, blob);
6894 if (err)
6895 goto done;
6896 if (blame->nlines == 0) {
6897 s->blame_complete = 1;
6898 goto done;
6901 /* Don't include \n at EOF in the blame line count. */
6902 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6903 blame->nlines--;
6905 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6906 if (blame->lines == NULL) {
6907 err = got_error_from_errno("calloc");
6908 goto done;
6911 err = got_repo_pack_fds_open(&pack_fds);
6912 if (err)
6913 goto done;
6914 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6915 pack_fds);
6916 if (err)
6917 goto done;
6919 blame->pack_fds = pack_fds;
6920 blame->cb_args.view = view;
6921 blame->cb_args.lines = blame->lines;
6922 blame->cb_args.nlines = blame->nlines;
6923 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6924 if (blame->cb_args.commit_id == NULL) {
6925 err = got_error_from_errno("got_object_id_dup");
6926 goto done;
6928 blame->cb_args.quit = &s->done;
6930 blame->thread_args.path = s->path;
6931 blame->thread_args.repo = thread_repo;
6932 blame->thread_args.cb_args = &blame->cb_args;
6933 blame->thread_args.complete = &s->blame_complete;
6934 blame->thread_args.cancel_cb = cancel_blame_view;
6935 blame->thread_args.cancel_arg = &s->done;
6936 s->blame_complete = 0;
6938 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6939 s->first_displayed_line = 1;
6940 s->last_displayed_line = view->nlines;
6941 s->selected_line = 1;
6943 s->matched_line = 0;
6945 done:
6946 if (commit)
6947 got_object_commit_close(commit);
6948 if (fd != -1 && close(fd) == -1 && err == NULL)
6949 err = got_error_from_errno("close");
6950 if (blob)
6951 got_object_blob_close(blob);
6952 free(obj_id);
6953 if (err)
6954 stop_blame(blame);
6955 return err;
6958 static const struct got_error *
6959 open_blame_view(struct tog_view *view, char *path,
6960 struct got_object_id *commit_id, struct got_repository *repo)
6962 const struct got_error *err = NULL;
6963 struct tog_blame_view_state *s = &view->state.blame;
6965 STAILQ_INIT(&s->blamed_commits);
6967 s->path = strdup(path);
6968 if (s->path == NULL)
6969 return got_error_from_errno("strdup");
6971 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6972 if (err) {
6973 free(s->path);
6974 return err;
6977 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6978 s->first_displayed_line = 1;
6979 s->last_displayed_line = view->nlines;
6980 s->selected_line = 1;
6981 s->blame_complete = 0;
6982 s->repo = repo;
6983 s->commit_id = commit_id;
6984 memset(&s->blame, 0, sizeof(s->blame));
6986 STAILQ_INIT(&s->colors);
6987 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6988 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6989 get_color_value("TOG_COLOR_COMMIT"));
6990 if (err)
6991 return err;
6994 view->show = show_blame_view;
6995 view->input = input_blame_view;
6996 view->reset = reset_blame_view;
6997 view->close = close_blame_view;
6998 view->search_start = search_start_blame_view;
6999 view->search_setup = search_setup_blame_view;
7000 view->search_next = search_next_view_match;
7002 if (using_mock_io) {
7003 struct tog_blame_thread_args *bta = &s->blame.thread_args;
7004 int rc;
7006 rc = pthread_cond_init(&bta->blame_complete, NULL);
7007 if (rc)
7008 return got_error_set_errno(rc, "pthread_cond_init");
7011 return run_blame(view);
7014 static const struct got_error *
7015 close_blame_view(struct tog_view *view)
7017 const struct got_error *err = NULL;
7018 struct tog_blame_view_state *s = &view->state.blame;
7020 if (s->blame.thread)
7021 err = stop_blame(&s->blame);
7023 while (!STAILQ_EMPTY(&s->blamed_commits)) {
7024 struct got_object_qid *blamed_commit;
7025 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
7026 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
7027 got_object_qid_free(blamed_commit);
7030 if (using_mock_io) {
7031 struct tog_blame_thread_args *bta = &s->blame.thread_args;
7032 int rc;
7034 rc = pthread_cond_destroy(&bta->blame_complete);
7035 if (rc && err == NULL)
7036 err = got_error_set_errno(rc, "pthread_cond_destroy");
7039 free(s->path);
7040 free_colors(&s->colors);
7041 return err;
7044 static const struct got_error *
7045 search_start_blame_view(struct tog_view *view)
7047 struct tog_blame_view_state *s = &view->state.blame;
7049 s->matched_line = 0;
7050 return NULL;
7053 static void
7054 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
7055 size_t *nlines, int **first, int **last, int **match, int **selected)
7057 struct tog_blame_view_state *s = &view->state.blame;
7059 *f = s->blame.f;
7060 *nlines = s->blame.nlines;
7061 *line_offsets = s->blame.line_offsets;
7062 *match = &s->matched_line;
7063 *first = &s->first_displayed_line;
7064 *last = &s->last_displayed_line;
7065 *selected = &s->selected_line;
7068 static const struct got_error *
7069 show_blame_view(struct tog_view *view)
7071 const struct got_error *err = NULL;
7072 struct tog_blame_view_state *s = &view->state.blame;
7073 int errcode;
7075 if (s->blame.thread == NULL && !s->blame_complete) {
7076 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
7077 &s->blame.thread_args);
7078 if (errcode)
7079 return got_error_set_errno(errcode, "pthread_create");
7081 if (!using_mock_io)
7082 halfdelay(1); /* fast refresh while annotating */
7085 if (s->blame_complete && !using_mock_io)
7086 halfdelay(10); /* disable fast refresh */
7088 err = draw_blame(view);
7090 view_border(view);
7091 return err;
7094 static const struct got_error *
7095 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
7096 struct got_repository *repo, struct got_object_id *id)
7098 struct tog_view *log_view;
7099 const struct got_error *err = NULL;
7101 *new_view = NULL;
7103 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7104 if (log_view == NULL)
7105 return got_error_from_errno("view_open");
7107 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0, NULL);
7108 if (err)
7109 view_close(log_view);
7110 else
7111 *new_view = log_view;
7113 return err;
7116 static const struct got_error *
7117 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
7119 const struct got_error *err = NULL, *thread_err = NULL;
7120 struct tog_view *diff_view;
7121 struct tog_blame_view_state *s = &view->state.blame;
7122 int eos, nscroll, begin_y = 0, begin_x = 0;
7124 eos = nscroll = view->nlines - 2;
7125 if (view_is_hsplit_top(view))
7126 --eos; /* border */
7128 switch (ch) {
7129 case '0':
7130 case '$':
7131 case KEY_RIGHT:
7132 case 'l':
7133 case KEY_LEFT:
7134 case 'h':
7135 horizontal_scroll_input(view, ch);
7136 break;
7137 case 'q':
7138 s->done = 1;
7139 break;
7140 case 'g':
7141 case KEY_HOME:
7142 s->selected_line = 1;
7143 s->first_displayed_line = 1;
7144 view->count = 0;
7145 break;
7146 case 'G':
7147 case KEY_END:
7148 if (s->blame.nlines < eos) {
7149 s->selected_line = s->blame.nlines;
7150 s->first_displayed_line = 1;
7151 } else {
7152 s->selected_line = eos;
7153 s->first_displayed_line = s->blame.nlines - (eos - 1);
7155 view->count = 0;
7156 break;
7157 case 'k':
7158 case KEY_UP:
7159 case CTRL('p'):
7160 if (s->selected_line > 1)
7161 s->selected_line--;
7162 else if (s->selected_line == 1 &&
7163 s->first_displayed_line > 1)
7164 s->first_displayed_line--;
7165 else
7166 view->count = 0;
7167 break;
7168 case CTRL('u'):
7169 case 'u':
7170 nscroll /= 2;
7171 /* FALL THROUGH */
7172 case KEY_PPAGE:
7173 case CTRL('b'):
7174 case 'b':
7175 if (s->first_displayed_line == 1) {
7176 if (view->count > 1)
7177 nscroll += nscroll;
7178 s->selected_line = MAX(1, s->selected_line - nscroll);
7179 view->count = 0;
7180 break;
7182 if (s->first_displayed_line > nscroll)
7183 s->first_displayed_line -= nscroll;
7184 else
7185 s->first_displayed_line = 1;
7186 break;
7187 case 'j':
7188 case KEY_DOWN:
7189 case CTRL('n'):
7190 if (s->selected_line < eos && s->first_displayed_line +
7191 s->selected_line <= s->blame.nlines)
7192 s->selected_line++;
7193 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
7194 s->first_displayed_line++;
7195 else
7196 view->count = 0;
7197 break;
7198 case 'c':
7199 case 'p': {
7200 struct got_object_id *id = NULL;
7202 view->count = 0;
7203 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
7204 s->first_displayed_line, s->selected_line);
7205 if (id == NULL)
7206 break;
7207 if (ch == 'p') {
7208 struct got_commit_object *commit, *pcommit;
7209 struct got_object_qid *pid;
7210 struct got_object_id *blob_id = NULL;
7211 int obj_type;
7212 err = got_object_open_as_commit(&commit,
7213 s->repo, id);
7214 if (err)
7215 break;
7216 pid = STAILQ_FIRST(
7217 got_object_commit_get_parent_ids(commit));
7218 if (pid == NULL) {
7219 got_object_commit_close(commit);
7220 break;
7222 /* Check if path history ends here. */
7223 err = got_object_open_as_commit(&pcommit,
7224 s->repo, &pid->id);
7225 if (err)
7226 break;
7227 err = got_object_id_by_path(&blob_id, s->repo,
7228 pcommit, s->path);
7229 got_object_commit_close(pcommit);
7230 if (err) {
7231 if (err->code == GOT_ERR_NO_TREE_ENTRY)
7232 err = NULL;
7233 got_object_commit_close(commit);
7234 break;
7236 err = got_object_get_type(&obj_type, s->repo,
7237 blob_id);
7238 free(blob_id);
7239 /* Can't blame non-blob type objects. */
7240 if (obj_type != GOT_OBJ_TYPE_BLOB) {
7241 got_object_commit_close(commit);
7242 break;
7244 err = got_object_qid_alloc(&s->blamed_commit,
7245 &pid->id);
7246 got_object_commit_close(commit);
7247 } else {
7248 if (got_object_id_cmp(id,
7249 &s->blamed_commit->id) == 0)
7250 break;
7251 err = got_object_qid_alloc(&s->blamed_commit,
7252 id);
7254 if (err)
7255 break;
7256 s->done = 1;
7257 thread_err = stop_blame(&s->blame);
7258 s->done = 0;
7259 if (thread_err)
7260 break;
7261 STAILQ_INSERT_HEAD(&s->blamed_commits,
7262 s->blamed_commit, entry);
7263 err = run_blame(view);
7264 if (err)
7265 break;
7266 break;
7268 case 'C': {
7269 struct got_object_qid *first;
7271 view->count = 0;
7272 first = STAILQ_FIRST(&s->blamed_commits);
7273 if (!got_object_id_cmp(&first->id, s->commit_id))
7274 break;
7275 s->done = 1;
7276 thread_err = stop_blame(&s->blame);
7277 s->done = 0;
7278 if (thread_err)
7279 break;
7280 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
7281 got_object_qid_free(s->blamed_commit);
7282 s->blamed_commit =
7283 STAILQ_FIRST(&s->blamed_commits);
7284 err = run_blame(view);
7285 if (err)
7286 break;
7287 break;
7289 case 'L':
7290 view->count = 0;
7291 s->id_to_log = get_selected_commit_id(s->blame.lines,
7292 s->blame.nlines, s->first_displayed_line, s->selected_line);
7293 if (s->id_to_log)
7294 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7295 break;
7296 case KEY_ENTER:
7297 case '\r': {
7298 struct got_object_id *id = NULL;
7299 struct got_object_qid *pid;
7300 struct got_commit_object *commit = NULL;
7302 view->count = 0;
7303 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
7304 s->first_displayed_line, s->selected_line);
7305 if (id == NULL)
7306 break;
7307 err = got_object_open_as_commit(&commit, s->repo, id);
7308 if (err)
7309 break;
7310 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7311 if (*new_view) {
7312 /* traversed from diff view, release diff resources */
7313 err = close_diff_view(*new_view);
7314 if (err)
7315 break;
7316 diff_view = *new_view;
7317 } else {
7318 if (view_is_parent_view(view))
7319 view_get_split(view, &begin_y, &begin_x);
7321 diff_view = view_open(0, 0, begin_y, begin_x,
7322 TOG_VIEW_DIFF);
7323 if (diff_view == NULL) {
7324 got_object_commit_close(commit);
7325 err = got_error_from_errno("view_open");
7326 break;
7329 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
7330 id, NULL, NULL, 3, 0, 0, view, s->repo);
7331 got_object_commit_close(commit);
7332 if (err)
7333 break;
7334 s->last_diffed_line = s->first_displayed_line - 1 +
7335 s->selected_line;
7336 if (*new_view)
7337 break; /* still open from active diff view */
7338 if (view_is_parent_view(view) &&
7339 view->mode == TOG_VIEW_SPLIT_HRZN) {
7340 err = view_init_hsplit(view, begin_y);
7341 if (err)
7342 break;
7345 view->focussed = 0;
7346 diff_view->focussed = 1;
7347 diff_view->mode = view->mode;
7348 diff_view->nlines = view->lines - begin_y;
7349 if (view_is_parent_view(view)) {
7350 view_transfer_size(diff_view, view);
7351 err = view_close_child(view);
7352 if (err)
7353 break;
7354 err = view_set_child(view, diff_view);
7355 if (err)
7356 break;
7357 view->focus_child = 1;
7358 } else
7359 *new_view = diff_view;
7360 if (err)
7361 break;
7362 break;
7364 case CTRL('d'):
7365 case 'd':
7366 nscroll /= 2;
7367 /* FALL THROUGH */
7368 case KEY_NPAGE:
7369 case CTRL('f'):
7370 case 'f':
7371 case ' ':
7372 if (s->last_displayed_line >= s->blame.nlines &&
7373 s->selected_line >= MIN(s->blame.nlines,
7374 view->nlines - 2)) {
7375 view->count = 0;
7376 break;
7378 if (s->last_displayed_line >= s->blame.nlines &&
7379 s->selected_line < view->nlines - 2) {
7380 s->selected_line +=
7381 MIN(nscroll, s->last_displayed_line -
7382 s->first_displayed_line - s->selected_line + 1);
7384 if (s->last_displayed_line + nscroll <= s->blame.nlines)
7385 s->first_displayed_line += nscroll;
7386 else
7387 s->first_displayed_line =
7388 s->blame.nlines - (view->nlines - 3);
7389 break;
7390 case KEY_RESIZE:
7391 if (s->selected_line > view->nlines - 2) {
7392 s->selected_line = MIN(s->blame.nlines,
7393 view->nlines - 2);
7395 break;
7396 default:
7397 view->count = 0;
7398 break;
7400 return thread_err ? thread_err : err;
7403 static const struct got_error *
7404 reset_blame_view(struct tog_view *view)
7406 const struct got_error *err;
7407 struct tog_blame_view_state *s = &view->state.blame;
7409 view->count = 0;
7410 s->done = 1;
7411 err = stop_blame(&s->blame);
7412 s->done = 0;
7413 if (err)
7414 return err;
7415 return run_blame(view);
7418 static const struct got_error *
7419 cmd_blame(int argc, char *argv[])
7421 const struct got_error *error;
7422 struct got_repository *repo = NULL;
7423 struct got_worktree *worktree = NULL;
7424 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7425 char *link_target = NULL;
7426 struct got_object_id *commit_id = NULL;
7427 struct got_commit_object *commit = NULL;
7428 char *keyword_idstr = NULL, *commit_id_str = NULL;
7429 int ch;
7430 struct tog_view *view = NULL;
7431 int *pack_fds = NULL;
7433 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7434 switch (ch) {
7435 case 'c':
7436 commit_id_str = optarg;
7437 break;
7438 case 'r':
7439 repo_path = realpath(optarg, NULL);
7440 if (repo_path == NULL)
7441 return got_error_from_errno2("realpath",
7442 optarg);
7443 break;
7444 default:
7445 usage_blame();
7446 /* NOTREACHED */
7450 argc -= optind;
7451 argv += optind;
7453 if (argc != 1)
7454 usage_blame();
7456 error = got_repo_pack_fds_open(&pack_fds);
7457 if (error != NULL)
7458 goto done;
7460 if (repo_path == NULL) {
7461 cwd = getcwd(NULL, 0);
7462 if (cwd == NULL)
7463 return got_error_from_errno("getcwd");
7464 error = got_worktree_open(&worktree, cwd, NULL);
7465 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7466 goto done;
7467 if (worktree)
7468 repo_path =
7469 strdup(got_worktree_get_repo_path(worktree));
7470 else
7471 repo_path = strdup(cwd);
7472 if (repo_path == NULL) {
7473 error = got_error_from_errno("strdup");
7474 goto done;
7478 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7479 if (error != NULL)
7480 goto done;
7482 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7483 worktree);
7484 if (error)
7485 goto done;
7487 init_curses();
7489 error = apply_unveil(got_repo_get_path(repo), NULL);
7490 if (error)
7491 goto done;
7493 error = tog_load_refs(repo, 0);
7494 if (error)
7495 goto done;
7497 if (commit_id_str == NULL) {
7498 struct got_reference *head_ref;
7499 error = got_ref_open(&head_ref, repo, worktree ?
7500 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7501 if (error != NULL)
7502 goto done;
7503 error = got_ref_resolve(&commit_id, repo, head_ref);
7504 got_ref_close(head_ref);
7505 } else {
7506 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
7507 repo, worktree);
7508 if (error != NULL)
7509 goto done;
7510 if (keyword_idstr != NULL)
7511 commit_id_str = keyword_idstr;
7513 error = got_repo_match_object_id(&commit_id, NULL,
7514 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7516 if (error != NULL)
7517 goto done;
7519 error = got_object_open_as_commit(&commit, repo, commit_id);
7520 if (error)
7521 goto done;
7523 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7524 commit, repo);
7525 if (error)
7526 goto done;
7528 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7529 if (view == NULL) {
7530 error = got_error_from_errno("view_open");
7531 goto done;
7533 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7534 commit_id, repo);
7535 if (error != NULL) {
7536 if (view->close == NULL)
7537 close_blame_view(view);
7538 view_close(view);
7539 goto done;
7542 if (worktree) {
7543 error = set_tog_base_commit(repo, worktree);
7544 if (error != NULL)
7545 goto done;
7547 /* Release work tree lock. */
7548 got_worktree_close(worktree);
7549 worktree = NULL;
7552 error = view_loop(view);
7554 done:
7555 free(tog_base_commit.id);
7556 free(repo_path);
7557 free(in_repo_path);
7558 free(link_target);
7559 free(cwd);
7560 free(commit_id);
7561 free(keyword_idstr);
7562 if (commit)
7563 got_object_commit_close(commit);
7564 if (worktree)
7565 got_worktree_close(worktree);
7566 if (repo) {
7567 const struct got_error *close_err = got_repo_close(repo);
7568 if (error == NULL)
7569 error = close_err;
7571 if (pack_fds) {
7572 const struct got_error *pack_err =
7573 got_repo_pack_fds_close(pack_fds);
7574 if (error == NULL)
7575 error = pack_err;
7577 tog_free_refs();
7578 return error;
7581 static const struct got_error *
7582 draw_tree_entries(struct tog_view *view, const char *parent_path)
7584 struct tog_tree_view_state *s = &view->state.tree;
7585 const struct got_error *err = NULL;
7586 struct got_tree_entry *te;
7587 wchar_t *wline;
7588 char *index = NULL;
7589 struct tog_color *tc;
7590 int width, n, nentries, scrollx, i = 1;
7591 int limit = view->nlines;
7593 s->ndisplayed = 0;
7594 if (view_is_hsplit_top(view))
7595 --limit; /* border */
7597 werase(view->window);
7599 if (limit == 0)
7600 return NULL;
7602 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7603 0, 0);
7604 if (err)
7605 return err;
7606 if (view_needs_focus_indication(view))
7607 wstandout(view->window);
7608 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7609 if (tc)
7610 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7611 waddwstr(view->window, wline);
7612 free(wline);
7613 wline = NULL;
7614 while (width++ < view->ncols)
7615 waddch(view->window, ' ');
7616 if (tc)
7617 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7618 if (view_needs_focus_indication(view))
7619 wstandend(view->window);
7620 if (--limit <= 0)
7621 return NULL;
7623 i += s->selected;
7624 if (s->first_displayed_entry) {
7625 i += got_tree_entry_get_index(s->first_displayed_entry);
7626 if (s->tree != s->root)
7627 ++i; /* account for ".." entry */
7629 nentries = got_object_tree_get_nentries(s->tree);
7630 if (asprintf(&index, "[%d/%d] %s",
7631 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7632 return got_error_from_errno("asprintf");
7633 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7634 free(index);
7635 if (err)
7636 return err;
7637 waddwstr(view->window, wline);
7638 free(wline);
7639 wline = NULL;
7640 if (width < view->ncols - 1)
7641 waddch(view->window, '\n');
7642 if (--limit <= 0)
7643 return NULL;
7644 waddch(view->window, '\n');
7645 if (--limit <= 0)
7646 return NULL;
7648 if (s->first_displayed_entry == NULL) {
7649 te = got_object_tree_get_first_entry(s->tree);
7650 if (s->selected == 0) {
7651 if (view->focussed)
7652 wstandout(view->window);
7653 s->selected_entry = NULL;
7655 waddstr(view->window, " ..\n"); /* parent directory */
7656 if (s->selected == 0 && view->focussed)
7657 wstandend(view->window);
7658 s->ndisplayed++;
7659 if (--limit <= 0)
7660 return NULL;
7661 n = 1;
7662 } else {
7663 n = 0;
7664 te = s->first_displayed_entry;
7667 view->maxx = 0;
7668 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7669 char *line = NULL, *id_str = NULL, *link_target = NULL;
7670 const char *modestr = "";
7671 mode_t mode;
7673 te = got_object_tree_get_entry(s->tree, i);
7674 mode = got_tree_entry_get_mode(te);
7676 if (s->show_ids) {
7677 err = got_object_id_str(&id_str,
7678 got_tree_entry_get_id(te));
7679 if (err)
7680 return got_error_from_errno(
7681 "got_object_id_str");
7683 if (got_object_tree_entry_is_submodule(te))
7684 modestr = "$";
7685 else if (S_ISLNK(mode)) {
7686 int i;
7688 err = got_tree_entry_get_symlink_target(&link_target,
7689 te, s->repo);
7690 if (err) {
7691 free(id_str);
7692 return err;
7694 for (i = 0; link_target[i] != '\0'; i++) {
7695 if (!isprint((unsigned char)link_target[i]))
7696 link_target[i] = '?';
7698 modestr = "@";
7700 else if (S_ISDIR(mode))
7701 modestr = "/";
7702 else if (mode & S_IXUSR)
7703 modestr = "*";
7704 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7705 got_tree_entry_get_name(te), modestr,
7706 link_target ? " -> ": "",
7707 link_target ? link_target : "") == -1) {
7708 free(id_str);
7709 free(link_target);
7710 return got_error_from_errno("asprintf");
7712 free(id_str);
7713 free(link_target);
7715 /* use full line width to determine view->maxx */
7716 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7717 if (err) {
7718 free(line);
7719 break;
7721 view->maxx = MAX(view->maxx, width);
7722 free(wline);
7723 wline = NULL;
7725 err = format_line(&wline, &width, &scrollx, line, view->x,
7726 view->ncols, 0, 0);
7727 if (err) {
7728 free(line);
7729 break;
7731 if (n == s->selected) {
7732 if (view->focussed)
7733 wstandout(view->window);
7734 s->selected_entry = te;
7736 tc = match_color(&s->colors, line);
7737 if (tc)
7738 wattr_on(view->window,
7739 COLOR_PAIR(tc->colorpair), NULL);
7740 waddwstr(view->window, &wline[scrollx]);
7741 if (tc)
7742 wattr_off(view->window,
7743 COLOR_PAIR(tc->colorpair), NULL);
7744 if (width < view->ncols)
7745 waddch(view->window, '\n');
7746 if (n == s->selected && view->focussed)
7747 wstandend(view->window);
7748 free(line);
7749 free(wline);
7750 wline = NULL;
7751 n++;
7752 s->ndisplayed++;
7753 s->last_displayed_entry = te;
7754 if (--limit <= 0)
7755 break;
7758 return err;
7761 static void
7762 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7764 struct got_tree_entry *te;
7765 int isroot = s->tree == s->root;
7766 int i = 0;
7768 if (s->first_displayed_entry == NULL)
7769 return;
7771 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7772 while (i++ < maxscroll) {
7773 if (te == NULL) {
7774 if (!isroot)
7775 s->first_displayed_entry = NULL;
7776 break;
7778 s->first_displayed_entry = te;
7779 te = got_tree_entry_get_prev(s->tree, te);
7783 static const struct got_error *
7784 tree_scroll_down(struct tog_view *view, int maxscroll)
7786 struct tog_tree_view_state *s = &view->state.tree;
7787 struct got_tree_entry *next, *last;
7788 int n = 0;
7790 if (s->first_displayed_entry)
7791 next = got_tree_entry_get_next(s->tree,
7792 s->first_displayed_entry);
7793 else
7794 next = got_object_tree_get_first_entry(s->tree);
7796 last = s->last_displayed_entry;
7797 while (next && n++ < maxscroll) {
7798 if (last) {
7799 s->last_displayed_entry = last;
7800 last = got_tree_entry_get_next(s->tree, last);
7802 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7803 s->first_displayed_entry = next;
7804 next = got_tree_entry_get_next(s->tree, next);
7808 return NULL;
7811 static const struct got_error *
7812 tree_entry_path(char **path, struct tog_parent_trees *parents,
7813 struct got_tree_entry *te)
7815 const struct got_error *err = NULL;
7816 struct tog_parent_tree *pt;
7817 size_t len = 2; /* for leading slash and NUL */
7819 TAILQ_FOREACH(pt, parents, entry)
7820 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7821 + 1 /* slash */;
7822 if (te)
7823 len += strlen(got_tree_entry_get_name(te));
7825 *path = calloc(1, len);
7826 if (path == NULL)
7827 return got_error_from_errno("calloc");
7829 (*path)[0] = '/';
7830 pt = TAILQ_LAST(parents, tog_parent_trees);
7831 while (pt) {
7832 const char *name = got_tree_entry_get_name(pt->selected_entry);
7833 if (strlcat(*path, name, len) >= len) {
7834 err = got_error(GOT_ERR_NO_SPACE);
7835 goto done;
7837 if (strlcat(*path, "/", len) >= len) {
7838 err = got_error(GOT_ERR_NO_SPACE);
7839 goto done;
7841 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7843 if (te) {
7844 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7845 err = got_error(GOT_ERR_NO_SPACE);
7846 goto done;
7849 done:
7850 if (err) {
7851 free(*path);
7852 *path = NULL;
7854 return err;
7857 static const struct got_error *
7858 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7859 struct got_tree_entry *te, struct tog_parent_trees *parents,
7860 struct got_object_id *commit_id, struct got_repository *repo)
7862 const struct got_error *err = NULL;
7863 char *path;
7864 struct tog_view *blame_view;
7866 *new_view = NULL;
7868 err = tree_entry_path(&path, parents, te);
7869 if (err)
7870 return err;
7872 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7873 if (blame_view == NULL) {
7874 err = got_error_from_errno("view_open");
7875 goto done;
7878 err = open_blame_view(blame_view, path, commit_id, repo);
7879 if (err) {
7880 if (err->code == GOT_ERR_CANCELLED)
7881 err = NULL;
7882 view_close(blame_view);
7883 } else
7884 *new_view = blame_view;
7885 done:
7886 free(path);
7887 return err;
7890 static const struct got_error *
7891 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7892 struct tog_tree_view_state *s)
7894 struct tog_view *log_view;
7895 const struct got_error *err = NULL;
7896 char *path;
7898 *new_view = NULL;
7900 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7901 if (log_view == NULL)
7902 return got_error_from_errno("view_open");
7904 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7905 if (err)
7906 return err;
7908 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7909 path, 0, NULL);
7910 if (err)
7911 view_close(log_view);
7912 else
7913 *new_view = log_view;
7914 free(path);
7915 return err;
7918 static const struct got_error *
7919 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7920 const char *head_ref_name, struct got_repository *repo)
7922 const struct got_error *err = NULL;
7923 char *commit_id_str = NULL;
7924 struct tog_tree_view_state *s = &view->state.tree;
7925 struct got_commit_object *commit = NULL;
7927 TAILQ_INIT(&s->parents);
7928 STAILQ_INIT(&s->colors);
7930 s->commit_id = got_object_id_dup(commit_id);
7931 if (s->commit_id == NULL) {
7932 err = got_error_from_errno("got_object_id_dup");
7933 goto done;
7936 err = got_object_open_as_commit(&commit, repo, commit_id);
7937 if (err)
7938 goto done;
7941 * The root is opened here and will be closed when the view is closed.
7942 * Any visited subtrees and their path-wise parents are opened and
7943 * closed on demand.
7945 err = got_object_open_as_tree(&s->root, repo,
7946 got_object_commit_get_tree_id(commit));
7947 if (err)
7948 goto done;
7949 s->tree = s->root;
7951 err = got_object_id_str(&commit_id_str, commit_id);
7952 if (err != NULL)
7953 goto done;
7955 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7956 err = got_error_from_errno("asprintf");
7957 goto done;
7960 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7961 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7962 if (head_ref_name) {
7963 s->head_ref_name = strdup(head_ref_name);
7964 if (s->head_ref_name == NULL) {
7965 err = got_error_from_errno("strdup");
7966 goto done;
7969 s->repo = repo;
7971 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7972 err = add_color(&s->colors, "\\$$",
7973 TOG_COLOR_TREE_SUBMODULE,
7974 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7975 if (err)
7976 goto done;
7977 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7978 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7979 if (err)
7980 goto done;
7981 err = add_color(&s->colors, "/$",
7982 TOG_COLOR_TREE_DIRECTORY,
7983 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7984 if (err)
7985 goto done;
7987 err = add_color(&s->colors, "\\*$",
7988 TOG_COLOR_TREE_EXECUTABLE,
7989 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7990 if (err)
7991 goto done;
7993 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7994 get_color_value("TOG_COLOR_COMMIT"));
7995 if (err)
7996 goto done;
7999 view->show = show_tree_view;
8000 view->input = input_tree_view;
8001 view->close = close_tree_view;
8002 view->search_start = search_start_tree_view;
8003 view->search_next = search_next_tree_view;
8004 done:
8005 free(commit_id_str);
8006 if (commit)
8007 got_object_commit_close(commit);
8008 if (err) {
8009 if (view->close == NULL)
8010 close_tree_view(view);
8011 view_close(view);
8013 return err;
8016 static const struct got_error *
8017 close_tree_view(struct tog_view *view)
8019 struct tog_tree_view_state *s = &view->state.tree;
8021 free_colors(&s->colors);
8022 free(s->tree_label);
8023 s->tree_label = NULL;
8024 free(s->commit_id);
8025 s->commit_id = NULL;
8026 free(s->head_ref_name);
8027 s->head_ref_name = NULL;
8028 while (!TAILQ_EMPTY(&s->parents)) {
8029 struct tog_parent_tree *parent;
8030 parent = TAILQ_FIRST(&s->parents);
8031 TAILQ_REMOVE(&s->parents, parent, entry);
8032 if (parent->tree != s->root)
8033 got_object_tree_close(parent->tree);
8034 free(parent);
8037 if (s->tree != NULL && s->tree != s->root)
8038 got_object_tree_close(s->tree);
8039 if (s->root)
8040 got_object_tree_close(s->root);
8041 return NULL;
8044 static const struct got_error *
8045 search_start_tree_view(struct tog_view *view)
8047 struct tog_tree_view_state *s = &view->state.tree;
8049 s->matched_entry = NULL;
8050 return NULL;
8053 static int
8054 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
8056 regmatch_t regmatch;
8058 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
8059 0) == 0;
8062 static const struct got_error *
8063 search_next_tree_view(struct tog_view *view)
8065 struct tog_tree_view_state *s = &view->state.tree;
8066 struct got_tree_entry *te = NULL;
8068 if (!view->searching) {
8069 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8070 return NULL;
8073 if (s->matched_entry) {
8074 if (view->searching == TOG_SEARCH_FORWARD) {
8075 if (s->selected_entry)
8076 te = got_tree_entry_get_next(s->tree,
8077 s->selected_entry);
8078 else
8079 te = got_object_tree_get_first_entry(s->tr