newt.c 24.5 KB
Newer Older
1 2 3 4
#define _GNU_SOURCE
#include <stdio.h>
#undef _GNU_SOURCE

5
#include <slang.h>
6 7
#include <stdlib.h>
#include <newt.h>
8
#include <sys/ttydefaults.h>
9 10 11

#include "cache.h"
#include "hist.h"
12
#include "pstack.h"
13 14 15 16
#include "session.h"
#include "sort.h"
#include "symbol.h"

17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
struct ui_progress {
	newtComponent form, scale;
};

struct ui_progress *ui_progress__new(const char *title, u64 total)
{
	struct ui_progress *self = malloc(sizeof(*self));

	if (self != NULL) {
		int cols;
		newtGetScreenSize(&cols, NULL);
		cols -= 4;
		newtCenteredWindow(cols, 1, title);
		self->form  = newtForm(NULL, NULL, 0);
		if (self->form == NULL)
			goto out_free_self;
		self->scale = newtScale(0, 0, cols, total);
		if (self->scale == NULL)
			goto out_free_form;
36
		newtFormAddComponent(self->form, self->scale);
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
		newtRefresh();
	}

	return self;

out_free_form:
	newtFormDestroy(self->form);
out_free_self:
	free(self);
	return NULL;
}

void ui_progress__update(struct ui_progress *self, u64 curr)
{
	newtScaleSet(self->scale, curr);
	newtRefresh();
}

void ui_progress__delete(struct ui_progress *self)
{
	newtFormDestroy(self->form);
	newtPopWindow();
	free(self);
}

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
static void ui_helpline__pop(void)
{
	newtPopHelpLine();
}

static void ui_helpline__push(const char *msg)
{
	newtPushHelpLine(msg);
}

static void ui_helpline__vpush(const char *fmt, va_list ap)
{
	char *s;

	if (vasprintf(&s, fmt, ap) < 0)
		vfprintf(stderr, fmt, ap);
	else {
		ui_helpline__push(s);
		free(s);
	}
}

static void ui_helpline__fpush(const char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	ui_helpline__vpush(fmt, ap);
	va_end(ap);
}

static void ui_helpline__puts(const char *msg)
{
	ui_helpline__pop();
	ui_helpline__push(msg);
}

99 100 101 102 103 104 105 106 107 108 109 110
static char browser__last_msg[1024];

int browser__show_help(const char *format, va_list ap)
{
	int ret;
	static int backlog;

        ret = vsnprintf(browser__last_msg + backlog,
			sizeof(browser__last_msg) - backlog, format, ap);
	backlog += ret;

	if (browser__last_msg[backlog - 1] == '\n') {
111
		ui_helpline__puts(browser__last_msg);
112 113 114 115 116 117 118
		newtRefresh();
		backlog = 0;
	}

	return ret;
}

119 120
static void newt_form__set_exit_keys(newtComponent self)
{
121
	newtFormAddHotKey(self, NEWT_KEY_LEFT);
122 123 124 125 126 127 128 129 130 131 132 133 134 135
	newtFormAddHotKey(self, NEWT_KEY_ESCAPE);
	newtFormAddHotKey(self, 'Q');
	newtFormAddHotKey(self, 'q');
	newtFormAddHotKey(self, CTRL('c'));
}

static newtComponent newt_form__new(void)
{
	newtComponent self = newtForm(NULL, NULL, 0);
	if (self)
		newt_form__set_exit_keys(self);
	return self;
}

136
static int popup_menu(int argc, char * const argv[])
137 138 139 140 141 142 143 144 145 146 147 148
{
	struct newtExitStruct es;
	int i, rc = -1, max_len = 5;
	newtComponent listbox, form = newt_form__new();

	if (form == NULL)
		return -1;

	listbox = newtListbox(0, 0, argc, NEWT_FLAG_RETURNEXIT);
	if (listbox == NULL)
		goto out_destroy_form;

149
	newtFormAddComponent(form, listbox);
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173

	for (i = 0; i < argc; ++i) {
		int len = strlen(argv[i]);
		if (len > max_len)
			max_len = len;
		if (newtListboxAddEntry(listbox, argv[i], (void *)(long)i))
			goto out_destroy_form;
	}

	newtCenteredWindow(max_len, argc, NULL);
	newtFormRun(form, &es);
	rc = newtListboxGetCurrent(listbox) - NULL;
	if (es.reason == NEWT_EXIT_HOTKEY)
		rc = -1;
	newtPopWindow();
out_destroy_form:
	newtFormDestroy(form);
	return rc;
}

