2001d26a5579f1b9f5e41159a317bbc11ceb0dba
[safe/jmp/linux-2.6] / tools / perf / util / newt.c
1 #define _GNU_SOURCE
2 #include <stdio.h>
3 #undef _GNU_SOURCE
4
5 #include <slang.h>
6 #include <stdlib.h>
7 #include <newt.h>
8 #include <sys/ttydefaults.h>
9
10 #include "cache.h"
11 #include "hist.h"
12 #include "pstack.h"
13 #include "session.h"
14 #include "sort.h"
15 #include "symbol.h"
16
17 struct ui_progress {
18         newtComponent form, scale;
19 };
20
21 struct ui_progress *ui_progress__new(const char *title, u64 total)
22 {
23         struct ui_progress *self = malloc(sizeof(*self));
24
25         if (self != NULL) {
26                 int cols;
27                 newtGetScreenSize(&cols, NULL);
28                 cols -= 4;
29                 newtCenteredWindow(cols, 1, title);
30                 self->form  = newtForm(NULL, NULL, 0);
31                 if (self->form == NULL)
32                         goto out_free_self;
33                 self->scale = newtScale(0, 0, cols, total);
34                 if (self->scale == NULL)
35                         goto out_free_form;
36                 newtFormAddComponent(self->form, self->scale);
37                 newtRefresh();
38         }
39
40         return self;
41
42 out_free_form:
43         newtFormDestroy(self->form);
44 out_free_self:
45         free(self);
46         return NULL;
47 }
48
49 void ui_progress__update(struct ui_progress *self, u64 curr)
50 {
51         newtScaleSet(self->scale, curr);
52         newtRefresh();
53 }
54
55 void ui_progress__delete(struct ui_progress *self)
56 {
57         newtFormDestroy(self->form);
58         newtPopWindow();
59         free(self);
60 }
61
62 static void ui_helpline__pop(void)
63 {
64         newtPopHelpLine();
65 }
66
67 static void ui_helpline__push(const char *msg)
68 {
69         newtPushHelpLine(msg);
70 }
71
72 static void ui_helpline__vpush(const char *fmt, va_list ap)
73 {
74         char *s;
75
76         if (vasprintf(&s, fmt, ap) < 0)
77                 vfprintf(stderr, fmt, ap);
78         else {
79                 ui_helpline__push(s);
80                 free(s);
81         }
82 }
83
84 static void ui_helpline__fpush(const char *fmt, ...)
85 {
86         va_list ap;
87
88         va_start(ap, fmt);
89         ui_helpline__vpush(fmt, ap);
90         va_end(ap);
91 }
92
93 static void ui_helpline__puts(const char *msg)
94 {
95         ui_helpline__pop();
96         ui_helpline__push(msg);
97 }
98
99 static char browser__last_msg[1024];
100
101 int browser__show_help(const char *format, va_list ap)
102 {
103         int ret;
104         static int backlog;
105
106         ret = vsnprintf(browser__last_msg + backlog,
107                         sizeof(browser__last_msg) - backlog, format, ap);
108         backlog += ret;
109
110         if (browser__last_msg[backlog - 1] == '\n') {
111                 ui_helpline__puts(browser__last_msg);
112                 newtRefresh();
113                 backlog = 0;
114         }
115
116         return ret;
117 }
118
119 static void newt_form__set_exit_keys(newtComponent self)
120 {
121         newtFormAddHotKey(self, NEWT_KEY_LEFT);
122         newtFormAddHotKey(self, NEWT_KEY_ESCAPE);
123         newtFormAddHotKey(self, 'Q');
124         newtFormAddHotKey(self, 'q');
125         newtFormAddHotKey(self, CTRL('c'));
126 }
127
128 static newtComponent newt_form__new(void)
129 {
130         newtComponent self = newtForm(NULL, NULL, 0);
131         if (self)
132                 newt_form__set_exit_keys(self);
133         return self;
134 }
135
136 static int popup_menu(int argc, char * const argv[])
137 {
138         struct newtExitStruct es;
139         int i, rc = -1, max_len = 5;
140         newtComponent listbox, form = newt_form__new();
141
142         if (form == NULL)
143                 return -1;
144
145         listbox = newtListbox(0, 0, argc, NEWT_FLAG_RETURNEXIT);
146         if (listbox == NULL)
147                 goto out_destroy_form;
148
149         newtFormAddComponent(form, listbox);
150
151         for (i = 0; i < argc; ++i) {
152                 int len = strlen(argv[i]);
153                 if (len > max_len)
154                         max_len = len;
155                 if (newtListboxAddEntry(listbox, argv[i], (void *)(long)i))
156                         goto out_destroy_form;
157         }
158
159         newtCenteredWindow(max_len, argc, NULL);
160         newtFormRun(form, &es);
161         rc = newtListboxGetCurrent(listbox) - NULL;
162         if (es.reason == NEWT_EXIT_HOTKEY)
163                 rc = -1;
164         newtPopWindow();
165 out_destroy_form:
166         newtFormDestroy(form);
167         return rc;
168 }
169
170 static int ui__help_window(const char *text)
171 {
172         struct newtExitStruct es;
173         newtComponent tb, form = newt_form__new();
174         int rc = -1;
175         int max_len = 0, nr_lines = 0;
176         const char *t;
177
178         if (form == NULL)
179                 return -1;
180
181         t = text;
182         while (1) {
183                 const char *sep = strchr(t, '\n');
184                 int len;
185
186                 if (sep == NULL)
187                         sep = strchr(t, '\0');
188                 len = sep - t;
189                 if (max_len < len)
190                         max_len = len;
191                 ++nr_lines;
192                 if (*sep == '\0')
193                         break;
194                 t = sep + 1;
195         }
196
197         tb = newtTextbox(0, 0, max_len, nr_lines, 0);
198         if (tb == NULL)
199                 goto out_destroy_form;
200
201         newtTextboxSetText(tb, text);
202         newtFormAddComponent(form, tb);
203         newtCenteredWindow(max_len, nr_lines, NULL);
204         newtFormRun(form, &es);
205         newtPopWindow();
206         rc = 0;
207 out_destroy_form:
208         newtFormDestroy(form);
209         return rc;
210 }
211
212 static bool dialog_yesno(const char *msg)
213 {
214         /* newtWinChoice should really be accepting const char pointers... */
215         char yes[] = "Yes", no[] = "No";
216         return newtWinChoice(NULL, yes, no, (char *)msg) == 1;
217 }
218
219 #define HE_COLORSET_TOP         50
220 #define HE_COLORSET_MEDIUM      51
221 #define HE_COLORSET_NORMAL      52
222 #define HE_COLORSET_SELECTED    53
223 #define HE_COLORSET_CODE        54
224
225 static int ui_browser__percent_color(double percent, bool current)
226 {
227         if (current)
228                 return HE_COLORSET_SELECTED;
229         if (percent >= MIN_RED)
230                 return HE_COLORSET_TOP;
231         if (percent >= MIN_GREEN)
232                 return HE_COLORSET_MEDIUM;
233         return HE_COLORSET_NORMAL;
234 }
235
236 struct ui_browser {
237         newtComponent   form, sb;
238         u64             index, first_visible_entry_idx;
239         void            *first_visible_entry, *entries;
240         u16             top, left, width, height;
241         void            *priv;
242         u32             nr_entries;
243 };
244
245 static void ui_browser__refresh_dimensions(struct ui_browser *self)
246 {
247         int cols, rows;
248         newtGetScreenSize(&cols, &rows);
249
250         if (self->width > cols - 4)
251                 self->width = cols - 4;
252         self->height = rows - 5;
253         if (self->height > self->nr_entries)
254                 self->height = self->nr_entries;
255         self->top  = (rows - self->height) / 2;
256         self->left = (cols - self->width) / 2;
257 }
258
259 static void ui_browser__reset_index(struct ui_browser *self)
260 {
261         self->index = self->first_visible_entry_idx = 0;
262         self->first_visible_entry = NULL;
263 }
264
265 static int objdump_line__show(struct objdump_line *self, struct list_head *head,
266                               int width, struct hist_entry *he, int len,
267                               bool current_entry)
268 {
269         if (self->offset != -1) {
270                 struct symbol *sym = he->ms.sym;
271                 unsigned int hits = 0;
272                 double percent = 0.0;
273                 int color;
274                 struct sym_priv *priv = symbol__priv(sym);
275                 struct sym_ext *sym_ext = priv->ext;
276                 struct sym_hist *h = priv->hist;
277                 s64 offset = self->offset;
278                 struct objdump_line *next = objdump__get_next_ip_line(head, self);
279
280                 while (offset < (s64)len &&
281                        (next == NULL || offset < next->offset)) {
282                         if (sym_ext) {
283                                 percent += sym_ext[offset].percent;
284                         } else
285                                 hits += h->ip[offset];
286
287                         ++offset;
288                 }
289
290                 if (sym_ext == NULL && h->sum)
291                         percent = 100.0 * hits / h->sum;
292
293                 color = ui_browser__percent_color(percent, current_entry);
294                 SLsmg_set_color(color);
295                 SLsmg_printf(" %7.2f ", percent);
296                 if (!current_entry)
297                         SLsmg_set_color(HE_COLORSET_CODE);
298         } else {
299                 int color = ui_browser__percent_color(0, current_entry);
300                 SLsmg_set_color(color);
301                 SLsmg_write_nstring(" ", 9);
302         }
303
304         SLsmg_write_char(':');
305         SLsmg_write_nstring(" ", 8);
306         if (!*self->line)
307                 SLsmg_write_nstring(" ", width - 18);
308         else
309                 SLsmg_write_nstring(self->line, width - 18);
310
311         return 0;
312 }
313
314 static int ui_browser__refresh_entries(struct ui_browser *self)
315 {
316         struct objdump_line *pos;
317         struct list_head *head = self->entries;
318         struct hist_entry *he = self->priv;
319         int row = 0;
320         int len = he->ms.sym->end - he->ms.sym->start;
321
322         if (self->first_visible_entry == NULL || self->first_visible_entry == self->entries)
323                 self->first_visible_entry = head->next;
324
325         pos = list_entry(self->first_visible_entry, struct objdump_line, node);
326
327         list_for_each_entry_from(pos, head, node) {
328                 bool current_entry = (self->first_visible_entry_idx + row) == self->index;
329                 SLsmg_gotorc(self->top + row, self->left);
330                 objdump_line__show(pos, head, self->width,
331                                    he, len, current_entry);
332                 if (++row == self->height)
333                         break;
334         }
335
336         SLsmg_set_color(HE_COLORSET_NORMAL);
337         SLsmg_fill_region(self->top + row, self->left,
338                           self->height - row, self->width, ' ');
339
340         return 0;
341 }
342
343 static int ui_browser__run(struct ui_browser *self, const char *title,
344                            struct newtExitStruct *es)
345 {
346         if (self->form) {
347                 newtFormDestroy(self->form);
348                 newtPopWindow();
349         }
350
351         ui_browser__refresh_dimensions(self);
352         newtCenteredWindow(self->width + 2, self->height, title);
353         self->form = newt_form__new();
354         if (self->form == NULL)
355                 return -1;
356
357         self->sb = newtVerticalScrollbar(self->width + 1, 0, self->height,
358                                          HE_COLORSET_NORMAL,
359                                          HE_COLORSET_SELECTED);
360         if (self->sb == NULL)
361                 return -1;
362
363         newtFormAddHotKey(self->form, NEWT_KEY_UP);
364         newtFormAddHotKey(self->form, NEWT_KEY_DOWN);
365         newtFormAddHotKey(self->form, NEWT_KEY_PGUP);
366         newtFormAddHotKey(self->form, NEWT_KEY_PGDN);
367         newtFormAddHotKey(self->form, NEWT_KEY_HOME);
368         newtFormAddHotKey(self->form, NEWT_KEY_END);
369
370         if (ui_browser__refresh_entries(self) < 0)
371                 return -1;
372         newtFormAddComponent(self->form, self->sb);
373
374         while (1) {
375                 unsigned int offset;
376
377                 newtFormRun(self->form, es);
378
379                 if (es->reason != NEWT_EXIT_HOTKEY)
380                         break;
381                 switch (es->u.key) {
382                 case NEWT_KEY_DOWN:
383                         if (self->index == self->nr_entries - 1)
384                                 break;
385                         ++self->index;
386                         if (self->index == self->first_visible_entry_idx + self->height) {
387                                 struct list_head *pos = self->first_visible_entry;
388                                 ++self->first_visible_entry_idx;
389                                 self->first_visible_entry = pos->next;
390                         }
391                         break;
392                 case NEWT_KEY_UP:
393                         if (self->index == 0)
394                                 break;
395                         --self->index;
396                         if (self->index < self->first_visible_entry_idx) {
397                                 struct list_head *pos = self->first_visible_entry;
398                                 --self->first_visible_entry_idx;
399                                 self->first_visible_entry = pos->prev;
400                         }
401                         break;
402                 case NEWT_KEY_PGDN:
403                         if (self->first_visible_entry_idx + self->height > self->nr_entries - 1)
404                                 break;
405
406                         offset = self->height;
407                         if (self->index + offset > self->nr_entries - 1)
408                                 offset = self->nr_entries - 1 - self->index;
409                         self->index += offset;
410                         self->first_visible_entry_idx += offset;
411
412                         while (offset--) {
413                                 struct list_head *pos = self->first_visible_entry;
414                                 self->first_visible_entry = pos->next;
415                         }
416
417                         break;
418                 case NEWT_KEY_PGUP:
419                         if (self->first_visible_entry_idx == 0)
420                                 break;
421
422                         if (self->first_visible_entry_idx < self->height)
423                                 offset = self->first_visible_entry_idx;
424                         else
425                                 offset = self->height;
426
427                         self->index -= offset;
428                         self->first_visible_entry_idx -= offset;
429
430                         while (offset--) {
431                                 struct list_head *pos = self->first_visible_entry;
432                                 self->first_visible_entry = pos->prev;
433                         }
434                         break;
435                 case NEWT_KEY_HOME:
436                         ui_browser__reset_index(self);
437                         break;
438                 case NEWT_KEY_END: {
439                         struct list_head *head = self->entries;
440                         offset = self->height - 1;
441
442                         if (offset > self->nr_entries)
443                                 offset = self->nr_entries;
444
445                         self->index = self->first_visible_entry_idx = self->nr_entries - 1 - offset;
446                         self->first_visible_entry = head->prev;
447                         while (offset-- != 0) {
448                                 struct list_head *pos = self->first_visible_entry;
449                                 self->first_visible_entry = pos->prev;
450                         }
451                 }
452                         break;
453                 case NEWT_KEY_ESCAPE:
454                 case NEWT_KEY_LEFT:
455                 case CTRL('c'):
456                 case 'Q':
457                 case 'q':
458                         return 0;
459                 default:
460                         continue;
461                 }
462                 if (ui_browser__refresh_entries(self) < 0)
463                         return -1;
464         }
465         return 0;
466 }
467
468 /*
469  * When debugging newt problems it was useful to be able to "unroll"
470  * the calls to newtCheckBoxTreeAdd{Array,Item}, so that we can generate
471  * a source file with the sequence of calls to these methods, to then
472  * tweak the arrays to get the intended results, so I'm keeping this code
473  * here, may be useful again in the future.
474  */
475 #undef NEWT_DEBUG
476
477 static void newt_checkbox_tree__add(newtComponent tree, const char *str,
478                                     void *priv, int *indexes)
479 {
480 #ifdef NEWT_DEBUG
481         /* Print the newtCheckboxTreeAddArray to tinker with its index arrays */
482         int i = 0, len = 40 - strlen(str);
483
484         fprintf(stderr,
485                 "\tnewtCheckboxTreeAddItem(tree, %*.*s\"%s\", (void *)%p, 0, ",
486                 len, len, " ", str, priv);
487         while (indexes[i] != NEWT_ARG_LAST) {
488                 if (indexes[i] != NEWT_ARG_APPEND)
489                         fprintf(stderr, " %d,", indexes[i]);
490                 else
491                         fprintf(stderr, " %s,", "NEWT_ARG_APPEND");
492                 ++i;
493         }
494         fprintf(stderr, " %s", " NEWT_ARG_LAST);\n");
495         fflush(stderr);
496 #endif
497         newtCheckboxTreeAddArray(tree, str, priv, 0, indexes);
498 }
499
500 static char *callchain_list__sym_name(struct callchain_list *self,
501                                       char *bf, size_t bfsize)
502 {
503         if (self->ms.sym)
504                 return self->ms.sym->name;
505
506         snprintf(bf, bfsize, "%#Lx", self->ip);
507         return bf;
508 }
509
510 static void __callchain__append_graph_browser(struct callchain_node *self,
511                                               newtComponent tree, u64 total,
512                                               int *indexes, int depth)
513 {
514         struct rb_node *node;
515         u64 new_total, remaining;
516         int idx = 0;
517
518         if (callchain_param.mode == CHAIN_GRAPH_REL)
519                 new_total = self->children_hit;
520         else
521                 new_total = total;
522
523         remaining = new_total;
524         node = rb_first(&self->rb_root);
525         while (node) {
526                 struct callchain_node *child = rb_entry(node, struct callchain_node, rb_node);
527                 struct rb_node *next = rb_next(node);
528                 u64 cumul = cumul_hits(child);
529                 struct callchain_list *chain;
530                 int first = true, printed = 0;
531                 int chain_idx = -1;
532                 remaining -= cumul;
533
534                 indexes[depth] = NEWT_ARG_APPEND;
535                 indexes[depth + 1] = NEWT_ARG_LAST;
536
537                 list_for_each_entry(chain, &child->val, list) {
538                         char ipstr[BITS_PER_LONG / 4 + 1],
539                              *alloc_str = NULL;
540                         const char *str = callchain_list__sym_name(chain, ipstr, sizeof(ipstr));
541
542                         if (first) {
543                                 double percent = cumul * 100.0 / new_total;
544
545                                 first = false;
546                                 if (asprintf(&alloc_str, "%2.2f%% %s", percent, str) < 0)
547                                         str = "Not enough memory!";
548                                 else
549                                         str = alloc_str;
550                         } else {
551                                 indexes[depth] = idx;
552                                 indexes[depth + 1] = NEWT_ARG_APPEND;
553                                 indexes[depth + 2] = NEWT_ARG_LAST;
554                                 ++chain_idx;
555                         }
556                         newt_checkbox_tree__add(tree, str, &chain->ms, indexes);
557                         free(alloc_str);
558                         ++printed;
559                 }
560
561                 indexes[depth] = idx;
562                 if (chain_idx != -1)
563                         indexes[depth + 1] = chain_idx;
564                 if (printed != 0)
565                         ++idx;
566                 __callchain__append_graph_browser(child, tree, new_total, indexes,
567                                                   depth + (chain_idx != -1 ? 2 : 1));
568                 node = next;
569         }
570 }
571
572 static void callchain__append_graph_browser(struct callchain_node *self,
573                                             newtComponent tree, u64 total,
574                                             int *indexes, int parent_idx)
575 {
576         struct callchain_list *chain;
577         int i = 0;
578
579         indexes[1] = NEWT_ARG_APPEND;
580         indexes[2] = NEWT_ARG_LAST;
581
582         list_for_each_entry(chain, &self->val, list) {
583                 char ipstr[BITS_PER_LONG / 4 + 1], *str;
584
585                 if (chain->ip >= PERF_CONTEXT_MAX)
586                         continue;
587
588                 if (!i++ && sort__first_dimension == SORT_SYM)
589                         continue;
590
591                 str = callchain_list__sym_name(chain, ipstr, sizeof(ipstr));
592                 newt_checkbox_tree__add(tree, str, &chain->ms, indexes);
593         }
594
595         indexes[1] = parent_idx;
596         indexes[2] = NEWT_ARG_APPEND;
597         indexes[3] = NEWT_ARG_LAST;
598         __callchain__append_graph_browser(self, tree, total, indexes, 2);
599 }
600
601 static void hist_entry__append_callchain_browser(struct hist_entry *self,
602                                                  newtComponent tree, u64 total, int parent_idx)
603 {
604         struct rb_node *rb_node;
605         int indexes[1024] = { [0] = parent_idx, };
606         int idx = 0;
607         struct callchain_node *chain;
608
609         rb_node = rb_first(&self->sorted_chain);
610         while (rb_node) {
611                 chain = rb_entry(rb_node, struct callchain_node, rb_node);
612                 switch (callchain_param.mode) {
613                 case CHAIN_FLAT:
614                         break;
615                 case CHAIN_GRAPH_ABS: /* falldown */
616                 case CHAIN_GRAPH_REL:
617                         callchain__append_graph_browser(chain, tree, total, indexes, idx++);
618                         break;
619                 case CHAIN_NONE:
620                 default:
621                         break;
622                 }
623                 rb_node = rb_next(rb_node);
624         }
625 }
626
627 static size_t hist_entry__append_browser(struct hist_entry *self,
628                                          newtComponent tree, u64 total)
629 {
630         char s[256];
631         size_t ret;
632
633         if (symbol_conf.exclude_other && !self->parent)
634                 return 0;
635
636         ret = hist_entry__snprintf(self, s, sizeof(s), NULL,
637                                    false, 0, false, total);
638         if (symbol_conf.use_callchain) {
639                 int indexes[2];
640
641                 indexes[0] = NEWT_ARG_APPEND;
642                 indexes[1] = NEWT_ARG_LAST;
643                 newt_checkbox_tree__add(tree, s, &self->ms, indexes);
644         } else
645                 newtListboxAppendEntry(tree, s, &self->ms);
646
647         return ret;
648 }
649
650 static void hist_entry__annotate_browser(struct hist_entry *self)
651 {
652         struct ui_browser browser;
653         struct newtExitStruct es;
654         struct objdump_line *pos, *n;
655         LIST_HEAD(head);
656
657         if (self->ms.sym == NULL)
658                 return;
659
660         if (hist_entry__annotate(self, &head) < 0)
661                 return;
662
663         ui_helpline__push("Press <- or ESC to exit");
664
665         memset(&browser, 0, sizeof(browser));
666         browser.entries = &head;
667         browser.priv = self;
668         list_for_each_entry(pos, &head, node) {
669                 size_t line_len = strlen(pos->line);
670                 if (browser.width < line_len)
671                         browser.width = line_len;
672                 ++browser.nr_entries;
673         }
674
675         browser.width += 18; /* Percentage */
676         ui_browser__run(&browser, self->ms.sym->name, &es);
677         newtFormDestroy(browser.form);
678         newtPopWindow();
679         list_for_each_entry_safe(pos, n, &head, node) {
680                 list_del(&pos->node);
681                 objdump_line__free(pos);
682         }
683         ui_helpline__pop();
684 }
685
686 static const void *newt__symbol_tree_get_current(newtComponent self)
687 {
688         if (symbol_conf.use_callchain)
689                 return newtCheckboxTreeGetCurrent(self);
690         return newtListboxGetCurrent(self);
691 }
692
693 static void hist_browser__selection(newtComponent self, void *data)
694 {
695         const struct map_symbol **symbol_ptr = data;
696         *symbol_ptr = newt__symbol_tree_get_current(self);
697 }
698
699 struct hist_browser {
700         newtComponent           form, tree;
701         const struct map_symbol *selection;
702 };
703
704 static struct hist_browser *hist_browser__new(void)
705 {
706         struct hist_browser *self = malloc(sizeof(*self));
707
708         if (self != NULL)
709                 self->form = NULL;
710
711         return self;
712 }
713
714 static void hist_browser__delete(struct hist_browser *self)
715 {
716         newtFormDestroy(self->form);
717         newtPopWindow();
718         free(self);
719 }
720
721 static int hist_browser__populate(struct hist_browser *self, struct hists *hists,
722                                   const char *title)
723 {
724         int max_len = 0, idx, cols, rows;
725         struct ui_progress *progress;
726         struct rb_node *nd;
727         u64 curr_hist = 0;
728         char seq[] = ".", unit;
729         char str[256];
730         unsigned long nr_events = hists->stats.nr_events[PERF_RECORD_SAMPLE];
731
732         if (self->form) {
733                 newtFormDestroy(self->form);
734                 newtPopWindow();
735         }
736
737         nr_events = convert_unit(nr_events, &unit);
738         snprintf(str, sizeof(str), "Events: %lu%c                            ",
739                  nr_events, unit);
740         newtDrawRootText(0, 0, str);
741
742         newtGetScreenSize(NULL, &rows);
743
744         if (symbol_conf.use_callchain)
745                 self->tree = newtCheckboxTreeMulti(0, 0, rows - 5, seq,
746                                                    NEWT_FLAG_SCROLL);
747         else
748                 self->tree = newtListbox(0, 0, rows - 5,
749                                         (NEWT_FLAG_SCROLL |
750                                          NEWT_FLAG_RETURNEXIT));
751
752         newtComponentAddCallback(self->tree, hist_browser__selection,
753                                  &self->selection);
754
755         progress = ui_progress__new("Adding entries to the browser...",
756                                     hists->nr_entries);
757         if (progress == NULL)
758                 return -1;
759
760         idx = 0;
761         for (nd = rb_first(&hists->entries); nd; nd = rb_next(nd)) {
762                 struct hist_entry *h = rb_entry(nd, struct hist_entry, rb_node);
763                 int len;
764
765                 if (h->filtered)
766                         continue;
767
768                 len = hist_entry__append_browser(h, self->tree, hists->stats.total_period);
769                 if (len > max_len)
770                         max_len = len;
771                 if (symbol_conf.use_callchain)
772                         hist_entry__append_callchain_browser(h, self->tree,
773                                                              hists->stats.total_period, idx++);
774                 ++curr_hist;
775                 if (curr_hist % 5)
776                         ui_progress__update(progress, curr_hist);
777         }
778
779         ui_progress__delete(progress);
780
781         newtGetScreenSize(&cols, &rows);
782
783         if (max_len > cols)
784                 max_len = cols - 3;
785
786         if (!symbol_conf.use_callchain)
787                 newtListboxSetWidth(self->tree, max_len);
788
789         newtCenteredWindow(max_len + (symbol_conf.use_callchain ? 5 : 0),
790                            rows - 5, title);
791         self->form = newt_form__new();
792         if (self->form == NULL)
793                 return -1;
794
795         newtFormAddHotKey(self->form, 'A');
796         newtFormAddHotKey(self->form, 'a');
797         newtFormAddHotKey(self->form, 'D');
798         newtFormAddHotKey(self->form, 'd');
799         newtFormAddHotKey(self->form, 'T');
800         newtFormAddHotKey(self->form, 't');
801         newtFormAddHotKey(self->form, '?');
802         newtFormAddHotKey(self->form, 'H');
803         newtFormAddHotKey(self->form, 'h');
804         newtFormAddHotKey(self->form, NEWT_KEY_F1);
805         newtFormAddHotKey(self->form, NEWT_KEY_RIGHT);
806         newtFormAddComponents(self->form, self->tree, NULL);
807         self->selection = newt__symbol_tree_get_current(self->tree);
808
809         return 0;
810 }
811
812 static struct hist_entry *hist_browser__selected_entry(struct hist_browser *self)
813 {
814         int *indexes;
815
816         if (!symbol_conf.use_callchain)
817                 goto out;
818
819         indexes = newtCheckboxTreeFindItem(self->tree, (void *)self->selection);
820         if (indexes) {
821                 bool is_hist_entry = indexes[1] == NEWT_ARG_LAST;
822                 free(indexes);
823                 if (is_hist_entry)
824                         goto out;
825         }
826         return NULL;
827 out:
828         return container_of(self->selection, struct hist_entry, ms);
829 }
830
831 static struct thread *hist_browser__selected_thread(struct hist_browser *self)
832 {
833         struct hist_entry *he = hist_browser__selected_entry(self);
834         return he ? he->thread : NULL;
835 }
836
837 static int hist_browser__title(char *bf, size_t size, const char *input_name,
838                                const struct dso *dso, const struct thread *thread)
839 {
840         int printed = 0;
841
842         if (thread)
843                 printed += snprintf(bf + printed, size - printed,
844                                     "Thread: %s(%d)",
845                                     (thread->comm_set ?  thread->comm : ""),
846                                     thread->pid);
847         if (dso)
848                 printed += snprintf(bf + printed, size - printed,
849                                     "%sDSO: %s", thread ? " " : "",
850                                     dso->short_name);
851         return printed ?: snprintf(bf, size, "Report: %s", input_name);
852 }
853
854 int hists__browse(struct hists *self, const char *helpline, const char *input_name)
855 {
856         struct hist_browser *browser = hist_browser__new();
857         struct pstack *fstack = pstack__new(2);
858         const struct thread *thread_filter = NULL;
859         const struct dso *dso_filter = NULL;
860         struct newtExitStruct es;
861         char msg[160];
862         int err = -1;
863
864         if (browser == NULL)
865                 return -1;
866
867         fstack = pstack__new(2);
868         if (fstack == NULL)
869                 goto out;
870
871         ui_helpline__push(helpline);
872
873         hist_browser__title(msg, sizeof(msg), input_name,
874                             dso_filter, thread_filter);
875         if (hist_browser__populate(browser, self, msg) < 0)
876                 goto out_free_stack;
877
878         while (1) {
879                 const struct thread *thread;
880                 const struct dso *dso;
881                 char *options[16];
882                 int nr_options = 0, choice = 0, i,
883                     annotate = -2, zoom_dso = -2, zoom_thread = -2;
884
885                 newtFormRun(browser->form, &es);
886
887                 thread = hist_browser__selected_thread(browser);
888                 dso = browser->selection->map ? browser->selection->map->dso : NULL;
889
890                 if (es.reason == NEWT_EXIT_HOTKEY) {
891                         if (es.u.key == NEWT_KEY_F1)
892                                 goto do_help;
893
894                         switch (toupper(es.u.key)) {
895                         case 'A':
896                                 goto do_annotate;
897                         case 'D':
898                                 goto zoom_dso;
899                         case 'T':
900                                 goto zoom_thread;
901                         case 'H':
902                         case '?':
903 do_help:
904                                 ui__help_window("->        Zoom into DSO/Threads & Annotate current symbol\n"
905                                                 "<-        Zoom out\n"
906                                                 "a         Annotate current symbol\n"
907                                                 "h/?/F1    Show this window\n"
908                                                 "d         Zoom into current DSO\n"
909                                                 "t         Zoom into current Thread\n"
910                                                 "q/CTRL+C  Exit browser");
911                                 continue;
912                         default:;
913                         }
914                         if (toupper(es.u.key) == 'Q' ||
915                             es.u.key == CTRL('c'))
916                                 break;
917                         if (es.u.key == NEWT_KEY_ESCAPE) {
918                                 if (dialog_yesno("Do you really want to exit?"))
919                                         break;
920                                 else
921                                         continue;
922                         }
923
924                         if (es.u.key == NEWT_KEY_LEFT) {
925                                 const void *top;
926
927                                 if (pstack__empty(fstack))
928                                         continue;
929                                 top = pstack__pop(fstack);
930                                 if (top == &dso_filter)
931                                         goto zoom_out_dso;
932                                 if (top == &thread_filter)
933                                         goto zoom_out_thread;
934                                 continue;
935                         }
936                 }
937
938                 if (browser->selection->sym != NULL &&
939                     asprintf(&options[nr_options], "Annotate %s",
940                              browser->selection->sym->name) > 0)
941                         annotate = nr_options++;
942
943                 if (thread != NULL &&
944                     asprintf(&options[nr_options], "Zoom %s %s(%d) thread",
945                              (thread_filter ? "out of" : "into"),
946                              (thread->comm_set ? thread->comm : ""),
947                              thread->pid) > 0)
948                         zoom_thread = nr_options++;
949
950                 if (dso != NULL &&
951                     asprintf(&options[nr_options], "Zoom %s %s DSO",
952                              (dso_filter ? "out of" : "into"),
953                              (dso->kernel ? "the Kernel" : dso->short_name)) > 0)
954                         zoom_dso = nr_options++;
955
956                 options[nr_options++] = (char *)"Exit";
957
958                 choice = popup_menu(nr_options, options);
959
960                 for (i = 0; i < nr_options - 1; ++i)
961                         free(options[i]);
962
963                 if (choice == nr_options - 1)
964                         break;
965
966                 if (choice == -1)
967                         continue;
968
969                 if (choice == annotate) {
970                         struct hist_entry *he;
971 do_annotate:
972                         if (browser->selection->map->dso->origin == DSO__ORIG_KERNEL) {
973                                 ui_helpline__puts("No vmlinux file found, can't "
974                                                  "annotate with just a "
975                                                  "kallsyms file");
976                                 continue;
977                         }
978
979                         he = hist_browser__selected_entry(browser);
980                         if (he == NULL)
981                                 continue;
982
983                         hist_entry__annotate_browser(he);
984                 } else if (choice == zoom_dso) {
985 zoom_dso:
986                         if (dso_filter) {
987                                 pstack__remove(fstack, &dso_filter);
988 zoom_out_dso:
989                                 ui_helpline__pop();
990                                 dso_filter = NULL;
991                         } else {
992                                 if (dso == NULL)
993                                         continue;
994                                 ui_helpline__fpush("To zoom out press <- or -> + \"Zoom out of %s DSO\"",
995                                                    dso->kernel ? "the Kernel" : dso->short_name);
996                                 dso_filter = dso;
997                                 pstack__push(fstack, &dso_filter);
998                         }
999                         hists__filter_by_dso(self, dso_filter);
1000                         hist_browser__title(msg, sizeof(msg), input_name,
1001                                             dso_filter, thread_filter);
1002                         if (hist_browser__populate(browser, self, msg) < 0)
1003                                 goto out;
1004                 } else if (choice == zoom_thread) {
1005 zoom_thread:
1006                         if (thread_filter) {
1007                                 pstack__remove(fstack, &thread_filter);
1008 zoom_out_thread:
1009                                 ui_helpline__pop();
1010                                 thread_filter = NULL;
1011                         } else {
1012                                 ui_helpline__fpush("To zoom out press <- or -> + \"Zoom out of %s(%d) thread\"",
1013                                                    thread->comm_set ? thread->comm : "",
1014                                                    thread->pid);
1015                                 thread_filter = thread;
1016                                 pstack__push(fstack, &thread_filter);
1017                         }
1018                         hists__filter_by_thread(self, thread_filter);
1019                         hist_browser__title(msg, sizeof(msg), input_name,
1020                                             dso_filter, thread_filter);
1021                         if (hist_browser__populate(browser, self, msg) < 0)
1022                                 goto out;
1023                 }
1024         }
1025         err = 0;
1026 out_free_stack:
1027         pstack__delete(fstack);
1028 out:
1029         hist_browser__delete(browser);
1030         return err;
1031 }
1032
1033 static struct newtPercentTreeColors {
1034         const char *topColorFg, *topColorBg;
1035         const char *mediumColorFg, *mediumColorBg;
1036         const char *normalColorFg, *normalColorBg;
1037         const char *selColorFg, *selColorBg;
1038         const char *codeColorFg, *codeColorBg;
1039 } defaultPercentTreeColors = {
1040         "red",       "lightgray",
1041         "green",     "lightgray",
1042         "black",     "lightgray",
1043         "lightgray", "magenta",
1044         "blue",      "lightgray",
1045 };
1046
1047 void setup_browser(void)
1048 {
1049         struct newtPercentTreeColors *c = &defaultPercentTreeColors;
1050         if (!isatty(1))
1051                 return;
1052
1053         use_browser = true;
1054         newtInit();
1055         newtCls();
1056         ui_helpline__puts(" ");
1057         SLtt_set_color(HE_COLORSET_TOP, NULL, c->topColorFg, c->topColorBg);
1058         SLtt_set_color(HE_COLORSET_MEDIUM, NULL, c->mediumColorFg, c->mediumColorBg);
1059         SLtt_set_color(HE_COLORSET_NORMAL, NULL, c->normalColorFg, c->normalColorBg);
1060         SLtt_set_color(HE_COLORSET_SELECTED, NULL, c->selColorFg, c->selColorBg);
1061         SLtt_set_color(HE_COLORSET_CODE, NULL, c->codeColorFg, c->codeColorBg);
1062 }
1063
1064 void exit_browser(bool wait_for_ok)
1065 {
1066         if (use_browser) {
1067                 if (wait_for_ok) {
1068                         char title[] = "Fatal Error", ok[] = "Ok";
1069                         newtWinMessage(title, ok, browser__last_msg);
1070                 }
1071                 newtFinished();
1072         }
1073 }