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