static bool dialog_yesno(const char *msg)
{
	/* newtWinChoice should really be accepting const char pointers... */
	char yes[] = "Yes", no[] = "No";
174
	return newtWinChoice(NULL, yes, no, (char *)msg) == 1;
175 176
}

177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
#define HE_COLORSET_TOP		50
#define HE_COLORSET_MEDIUM	51
#define HE_COLORSET_NORMAL	52
#define HE_COLORSET_SELECTED	53
#define HE_COLORSET_CODE	54

static int ui_browser__percent_color(double percent, bool current)
{
	if (current)
		return HE_COLORSET_SELECTED;
	if (percent >= MIN_RED)
		return HE_COLORSET_TOP;
	if (percent >= MIN_GREEN)
		return HE_COLORSET_MEDIUM;
	return HE_COLORSET_NORMAL;
}

struct ui_browser {
	newtComponent	form, sb;
	u64		index, first_visible_entry_idx;
	void		*first_visible_entry, *entries;
	u16		top, left, width, height;
	void		*priv;
	u32		nr_entries;
};

static void ui_browser__refresh_dimensions(struct ui_browser *self)
{
	int cols, rows;
	newtGetScreenSize(&cols, &rows);

	if (self->width > cols - 4)
		self->width = cols - 4;
	self->height = rows - 5;
	if (self->height > self->nr_entries)
		self->height = self->nr_entries;
	self->top  = (rows - self->height) / 2;
	self->left = (cols - self->width) / 2;
}

static void ui_browser__reset_index(struct ui_browser *self)
{
        self->index = self->first_visible_entry_idx = 0;
        self->first_visible_entry = NULL;
}

static int objdump_line__show(struct objdump_line *self, struct list_head *head,
			      int width, struct hist_entry *he, int len,
			      bool current_entry)
{
	if (self->offset != -1) {
		struct symbol *sym = he->ms.sym;
		unsigned int hits = 0;
		double percent = 0.0;
		int color;
		struct sym_priv *priv = symbol__priv(sym);
		struct sym_ext *sym_ext = priv->ext;
		struct sym_hist *h = priv->hist;
		s64 offset = self->offset;
		struct objdump_line *next = objdump__get_next_ip_line(head, self);

		while (offset < (s64)len &&
		       (next == NULL || offset < next->offset)) {
			if (sym_ext) {
				percent += sym_ext[offset].percent;
			} else
				hits += h->ip[offset];

			++offset;
		}

		if (sym_ext == NULL && h->sum)
			percent = 100.0 * hits / h->sum;

		color = ui_browser__percent_color(percent, current_entry);
		SLsmg_set_color(color);
		SLsmg_printf(" %7.2f ", percent);
		if (!current_entry)
			SLsmg_set_color(HE_COLORSET_CODE);
	} else {
		int color = ui_browser__percent_color(0, current_entry);
		SLsmg_set_color(color);
		SLsmg_write_nstring(" ", 9);
	}

	SLsmg_write_char(':');
	SLsmg_write_nstring(" ", 8);
	if (!*self->line)
		SLsmg_write_nstring(" ", width - 18);
	else
		SLsmg_write_nstring(self->line, width - 18);

	return 0;
}

static int ui_browser__refresh_entries(struct ui_browser *self)
{
	struct objdump_line *pos;
	struct list_head *head = self->entries;
	struct hist_entry *he = self->priv;
	int row = 0;
	int len = he->ms.sym->end - he->ms.sym->start;

	if (self->first_visible_entry == NULL || self->first_visible_entry == self->entries)
                self->first_visible_entry = head->next;

	pos = list_entry(self->first_visible_entry, struct objdump_line, node);

	list_for_each_entry_from(pos, head, node) {
		bool current_entry = (self->first_visible_entry_idx + row) == self->index;
		SLsmg_gotorc(self->top + row, self->left);
		objdump_line__show(pos, head, self->width,
				   he, len, current_entry);
		if (++row == self->height)
			break;
	}

	SLsmg_set_color(HE_COLORSET_NORMAL);
	SLsmg_fill_region(self->top + row, self->left,
			  self->height - row, self->width, ' ');

	return 0;
}

