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

#include <stdlib.h>
#include <newt.h>
7
#include <sys/ttydefaults.h>
8 9 10 11 12 13 14

#include "cache.h"
#include "hist.h"
#include "session.h"
#include "sort.h"
#include "symbol.h"

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
static void newt_form__set_exit_keys(newtComponent self)
{
	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;
}

31 32 33 34 35 36 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 62 63 64 65 66 67 68 69 70 71
static int popup_menu(int argc, const char *argv[])
{
	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;

	newtFormAddComponents(form, listbox, NULL);

	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";
	return newtWinChoice(NULL, no, yes, (char *)msg) == 2;
}

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 99 100 101 102 103 104 105 106
/*
 * 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)
{
107 108
	if (self->ms.sym)
		return self->ms.sym->name;
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159

	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;
			}
160
			newt_checkbox_tree__add(tree, str, chain->ms.sym, indexes);
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
			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));
196
		newt_checkbox_tree__add(tree, str, chain->ms.sym, indexes);
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
	}

	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);
	}
}

/*
 * FIXME: get lib/string.c linked with perf somehow
 */
static char *skip_spaces(const char *str)
{
	while (isspace(*str))
		++str;
	return (char *)str;
}

static char *strim(char *s)
{
	size_t size;
	char *end;

	s = skip_spaces(s);
	size = strlen(s);
	if (!size)
		return s;

	end = s + size - 1;
	while (end >= s && isspace(*end))
		end--;
	*(end + 1) = '\0';

	return s;
}

259
static size_t hist_entry__append_browser(struct hist_entry *self,
260
					 newtComponent tree, u64 total)
261
{
262
	char bf[1024], *s;
263 264 265 266 267 268 269 270 271
	FILE *fp;

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

	fp = fmemopen(bf, sizeof(bf), "w");
	if (fp == NULL)
		return 0;

272
	hist_entry__fprintf(self, NULL, false, 0, fp, total);
273
	fclose(fp);
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289

	/*
	 * FIXME: We shouldn't need to trim, as the printing routines shouldn't
	 * add spaces it in the first place, the stdio output routines should
	 * call a __snprintf method instead of the current __print (that
	 * actually is a __fprintf) one, but get the raw string and _then_ add
	 * the newline, as this is a detail of stdio printing, not needed in
	 * other UIs, e.g. newt.
	 */
	s = strim(bf);

	if (symbol_conf.use_callchain) {
		int indexes[2];

		indexes[0] = NEWT_ARG_APPEND;
		indexes[1] = NEWT_ARG_LAST;
290
		newt_checkbox_tree__add(tree, s, self->ms.sym, indexes);
291
	} else
292
		newtListboxAppendEntry(tree, s, self->ms.sym);
293 294

	return strlen(s);
295 296
}

297
static void symbol__annotate_browser(const struct symbol *self)
298 299
{
	FILE *fp;
300
	int cols, rows;
301
	newtComponent form, tree;
302 303 304 305 306 307
	struct newtExitStruct es;
	char *str;
	size_t line_len, max_line_len = 0;
	size_t max_usable_width;
	char *line = NULL;

308
	if (self == NULL)
309 310
		return;

311
	if (asprintf(&str, "perf annotate %s 2>&1 | expand", self->name) < 0)
312 313 314 315 316 317 318
		return;

	fp = popen(str, "r");
	if (fp == NULL)
		goto out_free_str;

	newtPushHelpLine("Press ESC to exit");
319
	newtGetScreenSize(&cols, &rows);
320
	tree = newtListbox(0, 0, rows - 5, NEWT_FLAG_SCROLL);
321 322 323 324 325 326 327 328 329

	while (!feof(fp)) {
		if (getline(&line, &line_len, fp) < 0 || !line_len)
			break;
		while (line_len != 0 && isspace(line[line_len - 1]))
			line[--line_len] = '\0';

		if (line_len > max_line_len)
			max_line_len = line_len;
330
		newtListboxAppendEntry(tree, line, NULL);
331 332 333 334
	}
	fclose(fp);
	free(line);

335
	max_usable_width = cols - 22;
336 337 338
	if (max_line_len > max_usable_width)
		max_line_len = max_usable_width;

339
	newtListboxSetWidth(tree, max_line_len);
340

341
	newtCenteredWindow(max_line_len + 2, rows - 5, self->name);
342
	form = newt_form__new();
343
	newtFormAddComponents(form, tree, NULL);
344 345 346 347 348 349 350 351 352

	newtFormRun(form, &es);
	newtFormDestroy(form);
	newtPopWindow();
	newtPopHelpLine();
out_free_str:
	free(str);
}

353 354 355 356 357 358 359 360 361 362 363 364 365
static const void *newt__symbol_tree_get_current(newtComponent self)
{
	if (symbol_conf.use_callchain)
		return newtCheckboxTreeGetCurrent(self);
	return newtListboxGetCurrent(self);
}

static void perf_session__selection(newtComponent self, void *data)
{
	const struct symbol **symbol_ptr = data;
	*symbol_ptr = newt__symbol_tree_get_current(self);
}

