perf report: Add a popup menu to ask what operation is to be performed
[linux-2.6.git] / tools / perf / util / newt.c
1 #define _GNU_SOURCE
2 #include <stdio.h>
3 #undef _GNU_SOURCE
4
5 #include <stdlib.h>
6 #include <newt.h>
7 #include <sys/ttydefaults.h>
8
9 #include "cache.h"
10 #include "hist.h"
11 #include "session.h"
12 #include "sort.h"
13 #include "symbol.h"
14
15 static void newt_form__set_exit_keys(newtComponent self)
16 {
17         newtFormAddHotKey(self, NEWT_KEY_ESCAPE);
18         newtFormAddHotKey(self, 'Q');
19         newtFormAddHotKey(self, 'q');
20         newtFormAddHotKey(self, CTRL('c'));
21 }
22
23 static newtComponent newt_form__new(void)
24 {
25         newtComponent self = newtForm(NULL, NULL, 0);
26         if (self)
27                 newt_form__set_exit_keys(self);
28         return self;
29 }
30
31 static int popup_menu(int argc, const char *argv[])
32 {
33         struct newtExitStruct es;
34         int i, rc = -1, max_len = 5;
35         newtComponent listbox, form = newt_form__new();
36
37         if (form == NULL)
38                 return -1;
39
40         listbox = newtListbox(0, 0, argc, NEWT_FLAG_RETURNEXIT);
41         if (listbox == NULL)
42                 goto out_destroy_form;
43
44         newtFormAddComponents(form, listbox, NULL);
45
46         for (i = 0; i < argc; ++i) {
47                 int len = strlen(argv[i]);
48                 if (len > max_len)
49                         max_len = len;
50                 if (newtListboxAddEntry(listbox, argv[i], (void *)(long)i))
51                         goto out_destroy_form;
52         }
53
54         newtCenteredWindow(max_len, argc, NULL);
55         newtFormRun(form, &es);
56         rc = newtListboxGetCurrent(listbox) - NULL;
57         if (es.reason == NEWT_EXIT_HOTKEY)
58                 rc = -1;
59         newtPopWindow();
60 out_destroy_form:
61         newtFormDestroy(form);
62         return rc;
63 }
64
65 static bool dialog_yesno(const char *msg)
66 {
67         /* newtWinChoice should really be accepting const char pointers... */
68         char yes[] = "Yes", no[] = "No";
69         return newtWinChoice(NULL, no, yes, (char *)msg) == 2;
70 }
71
72 /*
73  * When debugging newt problems it was useful to be able to "unroll"
74  * the calls to newtCheckBoxTreeAdd{Array,Item}, so that we can generate
75  * a source file with the sequence of calls to these methods, to then
76  * tweak the arrays to get the intended results, so I'm keeping this code
77  * here, may be useful again in the future.
78  */
79 #undef NEWT_DEBUG
80
81 static void newt_checkbox_tree__add(newtComponent tree, const char *str,
82                                     void *priv, int *indexes)
83 {
84 #ifdef NEWT_DEBUG
85         /* Print the newtCheckboxTreeAddArray to tinker with its index arrays */
86         int i = 0, len = 40 - strlen(str);
87
88         fprintf(stderr,
89                 "\tnewtCheckboxTreeAddItem(tree, %*.*s\"%s\", (void *)%p, 0, ",
90                 len, len, " ", str, priv);
91         while (indexes[i] != NEWT_ARG_LAST) {
92                 if (indexes[i] != NEWT_ARG_APPEND)
93                         fprintf(stderr, " %d,", indexes[i]);
94                 else
95                         fprintf(stderr, " %s,", "NEWT_ARG_APPEND");
96                 ++i;
97         }
98         fprintf(stderr, " %s", " NEWT_ARG_LAST);\n");
99         fflush(stderr);
100 #endif
101         newtCheckboxTreeAddArray(tree, str, priv, 0, indexes);
102 }
103
104 static char *callchain_list__sym_name(struct callchain_list *self,
105                                       char *bf, size_t bfsize)
106 {
107         if (self->sym)
108                 return self->sym->name;
109
110         snprintf(bf, bfsize, "%#Lx", self->ip);
111         return bf;
112 }
113
114 static void __callchain__append_graph_browser(struct callchain_node *self,
115                                               newtComponent tree, u64 total,
116                                               int *indexes, int depth)
117 {
118         struct rb_node *node;
119         u64 new_total, remaining;
120         int idx = 0;
121
122         if (callchain_param.mode == CHAIN_GRAPH_REL)
123                 new_total = self->children_hit;
124         else
125                 new_total = total;
126
127         remaining = new_total;
128         node = rb_first(&self->rb_root);
129         while (node) {
130                 struct callchain_node *child = rb_entry(node, struct callchain_node, rb_node);
131                 struct rb_node *next = rb_next(node);
132                 u64 cumul = cumul_hits(child);
133                 struct callchain_list *chain;
134                 int first = true, printed = 0;
135                 int chain_idx = -1;
136                 remaining -= cumul;
137
138                 indexes[depth] = NEWT_ARG_APPEND;
139                 indexes[depth + 1] = NEWT_ARG_LAST;
140
141                 list_for_each_entry(chain, &child->val, list) {
142                         char ipstr[BITS_PER_LONG / 4 + 1],
143                              *alloc_str = NULL;
144                         const char *str = callchain_list__sym_name(chain, ipstr, sizeof(ipstr));
145
146                         if (first) {
147                                 double percent = cumul * 100.0 / new_total;
148
149                                 first = false;
150                                 if (asprintf(&alloc_str, "%2.2f%% %s", percent, str) < 0)
151                                         str = "Not enough memory!";
152                                 else
153                                         str = alloc_str;
154                         } else {
155                                 indexes[depth] = idx;
156                                 indexes[depth + 1] = NEWT_ARG_APPEND;
157                                 indexes[depth + 2] = NEWT_ARG_LAST;
158                                 ++chain_idx;
159                         }
160                         newt_checkbox_tree__add(tree, str, chain->sym, indexes);
161                         free(alloc_str);
162                         ++printed;
163                 }
164
165                 indexes[depth] = idx;
166                 if (chain_idx != -1)
167                         indexes[depth + 1] = chain_idx;
168                 if (printed != 0)
169                         ++idx;
170                 __callchain__append_graph_browser(child, tree, new_total, indexes,
171                                                   depth + (chain_idx != -1 ? 2 : 1));
172                 node = next;
173         }
174 }
175
176 static void callchain__append_graph_browser(struct callchain_node *self,
177                                             newtComponent tree, u64 total,
178                                             int *indexes, int parent_idx)
179 {
180         struct callchain_list *chain;
181         int i = 0;
182
183         indexes[1] = NEWT_ARG_APPEND;
184         indexes[2] = NEWT_ARG_LAST;
185
186         list_for_each_entry(chain, &self->val, list) {
187                 char ipstr[BITS_PER_LONG / 4 + 1], *str;
188
189                 if (chain->ip >= PERF_CONTEXT_MAX)
190                         continue;
191
192                 if (!i++ && sort__first_dimension == SORT_SYM)
193                         continue;
194
195                 str = callchain_list__sym_name(chain, ipstr, sizeof(ipstr));
196                 newt_checkbox_tree__add(tree, str, chain->sym, indexes);
197         }
198
199         indexes[1] = parent_idx;
200         indexes[2] = NEWT_ARG_APPEND;
201         indexes[3] = NEWT_ARG_LAST;
202         __callchain__append_graph_browser(self, tree, total, indexes, 2);
203 }
204
205 static void hist_entry__append_callchain_browser(struct hist_entry *self,
206                                                  newtComponent tree, u64 total, int parent_idx)
207 {
208         struct rb_node *rb_node;
209         int indexes[1024] = { [0] = parent_idx, };
210         int idx = 0;
211         struct callchain_node *chain;
212
213         rb_node = rb_first(&self->sorted_chain);
214         while (rb_node) {
215                 chain = rb_entry(rb_node, struct callchain_node, rb_node);
216                 switch (callchain_param.mode) {
217                 case CHAIN_FLAT:
218                         break;
219                 case CHAIN_GRAPH_ABS: /* falldown */
220                 case CHAIN_GRAPH_REL:
221                         callchain__append_graph_browser(chain, tree, total, indexes, idx++);
222                         break;
223                 case CHAIN_NONE:
224                 default:
225                         break;
226                 }
227                 rb_node = rb_next(rb_node);
228         }
229 }
230
231 /*
232  * FIXME: get lib/string.c linked with perf somehow
233  */
234 static char *skip_spaces(const char *str)
235 {
236         while (isspace(*str))
237                 ++str;
238         return (char *)str;
239 }
240
241 static char *strim(char *s)
242 {
243         size_t size;
244         char *end;
245
246         s = skip_spaces(s);
247         size = strlen(s);
248         if (!size)
249                 return s;
250
251         end = s + size - 1;
252         while (end >= s && isspace(*end))
253                 end--;
254         *(end + 1) = '\0';
255
256         return s;
257 }
258
259 static size_t hist_entry__append_browser(struct hist_entry *self,
260                                          newtComponent tree, u64 total)
261 {
262         char bf[1024], *s;
263         FILE *fp;
264
265         if (symbol_conf.exclude_other && !self->parent)
266                 return 0;
267
268         fp = fmemopen(bf, sizeof(bf), "w");
269         if (fp == NULL)
270                 return 0;
271
272         hist_entry__fprintf(self, NULL, false, 0, fp, total);
273         fclose(fp);
274
275         /*
276          * FIXME: We shouldn't need to trim, as the printing routines shouldn't
277          * add spaces it in the first place, the stdio output routines should
278          * call a __snprintf method instead of the current __print (that
279          * actually is a __fprintf) one, but get the raw string and _then_ add
280          * the newline, as this is a detail of stdio printing, not needed in
281          * other UIs, e.g. newt.
282          */
283         s = strim(bf);
284
285         if (symbol_conf.use_callchain) {
286                 int indexes[2];
287
288                 indexes[0] = NEWT_ARG_APPEND;
289                 indexes[1] = NEWT_ARG_LAST;
290                 newt_checkbox_tree__add(tree, s, self->sym, indexes);
291         } else
292                 newtListboxAppendEntry(tree, s, self->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         struct newtExitStruct es;
303         char *str;
304         size_t line_len, max_line_len = 0;
305         size_t max_usable_width;
306         char *line = NULL;
307
308         if (self == NULL)
309                 return;
310
311         if (asprintf(&str, "perf annotate %s 2>&1 | expand", self->name) < 0)
312                 return;
313
314         fp = popen(str, "r");
315         if (fp == NULL)
316                 goto out_free_str;
317
318         newtPushHelpLine("Press ESC to exit");
319         newtGetScreenSize(&cols, &rows);
320         tree = newtListbox(0, 0, rows - 5, NEWT_FLAG_SCROLL);
321
322         while (!feof(fp)) {
323                 if (getline(&line, &line_len, fp) < 0 || !line_len)
324                         break;
325                 while (line_len != 0 && isspace(line[line_len - 1]))
326                         line[--line_len] = '\0';
327
328                 if (line_len > max_line_len)
329                         max_line_len = line_len;
330                 newtListboxAppendEntry(tree, line, NULL);
331         }
332         fclose(fp);
333         free(line);
334
335         max_usable_width = cols - 22;
336         if (max_line_len > max_usable_width)
337                 max_line_len = max_usable_width;
338
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         newtFormRun(form, &es);
346         newtFormDestroy(form);
347         newtPopWindow();
348         newtPopHelpLine();
349 out_free_str:
350         free(str);
351 }
352
353 static const void *newt__symbol_tree_get_current(newtComponent self)
354 {
355         if (symbol_conf.use_callchain)
356                 return newtCheckboxTreeGetCurrent(self);
357         return newtListboxGetCurrent(self);
358 }
359
360 static void perf_session__selection(newtComponent self, void *data)
361 {
362         const struct symbol **symbol_ptr = data;
363         *symbol_ptr = newt__symbol_tree_get_current(self);
364 }
365
366 void perf_session__browse_hists(struct rb_root *hists, u64 session_total,
367                                 const char *helpline)
368 {
369         struct sort_entry *se;
370         struct rb_node *nd;
371         char seq[] = ".";
372         unsigned int width;
373         char *col_width = symbol_conf.col_width_list_str;
374         int rows, cols, idx;
375         int max_len = 0;
376         char str[1024];
377         newtComponent form, tree;
378         struct newtExitStruct es;
379         const struct symbol *selection;
380
381         snprintf(str, sizeof(str), "Samples: %Ld", session_total);
382         newtDrawRootText(0, 0, str);
383         newtPushHelpLine(helpline);
384
385         newtGetScreenSize(&cols, &rows);
386
387         if (symbol_conf.use_callchain)
388                 tree = newtCheckboxTreeMulti(0, 0, rows - 5, seq,
389                                                 NEWT_FLAG_SCROLL);
390         else
391                 tree = newtListbox(0, 0, rows - 5, (NEWT_FLAG_SCROLL |
392                                                        NEWT_FLAG_RETURNEXIT));
393
394         newtComponentAddCallback(tree, perf_session__selection, &selection);
395
396         list_for_each_entry(se, &hist_entry__sort_list, list) {
397                 if (se->elide)
398                         continue;
399                 width = strlen(se->header);
400                 if (se->width) {
401                         if (symbol_conf.col_width_list_str) {
402                                 if (col_width) {
403                                         *se->width = atoi(col_width);
404                                         col_width = strchr(col_width, ',');
405                                         if (col_width)
406                                                 ++col_width;
407                                 }
408                         }
409                         *se->width = max(*se->width, width);
410                 }
411         }
412
413         idx = 0;
414         for (nd = rb_first(hists); nd; nd = rb_next(nd)) {
415                 struct hist_entry *h = rb_entry(nd, struct hist_entry, rb_node);
416                 int len = hist_entry__append_browser(h, tree, session_total);
417                 if (len > max_len)
418                         max_len = len;
419                 if (symbol_conf.use_callchain) {
420                         hist_entry__append_callchain_browser(h, tree, session_total, idx++);
421                         if (idx > 3300)
422                                 break;
423                 }
424         }
425
426         if (max_len > cols)
427                 max_len = cols - 3;
428
429         if (!symbol_conf.use_callchain)
430                 newtListboxSetWidth(tree, max_len);
431
432         newtCenteredWindow(max_len + (symbol_conf.use_callchain ? 5 : 0),
433                            rows - 5, "Report");
434         form = newt_form__new();
435         newtFormAddHotKey(form, 'A');
436         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                 char annotate[512];
443                 const char *options[2];
444                 int nr_options = 0, choice;
445
446                 newtFormRun(form, &es);
447                 if (es.reason == NEWT_EXIT_HOTKEY) {
448                         if (toupper(es.u.key) == 'A') {
449                                 symbol__annotate_browser(selection);
450                                 continue;
451                         }
452                         if (es.u.key == NEWT_KEY_ESCAPE ||
453                             toupper(es.u.key) == 'Q' ||
454                             es.u.key == CTRL('c')) {
455                                 if (dialog_yesno("Do you really want to exit?"))
456                                         break;
457                                 else
458                                         continue;
459                         }
460                 }
461
462                 if (selection != NULL) {
463                         snprintf(annotate, sizeof(annotate),
464                                  "Annotate %s", selection->name);
465                         options[nr_options++] = annotate;
466                 }
467
468                 options[nr_options++] = "Exit";
469                 choice = popup_menu(nr_options, options);
470                 if (choice == nr_options - 1)
471                         break;
472                 else if (selection != NULL && choice >= 0)
473                         symbol__annotate_browser(selection);
474         }
475
476         newtFormDestroy(form);
477         newtPopWindow();
478 }
479
480 static char browser__last_msg[1024];
481
482 int browser__show_help(const char *format, va_list ap)
483 {
484         int ret;
485         static int backlog;
486
487         ret = vsnprintf(browser__last_msg + backlog,
488                         sizeof(browser__last_msg) - backlog, format, ap);
489         backlog += ret;
490
491         if (browser__last_msg[backlog - 1] == '\n') {
492                 newtPopHelpLine();
493                 newtPushHelpLine(browser__last_msg);
494                 newtRefresh();
495                 backlog = 0;
496         }
497
498         return ret;
499 }
500
501 void setup_browser(void)
502 {
503         if (!isatty(1))
504                 return;
505
506         use_browser = true;
507         newtInit();
508         newtCls();
509         newtPushHelpLine(" ");
510 }
511
512 void exit_browser(bool wait_for_ok)
513 {
514         if (use_browser) {
515                 if (wait_for_ok) {
516                         char title[] = "Fatal Error", ok[] = "Ok";
517                         newtWinMessage(title, ok, browser__last_msg);
518                 }
519                 newtFinished();
520         }
521 }