static int ui_browser__run(struct ui_browser *self, const char *title,
			   struct newtExitStruct *es)
{
	if (self->form) {
		newtFormDestroy(self->form);
		newtPopWindow();
	}

	ui_browser__refresh_dimensions(self);
	newtCenteredWindow(self->width + 2, self->height, title);
	self->form = newt_form__new();
	if (self->form == NULL)
		return -1;

	self->sb = newtVerticalScrollbar(self->width + 1, 0, self->height,
					 HE_COLORSET_NORMAL,
					 HE_COLORSET_SELECTED);
	if (self->sb == NULL)
		return -1;

	newtFormAddHotKey(self->form, NEWT_KEY_UP);
	newtFormAddHotKey(self->form, NEWT_KEY_DOWN);
	newtFormAddHotKey(self->form, NEWT_KEY_PGUP);
	newtFormAddHotKey(self->form, NEWT_KEY_PGDN);
	newtFormAddHotKey(self->form, NEWT_KEY_HOME);
	newtFormAddHotKey(self->form, NEWT_KEY_END);

	if (ui_browser__refresh_entries(self) < 0)
		return -1;
	newtFormAddComponent(self->form, self->sb);

	while (1) {
		unsigned int offset;

		newtFormRun(self->form, es);

		if (es->reason != NEWT_EXIT_HOTKEY)
			break;
		switch (es->u.key) {
		case NEWT_KEY_DOWN:
			if (self->index == self->nr_entries - 1)
				break;
			++self->index;
			if (self->index == self->first_visible_entry_idx + self->height) {
				struct list_head *pos = self->first_visible_entry;
				++self->first_visible_entry_idx;
				self->first_visible_entry = pos->next;
			}
			break;
		case NEWT_KEY_UP:
			if (self->index == 0)
				break;
			--self->index;
			if (self->index < self->first_visible_entry_idx) {
				struct list_head *pos = self->first_visible_entry;
				--self->first_visible_entry_idx;
				self->first_visible_entry = pos->prev;
			}
			break;
		case NEWT_KEY_PGDN:
			if (self->first_visible_entry_idx + self->height > self->nr_entries - 1)
				break;

			offset = self->height;
			if (self->index + offset > self->nr_entries - 1)
				offset = self->nr_entries - 1 - self->index;
			self->index += offset;
			self->first_visible_entry_idx += offset;

			while (offset--) {
				struct list_head *pos = self->first_visible_entry;
				self->first_visible_entry = pos->next;
			}

			break;
		case NEWT_KEY_PGUP:
			if (self->first_visible_entry_idx == 0)
				break;

			if (self->first_visible_entry_idx < self->height)
				offset = self->first_visible_entry_idx;
			else
				offset = self->height;

			self->index -= offset;
			self->first_visible_entry_idx -= offset;

			while (offset--) {
				struct list_head *pos = self->first_visible_entry;
				self->first_visible_entry = pos->prev;
			}
			break;
		case NEWT_KEY_HOME:
			ui_browser__reset_index(self);
			break;
		case NEWT_KEY_END: {
			struct list_head *head = self->entries;
			offset = self->height - 1;

			if (offset > self->nr_entries)
				offset = self->nr_entries;

			self->index = self->first_visible_entry_idx = self->nr_entries - 1 - offset;
			self->first_visible_entry = head->prev;
			while (offset-- != 0) {
				struct list_head *pos = self->first_visible_entry;
				self->first_visible_entry = pos->prev;
			}
		}
			break;
		case NEWT_KEY_ESCAPE:
412
		case NEWT_KEY_LEFT:
413 414 415 416 417 418 419 420 421 422 423 424 425
		case CTRL('c'):
		case 'Q':
		case 'q':
			return 0;
		default:
			continue;
		}
		if (ui_browser__refresh_entries(self) < 0)
			return -1;
	}
	return 0;
}