366 367 368 369 370
void perf_session__browse_hists(struct rb_root *hists, u64 session_total,
				const char *helpline)
{
	struct sort_entry *se;
	struct rb_node *nd;
371
	char seq[] = ".";
372 373
	unsigned int width;
	char *col_width = symbol_conf.col_width_list_str;
374 375
	int rows, cols, idx;
	int max_len = 0;
376
	char str[1024];
377
	newtComponent form, tree;
378
	struct newtExitStruct es;
379
	const struct symbol *selection;
380 381 382 383 384

	snprintf(str, sizeof(str), "Samples: %Ld", session_total);
	newtDrawRootText(0, 0, str);
	newtPushHelpLine(helpline);

385
	newtGetScreenSize(&cols, &rows);
386

387 388 389 390 391 392
	if (symbol_conf.use_callchain)
		tree = newtCheckboxTreeMulti(0, 0, rows - 5, seq,
						NEWT_FLAG_SCROLL);
	else
		tree = newtListbox(0, 0, rows - 5, (NEWT_FLAG_SCROLL |
						       NEWT_FLAG_RETURNEXIT));
393

394 395
	newtComponentAddCallback(tree, perf_session__selection, &selection);

396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
	list_for_each_entry(se, &hist_entry__sort_list, list) {
		if (se->elide)
			continue;
		width = strlen(se->header);
		if (se->width) {
			if (symbol_conf.col_width_list_str) {
				if (col_width) {
					*se->width = atoi(col_width);
					col_width = strchr(col_width, ',');
					if (col_width)
						++col_width;
				}
			}
			*se->width = max(*se->width, width);
		}
	}

413
	idx = 0;
414 415
	for (nd = rb_first(hists); nd; nd = rb_next(nd)) {
		struct hist_entry *h = rb_entry(nd, struct hist_entry, rb_node);
416
		int len = hist_entry__append_browser(h, tree, session_total);
417 418
		if (len > max_len)
			max_len = len;
419 420 421 422 423
		if (symbol_conf.use_callchain) {
			hist_entry__append_callchain_browser(h, tree, session_total, idx++);
			if (idx > 3300)
				break;
		}
424 425
	}

426 427 428 429 430 431 432 433 434 435 436
	if (max_len > cols)
		max_len = cols - 3;

	if (!symbol_conf.use_callchain)
		newtListboxSetWidth(tree, max_len);

	newtCenteredWindow(max_len + (symbol_conf.use_callchain ? 5 : 0),
			   rows - 5, "Report");
	form = newt_form__new();
	newtFormAddHotKey(form, 'A');
	newtFormAddHotKey(form, 'a');
437
	newtFormAddHotKey(form, NEWT_KEY_RIGHT);
438
	newtFormAddComponents(form, tree, NULL);
439
	selection = newt__symbol_tree_get_current(tree);
440 441

	while (1) {
442 443 444
		char annotate[512];
		const char *options[2];
		int nr_options = 0, choice;
445 446

		newtFormRun(form, &es);
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
		if (es.reason == NEWT_EXIT_HOTKEY) {
			if (toupper(es.u.key) == 'A') {
				symbol__annotate_browser(selection);
				continue;
			}
			if (es.u.key == NEWT_KEY_ESCAPE ||
			    toupper(es.u.key) == 'Q' ||
			    es.u.key == CTRL('c')) {
				if (dialog_yesno("Do you really want to exit?"))
					break;
				else
					continue;
			}
		}

		if (selection != NULL) {
			snprintf(annotate, sizeof(annotate),
				 "Annotate %s", selection->name);
			options[nr_options++] = annotate;
		}

		options[nr_options++] = "Exit";
		choice = popup_menu(nr_options, options);
		if (choice == nr_options - 1)
471
			break;
472 473
		else if (selection != NULL && choice >= 0)
			symbol__annotate_browser(selection);
474 475 476
	}

	newtFormDestroy(form);
477
	newtPopWindow();
478 479
}

480 481
static char browser__last_msg[1024];

482 483 484 485 486
int browser__show_help(const char *format, va_list ap)
{
	int ret;
	static int backlog;

487 488
        ret = vsnprintf(browser__last_msg + backlog,
			sizeof(browser__last_msg) - backlog, format, ap);
489 490
	backlog += ret;

491
	if (browser__last_msg[backlog - 1] == '\n') {
492
		newtPopHelpLine();
493
		newtPushHelpLine(browser__last_msg);
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
		newtRefresh();
		backlog = 0;
	}

	return ret;
}

void setup_browser(void)
{
	if (!isatty(1))
		return;

	use_browser = true;
	newtInit();
	newtCls();
	newtPushHelpLine(" ");
}

512
void exit_browser(bool wait_for_ok)
513
{
514 515 516 517 518
	if (use_browser) {
		if (wait_for_ok) {
			char title[] = "Fatal Error", ok[] = "Ok";
			newtWinMessage(title, ok, browser__last_msg);
		}
519
		newtFinished();
520
	}
521
}