426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
/*
 * When debugging newt problems it was useful to be able to "unroll"
 * the calls to newtCheckBoxTreeAdd{Array,Item}, so that we can generate
 * a source file with the sequence of calls to these methods, to then
 * tweak the arrays to get the intended results, so I'm keeping this code
 * here, may be useful again in the future.
 */
#undef NEWT_DEBUG

static void newt_checkbox_tree__add(newtComponent tree, const char *str,
				    void *priv, int *indexes)
{
#ifdef NEWT_DEBUG
	/* Print the newtCheckboxTreeAddArray to tinker with its index arrays */
	int i = 0, len = 40 - strlen(str);

	fprintf(stderr,
		"\tnewtCheckboxTreeAddItem(tree, %*.*s\"%s\", (void *)%p, 0, ",
		len, len, " ", str, priv);
	while (indexes[i] != NEWT_ARG_LAST) {
		if (indexes[i] != NEWT_ARG_APPEND)
			fprintf(stderr, " %d,", indexes[i]);
		else
			fprintf(stderr, " %s,", "NEWT_ARG_APPEND");
		++i;
	}
	fprintf(stderr, " %s", " NEWT_ARG_LAST);\n");
	fflush(stderr);
#endif
	newtCheckboxTreeAddArray(tree, str, priv, 0, indexes);
}

static char *callchain_list__sym_name(struct callchain_list *self,
				      char *bf, size_t bfsize)
{
461 462
	if (self->ms.sym)
		return self->ms.sym->name;
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513

	snprintf(bf, bfsize, "%#Lx", self->ip);
	return bf;
}

static void __callchain__append_graph_browser(struct callchain_node *self,
					      newtComponent tree, u64 total,
					      int *indexes, int depth)
{
	struct rb_node *node;
	u64 new_total, remaining;
	int idx = 0;

	if (callchain_param.mode == CHAIN_GRAPH_REL)
		new_total = self->children_hit;
	else
		new_total = total;

	remaining = new_total;
	node = rb_first(&self->rb_root);
	while (node) {
		struct callchain_node *child = rb_entry(node, struct callchain_node, rb_node);
		struct rb_node *next = rb_next(node);
		u64 cumul = cumul_hits(child);
		struct callchain_list *chain;
		int first = true, printed = 0;
		int chain_idx = -1;
		remaining -= cumul;

		indexes[depth] = NEWT_ARG_APPEND;
		indexes[depth + 1] = NEWT_ARG_LAST;

		list_for_each_entry(chain, &child->val, list) {
			char ipstr[BITS_PER_LONG / 4 + 1],
			     *alloc_str = NULL;
			const char *str = callchain_list__sym_name(chain, ipstr, sizeof(ipstr));

			if (first) {
				double percent = cumul * 100.0 / new_total;

				first = false;
				if (asprintf(&alloc_str, "%2.2f%% %s", percent, str) < 0)
					str = "Not enough memory!";
				else
					str = alloc_str;
			} else {
				indexes[depth] = idx;
				indexes[depth + 1] = NEWT_ARG_APPEND;
				indexes[depth + 2] = NEWT_ARG_LAST;
				++chain_idx;
			}
514
			newt_checkbox_tree__add(tree, str, &chain->ms, indexes);
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
			free(alloc_str);
			++printed;
		}

		indexes[depth] = idx;
		if (chain_idx != -1)
			indexes[depth + 1] = chain_idx;
		if (printed != 0)
			++idx;
		__callchain__append_graph_browser(child, tree, new_total, indexes,
						  depth + (chain_idx != -1 ? 2 : 1));
		node = next;
	}
}

static void callchain__append_graph_browser(struct callchain_node *self,
					    newtComponent tree, u64 total,
					    int *indexes, int parent_idx)
{
	struct callchain_list *chain;
	int i = 0;

	indexes[1] = NEWT_ARG_APPEND;
	indexes[2] = NEWT_ARG_LAST;

	list_for_each_entry(chain, &self->val, list) {
		char ipstr[BITS_PER_LONG / 4 + 1], *str;

		if (chain->ip >= PERF_CONTEXT_MAX)
			continue;

		if (!i++ && sort__first_dimension == SORT_SYM)
			continue;

		str = callchain_list__sym_name(chain, ipstr, sizeof(ipstr));
550
		newt_checkbox_tree__add(tree, str, &chain->ms, indexes);
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
	}

	indexes[1] = parent_idx;
	indexes[2] = NEWT_ARG_APPEND;
	indexes[3] = NEWT_ARG_LAST;
	__callchain__append_graph_browser(self, tree, total, indexes, 2);
}

static void hist_entry__append_callchain_browser(struct hist_entry *self,
						 newtComponent tree, u64 total, int parent_idx)
{
	struct rb_node *rb_node;
	int indexes[1024] = { [0] = parent_idx, };
	int idx = 0;
	struct callchain_node *chain;

	rb_node = rb_first(&self->sorted_chain);
	while (rb_node) {
		chain = rb_entry(rb_node, struct callchain_node, rb_node);
		switch (callchain_param.mode) {
		case CHAIN_FLAT:
			break;
		case CHAIN_GRAPH_ABS: /* falldown */
		case CHAIN_GRAPH_REL:
			callchain__append_graph_browser(chain, tree, total, indexes, idx++);
			break;
		case CHAIN_NONE:
		default:
			break;
		}
		rb_node = rb_next(rb_node);
	}
}

585
static size_t hist_entry__append_browser(struct hist_entry *self,
586
					 newtComponent tree, u64 total)
587
{
588 589
	char s[256];
	size_t ret;
590 591 592 593

	if (symbol_conf.exclude_other && !self->parent)
		return 0;

594 595
	ret = hist_entry__snprintf(self, s, sizeof(s), NULL,
				   false, 0, false, total);
596 597 598 599 600
	if (symbol_conf.use_callchain) {
		int indexes[2];

		indexes[0] = NEWT_ARG_APPEND;
		indexes[1] = NEWT_ARG_LAST;
601
		newt_checkbox_tree__add(tree, s, &self->ms, indexes);
602
	} else
603
		newtListboxAppendEntry(tree, s, &self->ms);
604

605
	return ret;
606 607
}

608
static void hist_entry__annotate_browser(struct hist_entry *self)
609
{
610
	struct ui_browser browser;
611
	struct newtExitStruct es;
612 613
	struct objdump_line *pos, *n;
	LIST_HEAD(head);
614

615
	if (self->ms.sym == NULL)
616 617
		return;

618
	if (hist_entry__annotate(self, &head) < 0)
619 620
		return;

621
	ui_helpline__push("Press <- or ESC to exit");
622

623 624 625 626 627 628 629 630
	memset(&browser, 0, sizeof(browser));
	browser.entries = &head;
	browser.priv = self;
	list_for_each_entry(pos, &head, node) {
		size_t line_len = strlen(pos->line);
		if (browser.width < line_len)
			browser.width = line_len;
		++browser.nr_entries;
631 632
	}

633 634 635
	browser.width += 18; /* Percentage */
	ui_browser__run(&browser, self->ms.sym->name, &es);
	newtFormDestroy(browser.form);
636
	newtPopWindow();
637 638 639 640
	list_for_each_entry_safe(pos, n, &head, node) {
		list_del(&pos->node);
		objdump_line__free(pos);
	}
641
	ui_helpline__pop();
642 643
}

644 645 646 647 648 649 650
static const void *newt__symbol_tree_get_current(newtComponent self)
{
	if (symbol_conf.use_callchain)
		return newtCheckboxTreeGetCurrent(self);
	return newtListboxGetCurrent(self);
}

651
static void hist_browser__selection(newtComponent self, void *data)
652
{
653
	const struct map_symbol **symbol_ptr = data;
654 655 656
	*symbol_ptr = newt__symbol_tree_get_current(self);
}

657 658 659 660 661 662 663 664 665
struct hist_browser {
	newtComponent		form, tree;
	const struct map_symbol *selection;
};

static struct hist_browser *hist_browser__new(void)
{
	struct hist_browser *self = malloc(sizeof(*self));

666 667
	if (self != NULL)
		self->form = NULL;
668 669 670 671 672 673 674 675 676 677 678

	return self;
}

static void hist_browser__delete(struct hist_browser *self)
{
	newtFormDestroy(self->form);
	newtPopWindow();
	free(self);
}

679 680
static int hist_browser__populate(struct hist_browser *self, struct hists *hists,
				  const char *title)
681
{
682 683
	int max_len = 0, idx, cols, rows;
	struct ui_progress *progress;
684
	struct rb_node *nd;
685
	u64 curr_hist = 0;
686
	char seq[] = ".", unit;
687
	char str[256];
688
	unsigned long nr_events = hists->stats.nr_events[PERF_RECORD_SAMPLE];
689 690 691 692 693 694

	if (self->form) {
		newtFormDestroy(self->form);
		newtPopWindow();
	}

695 696 697
	nr_events = convert_unit(nr_events, &unit);
	snprintf(str, sizeof(str), "Events: %lu%c                            ",
		 nr_events, unit);
698 699 700 701 702 703 704 705 706 707 708 709 710 711
	newtDrawRootText(0, 0, str);

	newtGetScreenSize(NULL, &rows);

	if (symbol_conf.use_callchain)
		self->tree = newtCheckboxTreeMulti(0, 0, rows - 5, seq,
						   NEWT_FLAG_SCROLL);
	else
		self->tree = newtListbox(0, 0, rows - 5,
					(NEWT_FLAG_SCROLL |
					 NEWT_FLAG_RETURNEXIT));

	newtComponentAddCallback(self->tree, hist_browser__selection,
				 &self->selection);
712

713 714
	progress = ui_progress__new("Adding entries to the browser...",
				    hists->nr_entries);
715 716
	if (progress == NULL)
		return -1;
717

718
	idx = 0;
719
	for (nd = rb_first(&hists->entries); nd; nd = rb_next(nd)) {
720
		struct hist_entry *h = rb_entry(nd, struct hist_entry, rb_node);
721 722 723 724 725
		int len;

		if (h->filtered)
			continue;

726
		len = hist_entry__append_browser(h, self->tree, hists->stats.total_period);
727 728
		if (len > max_len)
			max_len = len;
729
		if (symbol_conf.use_callchain)
730
			hist_entry__append_callchain_browser(h, self->tree,
731
							     hists->stats.total_period, idx++);
732 733 734
		++curr_hist;
		if (curr_hist % 5)
			ui_progress__update(progress, curr_hist);
735 736
	}

737 738
	ui_progress__delete(progress);

739 740
	newtGetScreenSize(&cols, &rows);

741 742 743 744
	if (max_len > cols)
		max_len = cols - 3;

	if (!symbol_conf.use_callchain)
745
		newtListboxSetWidth(self->tree, max_len);
746 747

	newtCenteredWindow(max_len + (symbol_conf.use_callchain ? 5 : 0),
748
			   rows - 5, title);
749
	self->form = newt_form__new();
750 751 752
	if (self->form == NULL)
		return -1;

753 754
	newtFormAddHotKey(self->form, 'A');
	newtFormAddHotKey(self->form, 'a');
755 756 757 758
	newtFormAddHotKey(self->form, 'D');
	newtFormAddHotKey(self->form, 'd');
	newtFormAddHotKey(self->form, 'T');
	newtFormAddHotKey(self->form, 't');
759 760 761 762 763 764 765
	newtFormAddHotKey(self->form, NEWT_KEY_RIGHT);
	newtFormAddComponents(self->form, self->tree, NULL);
	self->selection = newt__symbol_tree_get_current(self->tree);

	return 0;
}

766
static struct hist_entry *hist_browser__selected_entry(struct hist_browser *self)
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
{
	int *indexes;

	if (!symbol_conf.use_callchain)
		goto out;

	indexes = newtCheckboxTreeFindItem(self->tree, (void *)self->selection);
	if (indexes) {
		bool is_hist_entry = indexes[1] == NEWT_ARG_LAST;
		free(indexes);
		if (is_hist_entry)
			goto out;
	}
	return NULL;
out:
782 783 784 785 786 787 788
	return container_of(self->selection, struct hist_entry, ms);
}

static struct thread *hist_browser__selected_thread(struct hist_browser *self)
{
	struct hist_entry *he = hist_browser__selected_entry(self);
	return he ? he->thread : NULL;
789 790
}

791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
static int hist_browser__title(char *bf, size_t size, const char *input_name,
			       const struct dso *dso, const struct thread *thread)
{
	int printed = 0;

	if (thread)
		printed += snprintf(bf + printed, size - printed,
				    "Thread: %s(%d)",
				    (thread->comm_set ?  thread->comm : ""),
				    thread->pid);
	if (dso)
		printed += snprintf(bf + printed, size - printed,
				    "%sDSO: %s", thread ? " " : "",
				    dso->short_name);
	return printed ?: snprintf(bf, size, "Report: %s", input_name);
}

808
int hists__browse(struct hists *self, const char *helpline, const char *input_name)
809
{
810
	struct hist_browser *browser = hist_browser__new();
811
	struct pstack *fstack = pstack__new(2);
812 813
	const struct thread *thread_filter = NULL;
	const struct dso *dso_filter = NULL;
814
	struct newtExitStruct es;
815
	char msg[160];
816 817 818 819 820
	int err = -1;

	if (browser == NULL)
		return -1;

821 822 823 824
	fstack = pstack__new(2);
	if (fstack == NULL)
		goto out;

825
	ui_helpline__push(helpline);
826

827 828
	hist_browser__title(msg, sizeof(msg), input_name,
			    dso_filter, thread_filter);
829
	if (hist_browser__populate(browser, self, msg) < 0)
830
		goto out_free_stack;
831 832

	while (1) {
833
		const struct thread *thread;
834
		const struct dso *dso;
835 836
		char *options[16];
		int nr_options = 0, choice = 0, i,
837
		    annotate = -2, zoom_dso = -2, zoom_thread = -2;
838

839
		newtFormRun(browser->form, &es);
840 841 842 843

		thread = hist_browser__selected_thread(browser);
		dso = browser->selection->map ? browser->selection->map->dso : NULL;

844
		if (es.reason == NEWT_EXIT_HOTKEY) {
845 846
			switch (toupper(es.u.key)) {
			case 'A':
847
				goto do_annotate;
848 849 850 851 852 853
			case 'D':
				goto zoom_dso;
			case 'T':
				goto zoom_thread;
			default:;
			}
854 855 856 857
			if (toupper(es.u.key) == 'Q' ||
			    es.u.key == CTRL('c'))
				break;
			if (es.u.key == NEWT_KEY_ESCAPE) {
858 859 860 861 862
				if (dialog_yesno("Do you really want to exit?"))
					break;
				else
					continue;
			}
863 864 865 866 867 868 869 870 871 872 873 874 875

			if (es.u.key == NEWT_KEY_LEFT) {
				const void *top;

				if (pstack__empty(fstack))
					continue;
				top = pstack__pop(fstack);
				if (top == &dso_filter)
					goto zoom_out_dso;
				if (top == &thread_filter)
					goto zoom_out_thread;
				continue;
			}
876 877
		}

878 879 880 881 882
		if (browser->selection->sym != NULL &&
		    asprintf(&options[nr_options], "Annotate %s",
			     browser->selection->sym->name) > 0)
			annotate = nr_options++;

883 884
		if (thread != NULL &&
		    asprintf(&options[nr_options], "Zoom %s %s(%d) thread",
885 886 887
			     (thread_filter ? "out of" : "into"),
			     (thread->comm_set ? thread->comm : ""),
			     thread->pid) > 0)
888 889
			zoom_thread = nr_options++;

890 891 892 893 894 895
		if (dso != NULL &&
		    asprintf(&options[nr_options], "Zoom %s %s DSO",
			     (dso_filter ? "out of" : "into"),
			     (dso->kernel ? "the Kernel" : dso->short_name)) > 0)
			zoom_dso = nr_options++;

896
		options[nr_options++] = (char *)"Exit";
897 898

		choice = popup_menu(nr_options, options);
899 900 901 902

		for (i = 0; i < nr_options - 1; ++i)
			free(options[i]);

903
		if (choice == nr_options - 1)
904
			break;
905 906 907

		if (choice == -1)
			continue;
908

909
		if (choice == annotate) {
910
			struct hist_entry *he;
911
do_annotate:
912
			if (browser->selection->map->dso->origin == DSO__ORIG_KERNEL) {
913
				ui_helpline__puts("No vmlinux file found, can't "
914 915 916 917
						 "annotate with just a "
						 "kallsyms file");
				continue;
			}
918 919 920 921 922 923

			he = hist_browser__selected_entry(browser);
			if (he == NULL)
				continue;

			hist_entry__annotate_browser(he);
924
		} else if (choice == zoom_dso) {
925
zoom_dso:
926
			if (dso_filter) {
927 928
				pstack__remove(fstack, &dso_filter);
zoom_out_dso:
929
				ui_helpline__pop();
930 931
				dso_filter = NULL;
			} else {
932 933
				if (dso == NULL)
					continue;
934
				ui_helpline__fpush("To zoom out press <- or -> + \"Zoom out of %s DSO\"",
935
						   dso->kernel ? "the Kernel" : dso->short_name);
936
				dso_filter = dso;
937
				pstack__push(fstack, &dso_filter);
938
			}
939
			hists__filter_by_dso(self, dso_filter);
940 941
			hist_browser__title(msg, sizeof(msg), input_name,
					    dso_filter, thread_filter);
942
			if (hist_browser__populate(browser, self, msg) < 0)
943
				goto out;
944
		} else if (choice == zoom_thread) {
945
zoom_thread:
946
			if (thread_filter) {
947 948
				pstack__remove(fstack, &thread_filter);
zoom_out_thread:
949
				ui_helpline__pop();
950 951
				thread_filter = NULL;
			} else {
952
				ui_helpline__fpush("To zoom out press <- or -> + \"Zoom out of %s(%d) thread\"",
953 954
						   thread->comm_set ? thread->comm : "",
						   thread->pid);
955
				thread_filter = thread;
956
				pstack__push(fstack, &thread_filter);
957
			}
958
			hists__filter_by_thread(self, thread_filter);
959 960
			hist_browser__title(msg, sizeof(msg), input_name,
					    dso_filter, thread_filter);
961
			if (hist_browser__populate(browser, self, msg) < 0)
962
				goto out;
963
		}
964
	}
965
	err = 0;
966 967
out_free_stack:
	pstack__delete(fstack);
968 969 970
out:
	hist_browser__delete(browser);
	return err;
971 972
}

973 974 975 976 977 978 979 980 981 982 983 984 985 986
static struct newtPercentTreeColors {
	const char *topColorFg, *topColorBg;
	const char *mediumColorFg, *mediumColorBg;
	const char *normalColorFg, *normalColorBg;
	const char *selColorFg, *selColorBg;
	const char *codeColorFg, *codeColorBg;
} defaultPercentTreeColors = {
	"red",       "lightgray",
	"green",     "lightgray",
	"black",     "lightgray",
	"lightgray", "magenta",
	"blue",	     "lightgray",
};

987 988
void setup_browser(void)
{
989
	struct newtPercentTreeColors *c = &defaultPercentTreeColors;
990 991 992 993 994 995
	if (!isatty(1))
		return;

	use_browser = true;
	newtInit();
	newtCls();
996
	ui_helpline__puts(" ");
997 998 999 1000 1001
	SLtt_set_color(HE_COLORSET_TOP, NULL, c->topColorFg, c->topColorBg);
	SLtt_set_color(HE_COLORSET_MEDIUM, NULL, c->mediumColorFg, c->mediumColorBg);
	SLtt_set_color(HE_COLORSET_NORMAL, NULL, c->normalColorFg, c->normalColorBg);
	SLtt_set_color(HE_COLORSET_SELECTED, NULL, c->selColorFg, c->selColorBg);
	SLtt_set_color(HE_COLORSET_CODE, NULL, c->codeColorFg, c->codeColorBg);
1002 1003
}

1004
void exit_browser(bool wait_for_ok)
1005
{
1006 1007 1008 1009 1010
	if (use_browser) {
		if (wait_for_ok) {
			char title[] = "Fatal Error", ok[] = "Ok";
			newtWinMessage(title, ok, browser__last_msg);
		}
1011
		newtFinished();
1012
	}
1013
}