[go: up one dir, main page]

File: tui.c

package info (click to toggle)
uftrace 0.9.0-1
  • links: PTS
  • area: main
  • in suites: buster
  • size: 3,896 kB
  • sloc: ansic: 41,425; python: 7,369; makefile: 698; asm: 488; cpp: 461; sh: 349
file content (2567 lines) | stat: -rw-r--r-- 57,529 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
#ifdef HAVE_LIBNCURSES

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <ncurses.h>
#include <locale.h>
#include <inttypes.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>

#include "uftrace.h"
#include "version.h"
#include "utils/utils.h"
#include "utils/fstack.h"
#include "utils/graph.h"
#include "utils/list.h"
#include "utils/rbtree.h"
#include "utils/field.h"
#include "utils/dwarf.h"

#define KEY_ESCAPE  27

static bool tui_finished;
static bool tui_debug;

struct tui_graph_node {
	struct uftrace_graph_node n;
	struct uftrace_graph *graph;
	struct list_head link; // for tui_report_node.head
	bool folded;
};

struct tui_report_node {
	struct rb_node name_link;
	struct rb_node sort_link;
	struct list_head head; // links tui_graph_node.link
	char *name;
	uint64_t time;
	uint64_t min_time;
	uint64_t max_time;
	uint64_t self_time;
	uint64_t min_self_time;
	uint64_t max_self_time;
	uint64_t recursive_time;
	unsigned calls;
};

struct tui_list_node {
	struct list_head list;
	void *data;
};

struct tui_window;

struct tui_window_ops {
	void * (*prev)(struct tui_window *win, void *node, bool update);
	void * (*next)(struct tui_window *win, void *node, bool update);
	void * (*top)(struct tui_window *win, bool update);
	void * (*parent)(struct tui_window *win, void *node);
	void * (*sibling_prev)(struct tui_window *win, void *node);
	void * (*sibling_next)(struct tui_window *win, void *node);
	bool (*needs_blank)(struct tui_window *win, void *prev, void *next);
	bool (*enter)(struct tui_window *win, void *node);
	bool (*collapse)(struct tui_window *win, void *node, int depth);
	bool (*expand)(struct tui_window *win, void *node, int depth);
	void (*header)(struct tui_window *win, struct ftrace_file_handle *handle);
	void (*footer)(struct tui_window *win, struct ftrace_file_handle *handle);
	void (*display)(struct tui_window *win, void *node);
	bool (*search)(struct tui_window *win, void *node, char *str);
	bool (*longest_child)(struct tui_window *win, void *node);
	struct debug_location * (*location)(struct tui_window *win, void *node);
};

struct tui_window {
	const struct tui_window_ops *ops;
	void *top;
	void *curr;
	void *old;
	int top_index;
	int curr_index;
	int search_count;
};

struct tui_report {
	struct tui_window win;
	struct list_head list;
	struct rb_root name_tree;
	struct rb_root sort_tree;
	int nr_sess;
	int nr_func;
};

struct tui_graph {
	struct tui_window win;
	struct uftrace_graph ug;
	struct list_head list;
	struct tui_graph_node *disp;
	int top_depth;
	int curr_depth;
	int disp_depth;
	int width;
	bool *top_mask;
	bool *disp_mask;
	size_t mask_size;
	bool disp_update;
};

struct tui_list {
	struct tui_window win;
	struct list_head head;
	int nr_node;
};

static LIST_HEAD(tui_graph_list);
static LIST_HEAD(graph_output_fields);
static struct tui_report tui_report;
static struct tui_graph partial_graph;
static struct tui_list tui_info;
static struct tui_list tui_session;
static char *tui_search;

static const struct tui_window_ops graph_ops;
static const struct tui_window_ops report_ops;
static const struct tui_window_ops info_ops;
static const struct tui_window_ops session_ops;

static void tui_window_move_down(struct tui_window *win);

#define FIELD_SPACE  2
#define FIELD_SEP  " :"

#define C_NORMAL  0
#define C_HEADER  1
#define C_GREEN   2
#define C_YELLOW  3
#define C_RED     4

static const char *help[] = {
	"ARROW         Navigation",
	"PgUp/Dn",
	"Home/End",
	"Enter         Select/Fold",
	"G             Show (full) call graph",
	"g             Show call graph for this function",
	"R             Show uftrace report",
	"I             Show uftrace info",
	"S             Change session",
	"O             Open editor",
	"c/e           Collapse/Expand graph",
	"n/p           Next/Prev sibling",
	"u             Move up to parent",
	"l             Move to the longest executed child",
	"j/k           Move down/up",
	"/             Search",
	"</>/N/P       Search next/prev",
	"v             Show debug message",
	"h/?           Show this help",
	"q             Quit",
};

static void init_colors(void)
{
	if (!has_colors())
		return;

	start_color();

	/* C_NORMAL uses the default color pair */
	init_pair(C_HEADER, COLOR_WHITE,  COLOR_BLUE);
	init_pair(C_GREEN,  COLOR_GREEN,  COLOR_BLACK);
	init_pair(C_YELLOW, COLOR_YELLOW, COLOR_BLACK);
	init_pair(C_RED,    COLOR_RED,    COLOR_BLACK);
}

static void print_time(uint64_t ntime)
{
	char *units[] = { "us", "ms", " s", " m", " h", };
	int pairs[] = { C_NORMAL, C_GREEN, C_YELLOW, C_RED, C_RED };
	unsigned limit[] = { 1000, 1000, 1000, 60, 24, INT_MAX, };
	uint64_t fract;
	unsigned idx;

	if (ntime == 0UL) {
		printw("%7s %2s", "", "");
		return;
	}

	for (idx = 0; idx < ARRAY_SIZE(units); idx++) {
		fract = ntime % limit[idx];
		ntime = ntime / limit[idx];

		if (ntime < limit[idx+1])
			break;
	}

	/* for some error cases */
	if (ntime > 999)
		ntime = fract = 999;

	printw("%3"PRIu64".%03"PRIu64" ", ntime, fract);
	attron(COLOR_PAIR(pairs[idx]));
	printw("%2s", units[idx]);
	attroff(COLOR_PAIR(pairs[idx]));
}

static void print_graph_total(struct field_data *fd)
{
	struct uftrace_graph_node *node = fd->arg;
	uint64_t d;

	d = node->time;

	print_time(d);
}

static void print_graph_self(struct field_data *fd)
{
	struct uftrace_graph_node *node = fd->arg;
	uint64_t d;

	d = node->time - node->child_time;

	print_time(d);
}

static void print_graph_addr(struct field_data *fd)
{
	struct uftrace_graph_node *node = fd->arg;

	/* uftrace records (truncated) 48-bit addresses */
	int width = sizeof(long) == 4 ? 8 : 12;

	printw("%*lx", width, node->addr);
}

static struct display_field field_total_time= {
	.id      = GRAPH_F_TOTAL_TIME,
	.name    = "total-time",
	.alias   = "total",
	.header  = "TOTAL TIME",
	.length  = 10,
	.print   = print_graph_total,
	.list    = LIST_HEAD_INIT(field_total_time.list),
};

static struct display_field field_self_time= {
	.id      = GRAPH_F_SELF_TIME,
	.name    = "self-time",
	.alias   = "self",
	.header  = " SELF TIME",
	.length  = 10,
	.print   = print_graph_self,
	.list    = LIST_HEAD_INIT(field_self_time.list),
};

static struct display_field field_addr = {
	.id      = GRAPH_F_ADDR,
	.name    = "address",
	.alias   = "addr",
#if __SIZEOF_LONG == 4
	.header  = "  ADDR  ",
	.length  = 8,
#else
	.header  = "   ADDRESS  ",
	.length  = 12,
#endif
	.print   = print_graph_addr,
	.list    = LIST_HEAD_INIT(field_addr.list),
};

/* index of this table should be matched to display_field_id */
static struct display_field *graph_field_table[] = {
	&field_total_time,
	&field_self_time,
	&field_addr,
};

static void setup_default_graph_field(struct list_head *fields, struct opts *opts)
{
	add_field(fields, graph_field_table[GRAPH_F_TOTAL_TIME]);
}

static inline bool is_first_child(struct tui_graph_node *prev,
				  struct tui_graph_node *next)
{
	return prev->n.head.next == &next->n.list;
}

static inline bool is_last_child(struct tui_graph_node *prev,
				 struct tui_graph_node *next)
{
	return prev->n.head.prev == &next->n.list;
}

static int create_data(struct uftrace_session *sess, void *arg)
{
	struct tui_graph *graph = xzalloc(sizeof(*graph));

	pr_dbg("create graph for session %.*s (%s)\n",
	       SESSION_ID_LEN, sess->sid, sess->exename);

	graph_init(&graph->ug, sess);

	list_add_tail(&graph->list, &tui_graph_list);

	tui_report.nr_sess++;

	return 0;
}

static void tui_setup(struct ftrace_file_handle *handle, struct opts *opts)
{
	walk_sessions(&handle->sessions, create_data, NULL);

	tui_report.name_tree = RB_ROOT;
	tui_report.sort_tree = RB_ROOT;

	setup_field(&graph_output_fields, opts, setup_default_graph_field,
		    graph_field_table, ARRAY_SIZE(graph_field_table));
}

static void tui_cleanup(void)
{
	struct tui_graph *graph;

	if (!tui_finished)
		endwin();

	tui_finished = true;

	while (!list_empty(&tui_graph_list)) {
		graph = list_first_entry(&tui_graph_list, typeof(*graph), list);
		list_del(&graph->list);
		free(graph);
	}
	graph_remove_task();
}

static struct uftrace_graph * get_graph(struct ftrace_task_handle *task,
					uint64_t time, uint64_t addr)
{
	struct tui_graph *graph;
	struct uftrace_session_link *sessions = &task->h->sessions;
	struct uftrace_session *sess;

	sess = find_task_session(sessions, task->tid, time);
	if (sess == NULL)
		sess = find_task_session(sessions, task->t->pid, time);
	if (sess == NULL)
		sess = find_task_session(sessions, task->t->ppid, time);

	if (sess == NULL) {
		struct uftrace_session *fsess = sessions->first;

		if (is_kernel_address(&fsess->symtabs, addr))
			sess = fsess;
		else
			return NULL;
	}

	list_for_each_entry(graph, &tui_graph_list, list) {
		if (graph->ug.sess == sess)
			return &graph->ug;
	}
	return NULL;
}

static struct tui_report_node * find_report_node(struct tui_report *report,
						 char *symname)
{
	struct tui_report_node *node;
	struct rb_node *parent = NULL;
	struct rb_node **p = &report->name_tree.rb_node;

	while (*p) {
		int cmp;

		parent = *p;
		node = rb_entry(parent, struct tui_report_node, name_link);

		cmp = strcmp(node->name, symname);
		if (cmp == 0)
			return node;

		if (cmp < 0)
			p = &parent->rb_left;
		else
			p = &parent->rb_right;
	}

	node = xzalloc(sizeof(*node));
	node->name = xstrdup(symname);
	INIT_LIST_HEAD(&node->head);

	rb_link_node(&node->name_link, parent, p);
	rb_insert_color(&node->name_link, &report->name_tree);
	report->nr_func++;

	return node;
}

static void prepare_report_node(struct tui_report_node *node)
{
	struct tui_graph_node *gn;

	list_for_each_entry(gn, &node->head, link) {
		node->time      += gn->n.time;
		node->self_time += gn->n.time - gn->n.child_time;
		node->calls     += gn->n.nr_calls;
	}

	node->time -= node->recursive_time;
}

static int cmp_report_node(struct tui_report_node *a, struct tui_report_node *b)
{
	/* TODO: apply sort key */
	if (a->time != b->time)
		return a->time > b->time ? 1 : -1;

	return 0;
}

static void sort_report_node(struct tui_report *report,
			     struct tui_report_node *node)
{
	struct tui_report_node *iter;
	struct rb_node *parent = NULL;
	struct rb_node **p = &report->sort_tree.rb_node;

	prepare_report_node(node);

	while (*p) {
		int cmp;

		parent = *p;
		iter = rb_entry(parent, struct tui_report_node, sort_link);

		cmp = cmp_report_node(iter, node);
		if (cmp < 0)
			p = &parent->rb_left;
		else
			p = &parent->rb_right;
	}

	rb_link_node(&node->sort_link, parent, p);
	rb_insert_color(&node->sort_link, &report->sort_tree);
}

static void sort_tui_report(struct tui_report *report)
{
	struct rb_node *node = rb_first(&report->name_tree);
	struct tui_report_node *tui_node;

	while (node) {
		tui_node = rb_entry(node, struct tui_report_node, name_link);
		sort_report_node(report, tui_node);

		node = rb_next(node);
	}
}

static bool list_is_none(struct list_head *list)
{
	return list->next == NULL && list->prev == NULL;
}

static void update_report_node(struct ftrace_task_handle *task, char *symname,
			       struct uftrace_task_graph *tg)
{
	struct fstack *fstack = &task->func_stack[task->stack_count];
	uint64_t total_time = fstack->total_time;
	uint64_t self_time = fstack->total_time - fstack->child_time;
	struct tui_report_node *node;
	struct tui_graph_node *graph_node;
	int i;

	node = find_report_node(&tui_report, symname);

	graph_node = (struct tui_graph_node *)tg->node;
	if (list_is_none(&graph_node->link))
		list_add_tail(&graph_node->link, &node->head);

	if (node->max_time < total_time)
		node->max_time = total_time;
	if (node->min_time == 0 || node->min_time > total_time)
		node->min_time = total_time;
	if (node->max_self_time < self_time)
		node->max_self_time = self_time;
	if (node->min_self_time == 0 || node->min_self_time > self_time)
		node->min_self_time = self_time;

	for (i = 0; i < task->stack_count; i++) {
		if (task->func_stack[i].addr == fstack->addr) {
			node->recursive_time += total_time;
			break;
		}
	}
}

static int build_tui_node(struct ftrace_task_handle *task,
			  struct uftrace_record *rec)
{
	struct uftrace_task_graph *tg;
	struct uftrace_graph *graph;
	struct tui_graph_node *graph_node;
	struct sym *sym;
	char *name;

	tg = graph_get_task(task, sizeof(*tg));
	graph = get_graph(task, rec->time, rec->addr);

	if (tg->node == NULL || tg->graph != graph)
		tg->node = &graph->root;

	tg->graph = graph;

	if (rec->type == UFTRACE_ENTRY || rec->type == UFTRACE_EXIT) {
		sym = task_find_sym_addr(&task->h->sessions,
					 task, rec->time, rec->addr);
		name = symbol_getname(sym, rec->addr);

		if (rec->type == UFTRACE_EXIT)
			update_report_node(task, name, tg);
	}
	else if (rec->type == UFTRACE_EVENT) {
		sym = &sched_sym;
		name = symbol_getname(sym, rec->addr);

		if (rec->addr == EVENT_ID_PERF_SCHED_IN)
			update_report_node(task, name, tg);
		else if (rec->addr != EVENT_ID_PERF_SCHED_OUT)
			return 0;
	}
	else  /* rec->type == UFTRACE_LOST */
		return 0;

	graph_add_node(tg, rec->type, name, sizeof(struct tui_graph_node));
	if (tg->node && tg->node != &graph->root) {
		graph_node = (struct tui_graph_node *)tg->node;
		graph_node->graph = graph;
	}

	symbol_putname(sym, name);
	return 0;
}

static void add_remaining_node(struct opts *opts, struct ftrace_file_handle *handle)
{
	uint64_t last_time;
	struct fstack *fstack;
	struct ftrace_task_handle *task;
	struct uftrace_task_graph *tg;
	struct sym *sym;
	char *name;
	int i;

	for (i = 0; i < handle->nr_tasks; i++) {
		task = &handle->tasks[i];

		if (task->stack_count == 0)
			continue;

		if (opts->kernel_skip_out && task->user_stack_count == 0)
			continue;

		last_time = task->rstack->time;

		if (handle->time_range.stop)
			last_time = handle->time_range.stop;

		while (--task->stack_count >= 0) {
			fstack = &task->func_stack[task->stack_count];

			if (fstack->addr == 0)
				continue;

			if (fstack->total_time > last_time)
				continue;

			tg = graph_get_task(task, sizeof(*tg));
			sym = task_find_sym_addr(&handle->sessions,
						 task, fstack->total_time,
						 fstack->addr);
			name = symbol_getname(sym, fstack->addr);

			fstack->total_time = last_time - fstack->total_time;
			if (fstack->child_time > fstack->total_time)
				fstack->total_time = fstack->child_time;

			if (task->stack_count > 0)
				fstack[-1].child_time += fstack->total_time;

			update_report_node(task, name, tg);
			graph_add_node(tg, UFTRACE_EXIT, name,
				       sizeof(struct tui_graph_node));

			symbol_putname(sym, name);
		}
	}
}

static struct tui_graph_node * append_graph_node(struct uftrace_graph_node *dst,
						 struct tui_graph *graph,
						 char *name)
{
	struct tui_graph_node *node;

	node = xzalloc(sizeof(*node));

	node->n.name = xstrdup(name);
	INIT_LIST_HEAD(&node->n.head);

	node->n.parent = dst;
	node->graph = &graph->ug;
	list_add_tail(&node->n.list, &dst->head);
	dst->nr_edges++;

	return node;
}

static void copy_graph_node(struct uftrace_graph_node *dst,
			    struct uftrace_graph_node *src)
{
	struct uftrace_graph_node *child;
	struct tui_graph_node *node;

	list_for_each_entry(child, &src->head, list) {
		list_for_each_entry(node, &dst->head, n.list) {
			if (!strcmp(child->name, node->n.name))
				break;
		}

		if (list_no_entry(node, &dst->head, n.list)) {
			struct tui_graph *graph;

			node = (struct tui_graph_node *)src;
			graph = container_of(node->graph, typeof(*graph), ug);

			node = append_graph_node(dst, graph,
						 child->name);
		}

		node->n.addr        = child->addr;
		node->n.time       += child->time;
		node->n.child_time += child->child_time;
		node->n.nr_calls   += child->nr_calls;

		copy_graph_node(&node->n, child);
	}
}

static void tui_window_init(struct tui_window *win,
			    const struct tui_window_ops *ops)
{
	void *top = ops->top(win, true);

	win->ops = ops;
	win->top = top;
	win->curr = win->old = top;
	win->top_index = win->curr_index = 0;
}

static struct tui_graph * tui_graph_init(struct opts *opts)
{
	struct tui_graph *graph;
	struct uftrace_graph_node *top, *node;

	list_for_each_entry(graph, &tui_graph_list, list) {
		/* top (root) is an artificial node, fill the info */
		top = &graph->ug.root;
		top->name = basename(graph->ug.sess->exename);
		top->nr_calls = 1;

		list_for_each_entry(node, &graph->ug.root.head, list) {
			top->time       += node->time;
			top->child_time += node->time;
		}

		tui_window_init(&graph->win, &graph_ops);

		graph->mask_size = sizeof(*graph->top_mask) * opts->max_stack;

		graph->top_mask  = xzalloc(graph->mask_size);
		graph->disp_mask = xmalloc(graph->mask_size);
	}

	graph = list_first_entry(&tui_graph_list, typeof(*graph), list);

	partial_graph.mask_size = graph->mask_size;
	partial_graph.top_mask  = xzalloc(graph->mask_size);
	partial_graph.disp_mask = xmalloc(graph->mask_size);

	tui_window_init(&partial_graph.win, &graph_ops);

	INIT_LIST_HEAD(&partial_graph.ug.root.head);
	INIT_LIST_HEAD(&partial_graph.ug.special_nodes);

	/* select first session */
	partial_graph.ug.sess = graph->ug.sess;

	return graph;
}

static void tui_graph_finish(void)
{
	struct tui_graph *graph;

	list_for_each_entry(graph, &tui_graph_list, list) {
		graph_destroy(&graph->ug);
		free(graph->top_mask);
		free(graph->disp_mask);
	}

	graph_destroy(&partial_graph.ug);
	free(partial_graph.top_mask);
	free(partial_graph.disp_mask);
}

static void build_partial_graph(struct tui_report_node *root_node,
				struct tui_graph *target)
{
	struct tui_graph *graph = &partial_graph;
	struct tui_graph_node *root, *node;
	char *str;

	graph_destroy(&graph->ug);

	graph->ug.sess = target->ug.sess;

	xasprintf(&str, "=== Function Call Graph for '%s' ===", root_node->name);

	root = (struct tui_graph_node*) &graph->ug.root;
	root->n.name = str;
	root->n.parent = NULL;

	root->n.time       = 0;
	root->n.child_time = 0;
	root->n.nr_calls   = 0;

	/* special node */
	root = append_graph_node(&graph->ug.root, target,
				 "========== Back-trace ==========");

	list_for_each_entry(node, &root_node->head, link) {
		struct tui_graph_node *tmp, *parent;
		int n = 0;

		if (node->graph != &target->ug)
			continue;

		tmp = root;
		parent = node;

		while (parent->n.parent) {
			tmp = append_graph_node(&tmp->n, target, parent->n.name);

			tmp->n.addr       = parent->n.addr;
			tmp->n.time       = node->n.time;
			tmp->n.child_time = node->n.child_time;
			tmp->n.nr_calls   = node->n.nr_calls;

			/* fold backtrace at the first child */
			if (n++ == 1)
				tmp->folded = true;

			parent = (void *)parent->n.parent;
		}

		/* but, unfoled it if it's the last child */
		if (n == 2)
			tmp->folded = false;
	}

	/* special node */
	root = append_graph_node(&graph->ug.root, target,
				 "========== Call Graph ==========");

	root = append_graph_node(&root->n, target, root_node->name);

	list_for_each_entry(node, &root_node->head, link) {
		if (node->graph != &target->ug)
			continue;

		root->n.addr        = node->n.addr;
		root->n.time       += node->n.time;
		root->n.child_time += node->n.child_time;
		root->n.nr_calls   += node->n.nr_calls;

		copy_graph_node(&root->n, &node->n);
	}

	tui_window_init(&graph->win, &graph_ops);

	memset(graph->top_mask, 0, graph->mask_size);
}

static inline bool is_special_node(struct uftrace_graph_node *node)
{
	return node->name[0] == '=';
}

static struct tui_graph_node * graph_prev_node(struct tui_graph_node *node,
					       int *depth, bool *indent_mask)
{
	struct uftrace_graph_node *n = &node->n;
	struct tui_graph_node *parent = (void *)n->parent;

	/* root node */
	if (parent == NULL) {
		*depth = 0;
		return NULL;
	}

	/* simple case: if it's the first child, move to the parent */
	if (is_first_child(parent, node)) {
		if (!list_is_singular(&n->parent->head) && *depth > 0) {
			*depth -= 1;
			if (indent_mask)
				indent_mask[*depth] = false;
		}
		n = n->parent;
		goto out;
	}

	/* move to sibling */
	n = list_prev_entry(n, list);
	node = (struct tui_graph_node *)n;

	/* if it has children, move to the last child */
	while (!list_empty(&n->head) && !node->folded) {
		if (!list_is_singular(&n->head)) {
			if (indent_mask)
				indent_mask[*depth] = false;
			*depth += 1;
		}

		n = list_last_entry(&n->head, typeof(*n), list);
		node = (struct tui_graph_node *)n;
	}

out:
	if (n->parent && !list_is_singular(&n->parent->head)) {
		if (indent_mask && *depth > 0)
			indent_mask[*depth - 1] = true;
	}

	return (struct tui_graph_node *)n;
}

static struct tui_graph_node * graph_next_node(struct tui_graph_node *node,
					       int *depth, bool *indent_mask)
{
	struct uftrace_graph_node *n = &node->n;
	struct tui_graph_node *parent = (void *)n->parent;

	if (parent && !list_is_singular(&n->parent->head) &&
	    is_last_child(parent, node) && indent_mask && *depth > 0)
		indent_mask[*depth - 1] = false;

	/* simple case: if it has children, move to it */
	if (!list_empty(&n->head) && (parent == NULL || !node->folded)) {
		if (!list_is_singular(&n->head)) {
			if (indent_mask)
				indent_mask[*depth] = true;
			*depth += 1;
		}

		n = list_first_entry(&n->head, typeof(*n), list);

		if (is_special_node(n))
			*depth = 0;
		return (struct tui_graph_node *)n;
	}

	/* parent should not be folded */
	while (n->parent != NULL) {
		parent = (struct tui_graph_node *)n->parent;

		/* move to sibling if possible */
		if (!is_last_child(parent, (void *)n)) {
			n = list_next_entry(n, list);

			if (is_special_node(n))
				*depth = 0;
			return (struct tui_graph_node *)n;
		}

		/* otherwise look up parent */
		n = n->parent;
		if (!list_is_singular(&n->head) && *depth > 0) {
			*depth -= 1;
			if (indent_mask)
				indent_mask[*depth] = false;
		}
	}

	return NULL;
}

/* per-window operations for graph window */
static void * win_top_graph(struct tui_window *win, bool update)
{
	struct tui_graph *graph = (struct tui_graph *)win;

	if (update)
		graph->top_depth = 0;

	return &graph->ug.root;
}

static void * win_prev_graph(struct tui_window *win, void *node, bool update)
{
	void *prev;
	int depth;
	struct tui_graph *graph = (struct tui_graph *)win;

	if (update)
		prev = graph_prev_node(node, &graph->top_depth, graph->top_mask);
	else
		prev = graph_prev_node(node, &depth, NULL);

	return prev;
}

static void * win_next_graph(struct tui_window *win, void *node, bool update)
{
	void *next;
	int depth;
	struct tui_graph *graph = (struct tui_graph *)win;

	if (update) {
		/* update top node for new page */
		next = graph_next_node(node, &graph->top_depth, graph->top_mask);
	}
	else if (graph->disp_update) {
		/* update display node for next */
		next = graph_next_node(node, &graph->disp_depth,
				       graph->disp_mask);
		graph->disp = next;
	}
	else {
		next = graph_next_node(node, &depth, NULL);
	}

	return next;
}

static bool win_needs_blank_graph(struct tui_window *win, void *prev, void *next)
{
	return !is_first_child(prev, next);
}

static void * win_sibling_prev_graph(struct tui_window *win, void *node)
{
	struct uftrace_graph_node *curr = node;
	struct uftrace_graph_node *parent = curr->parent;

	if (parent == NULL)
		return NULL;

	if (list_first_entry(&parent->head, typeof(*curr), list) == curr)
		return NULL;

	return list_prev_entry(curr, list);
}

static void * win_sibling_next_graph(struct tui_window *win, void *node)
{
	struct uftrace_graph_node *curr = node;
	struct uftrace_graph_node *parent = curr->parent;

	if (parent == NULL)
		return NULL;

	if (list_last_entry(&parent->head, typeof(*curr), list) == curr)
		return NULL;

	return list_next_entry(curr, list);
}

static void * win_parent_graph(struct tui_window *win, void *node)
{
	struct uftrace_graph_node *curr = node;

	return curr->parent;
}

static bool win_enter_graph(struct tui_window *win, void *node)
{
	struct tui_graph_node *curr = node;

	/* root node is not foldable */
	if (curr->n.parent == NULL)
		return false;

	if (list_empty(&curr->n.head))
		return false;

	curr->folded = !curr->folded;
	return true;
}

static int fold_graph_node(struct tui_graph_node *node, bool fold, int depth)
{
	struct tui_graph_node *child;
	int count = 0;
	bool curr_fold = fold;

	if (depth < 0)
		return 0;
	else if (depth > 0)
		curr_fold = false;

	/* do not fold leaf nodes - it's meaningless but confusing */
	if (list_empty(&node->n.head))
		return 0;

	if (node->folded != curr_fold) {
		node->folded = curr_fold;
		count++;
	}

	list_for_each_entry(child, &node->n.head, n.list)
		count += fold_graph_node(child, fold, depth - 1);

	return count;
}

static bool win_collapse_graph(struct tui_window *win, void *node, int depth)
{
	return fold_graph_node(node, true, depth);
}

static bool win_expand_graph(struct tui_window *win, void *node, int depth)
{
	return fold_graph_node(node, false, depth);
}

static void win_header_graph(struct tui_window *win,
			     struct ftrace_file_handle *handle)
{
	int w = 0, c;
	char *buf, *p;
	struct tui_graph *graph = (struct tui_graph *)win;
	struct display_field *field;

	/* calculate width for fields */
	list_for_each_entry(field, &graph_output_fields, list) {
		w += field->length + FIELD_SPACE;
	}
	if (!list_empty(&graph_output_fields))
		w += strlen(FIELD_SEP);

	graph->width = w;

	w += strlen(" FUNCTION");

	if (list_empty(&graph_output_fields)) {
		printw("%-*.*s", COLS, COLS, "uftrace graph TUI");
		return;
	}

	buf = p = xmalloc(w + 1);

	list_for_each_entry(field, &graph_output_fields, list) {
		c = snprintf(p, w, "%*s%*s", FIELD_SPACE, "",
			     field->length, field->header);
		p += c;
		w -= c;
	}
	snprintf(p, w+1, "%s %s", FIELD_SEP, "FUNCTION");

	printw("%-*.*s", COLS, COLS, buf);
	free(buf);

	/* start with same make as top */
	graph->disp = graph->win.top;
	graph->disp_depth = graph->top_depth;
	graph->disp_update = true;
	memcpy(graph->disp_mask, graph->top_mask, graph->mask_size);
}

static void win_footer_graph(struct tui_window *win,
			     struct ftrace_file_handle *handle)
{
	char buf[COLS + 1];
	struct tui_graph *graph = (struct tui_graph *)win;
	struct tui_graph_node *node = win->curr;
	struct uftrace_session *sess = graph->ug.sess;

	if (tui_debug) {
		snprintf(buf, COLS, "uftrace graph: top: %d depth: %d, curr: %d depth: %d",
			 graph->win.top_index, graph->top_depth,
			 graph->win.curr_index, graph->curr_depth);
	}
	else if (tui_search) {
		snprintf(buf, COLS, "uftrace graph: searching \"%s\"  (%d match, %s)",
			 tui_search, graph->win.search_count,
			 "use '<' and '>' keys to navigate");
	}
	else {
		struct debug_location *dloc;

		dloc = win->ops->location(win, win->curr);

		if (dloc != NULL && dloc->file != NULL) {
			snprintf(buf, COLS, "uftrace graph: %s [line:%d]",
				 dloc->file->name, dloc->line);
		}
		else if (find_symtabs(&sess->symtabs, node->n.addr) != NULL) {
			/* some symbols don't have source location */
			snprintf(buf, COLS, "uftrace graph: %s [at %#"PRIx64"]",
				 "source location is not available",
				 node->n.addr);
		}
		else {
			snprintf(buf, COLS, "uftrace graph: session %.*s (%s)",
				 SESSION_ID_LEN, sess->sid, sess->exename);
		}
	}
	buf[COLS] = '\0';

	printw("%-*s", COLS, buf);

	graph->disp_update = false;
}

static void print_graph_field(struct uftrace_graph_node *node)
{
	struct display_field *field;
	struct field_data fd = {
		.arg = node,
	};

	if (list_empty(&graph_output_fields))
		return;

	list_for_each_entry(field, &graph_output_fields, list) {
		printw("%*s", FIELD_SPACE, "");
		field->print(&fd);
	}
	printw(FIELD_SEP);
}

static void print_graph_empty(void)
{
	struct display_field *field;

	if (list_empty(&graph_output_fields))
		return;

	list_for_each_entry(field, &graph_output_fields, list)
		printw("%*s", field->length + FIELD_SPACE, "");

	printw(FIELD_SEP);
}

static void print_graph_indent(struct tui_graph *graph,
			       struct tui_graph_node *node,
			       int depth, bool single_child)
{
	int i;
	struct tui_graph_node *parent = (void *)node->n.parent;

	for (i = 0; i < depth; i++) {
		if (!graph->disp_mask[i]) {
			printw("   ");
			continue;
		}

		if (i < depth - 1 || single_child)
			printw("  │");
		else if (is_last_child(parent, node))
			printw("  â””");
		else
			printw("  ├");
	}
}

static void win_display_graph(struct tui_window *win, void *node)
{
	struct tui_graph *graph = (struct tui_graph *)win;
	struct tui_graph_node *curr = node;
	struct tui_graph_node *parent;
	int d = graph->disp_depth;
	int w = graph->width;
	const char *fold_sign;
	bool single_child = false;
	int width;

	if (node == NULL) {
		print_graph_empty();
		print_graph_indent(graph, graph->disp, d, true);
		return;
	}

	fold_sign = curr->folded ? "▶" : "─";

	parent = win_parent_graph(win, node);
	if (parent == NULL)
		fold_sign = " ";
	else if (list_is_singular(&parent->n.head)) {
		single_child = true;
		if (!curr->folded)
			fold_sign = " ";
	}

	print_graph_field(&curr->n);
	print_graph_indent(graph, curr, d, single_child);

	width = d * 3 + w;

	if (is_special_node(&curr->n)) {
		width = COLS - width;
		if (width > 0)
			printw("%-*.*s", width, width, curr->n.name);
	}
	else {
		char buf[32];

		/* 4 = fold_sign(1) + parenthesis92) + space(1) */
		width += snprintf(buf, sizeof(buf),
				  "%d", curr->n.nr_calls) + 4;
		width = COLS - width;

		if (width > 0) {
			printw("%s(%d) %-*.*s", fold_sign, curr->n.nr_calls,
			       width, width, curr->n.name);
		}
	}
}

static bool win_search_graph(struct tui_window *win, void *node, char *str)
{
	struct tui_graph_node *curr = node;

	return strstr(curr->n.name, str);
}

static bool win_longest_child_graph(struct tui_window *win, void *node)
{
	struct tui_graph_node *curr = node;
	struct tui_graph_node *child;
	struct tui_graph_node *longest_child = NULL;
	uint64_t longest_child_time = 0;

	curr->folded = false;

	list_for_each_entry(child, &curr->n.head, n.list) {
		fold_graph_node(child, true, 0);
		if (longest_child_time < child->n.time) {
			longest_child_time = child->n.time;
			longest_child = child;
		}
	}

	if (longest_child == NULL)
		return false;

	longest_child->folded = false;
	while (win->curr != longest_child)
		tui_window_move_down(win);

	return true;
}

static struct debug_location *win_location_graph(struct tui_window *win,
						 void *node)
{
	struct tui_graph *graph = (struct tui_graph *)win;
	struct tui_graph_node *curr = node;
	struct uftrace_session *sess = graph->ug.sess;

	return find_file_line(&sess->symtabs, curr->n.addr);
}

static const struct tui_window_ops graph_ops = {
	.prev = win_prev_graph,
	.next = win_next_graph,
	.top = win_top_graph,
	.parent = win_parent_graph,
	.sibling_prev = win_sibling_prev_graph,
	.sibling_next = win_sibling_next_graph,
	.needs_blank = win_needs_blank_graph,
	.enter = win_enter_graph,
	.collapse = win_collapse_graph,
	.expand = win_expand_graph,
	.header = win_header_graph,
	.footer = win_footer_graph,
	.display = win_display_graph,
	.search = win_search_graph,
	.longest_child = win_longest_child_graph,
	.location = win_location_graph,
};

/* some default (no-op) window operations */
static bool win_needs_blank_no(struct tui_window *win, void *prev, void *next)
{
	return false;
}

static void * win_sibling_prev_no(struct tui_window *win, void *node)
{
	return win->ops->prev(win, node, false);
}

static void * win_sibling_next_no(struct tui_window *win, void *node)
{
	return win->ops->next(win, node, false);
}

static void * win_parent_no(struct tui_window *win, void *node)
{
	return NULL;
}

/* per-window operations for report window */
static struct tui_report * tui_report_init(struct opts *opts)
{
	struct tui_window *win = &tui_report.win;

	sort_tui_report(&tui_report);
	tui_window_init(win, &report_ops);

	return &tui_report;
}

static void tui_report_finish(void)
{
}

static void * win_top_report(struct tui_window *win, bool update)
{
	struct tui_report *report = (struct tui_report *)win;
	struct rb_node *node = rb_first(&report->sort_tree);

	return rb_entry(node, struct tui_report_node, sort_link);
}

static void * win_prev_report(struct tui_window *win, void *node, bool update)
{
	struct tui_report_node *curr = node;
	struct rb_node *rbnode = rb_prev(&curr->sort_link);

	if (rbnode == NULL)
		return NULL;

	return rb_entry(rbnode, struct tui_report_node, sort_link);
}

static void * win_next_report(struct tui_window *win, void *node, bool update)
{
	struct tui_report_node *curr = node;
	struct rb_node *rbnode = rb_next(&curr->sort_link);

	if (rbnode == NULL)
		return NULL;

	return rb_entry(rbnode, struct tui_report_node, sort_link);
}

static bool win_search_report(struct tui_window *win, void *node, char *str)
{
	struct tui_report_node *curr = node;

	return strstr(curr->name, str);
}

static void win_header_report(struct tui_window *win, struct ftrace_file_handle *handle)
{
	int w = 46;

	printw("  %10s  %10s  %10s  %s", "Total Time", "Self Time", "Calls", "Function");
	if (COLS > w)
		printw("%*s", COLS - w, "");
}

static void win_footer_report(struct tui_window *win, struct ftrace_file_handle *handle)
{
	char buf[COLS + 1];

	if (tui_debug) {
		snprintf(buf, COLS, "uftrace report: top: %d, curr: %d",
			 win->top_index, win->curr_index);
	}
	else if (tui_search) {
		snprintf(buf, COLS, "uftrace report: searching \"%s\"  (%d match, %s)",
			 tui_search, win->search_count, "use '<' and '>' keys to navigate");
	}
	else {
		struct tui_report *report = (struct tui_report *)win;

		snprintf(buf, COLS, "uftrace report: %s (%d sessions, %d functions)",
			 handle->dirname, report->nr_sess, report->nr_func);
	}
	buf[COLS] = '\0';

	printw("%-*.*s", COLS, COLS, buf);
}

static void win_display_report(struct tui_window *win, void *node)
{
	struct tui_report_node *curr = node;
	int width = 38;  /* 3 output fields and spaces */

	printw("  ");
	print_time(curr->time);
	printw("  ");
	print_time(curr->self_time);
	printw("  ");
	printw("%10u", curr->calls);
	printw("  ");

	printw("%-*.*s", COLS - width, COLS - width, curr->name);
}

static struct debug_location *win_location_report(struct tui_window *win,
						  void *node)
{
	struct tui_report_node *curr = node;
	struct tui_graph_node *gnode;
	struct uftrace_session *sess;
	struct debug_location *dloc;

	list_for_each_entry(gnode, &curr->head, link) {
		sess = gnode->graph->sess;
		dloc = find_file_line(&sess->symtabs, gnode->n.addr);

		if (dloc != NULL && dloc->file != NULL)
			return dloc;
	}
	return NULL;
}

static const struct tui_window_ops report_ops = {
	.prev = win_prev_report,
	.next = win_next_report,
	.top = win_top_report,
	.parent = win_parent_no,
	.sibling_prev = win_sibling_prev_no,
	.sibling_next = win_sibling_next_no,
	.needs_blank = win_needs_blank_no,
	.header = win_header_report,
	.footer = win_footer_report,
	.display = win_display_report,
	.search = win_search_report,
	.location = win_location_report,
};

/* per-window operations for list window */
static void * win_top_list(struct tui_window *win, bool update)
{
	struct tui_list *list = (struct tui_list *)win;

	return list_first_entry(&list->head, struct tui_list_node, list);
}

static void * win_prev_list(struct tui_window *win, void *node, bool update)
{
	struct tui_list *list = (struct tui_list *)win;

	if (list_first_entry(&list->head, struct tui_list_node, list) == node)
		return NULL;

	return list_prev_entry((struct tui_list_node *)node, list);
}

static void * win_next_list(struct tui_window *win, void *node, bool update)
{
	struct tui_list *list = (struct tui_list *)win;

	if (list_last_entry(&list->head, struct tui_list_node, list) == node)
		return NULL;

	return list_next_entry((struct tui_list_node *)node, list);
}

/* per-window operations for info window */
static void build_info_node(void *data, const char *fmt, ...)
{
	va_list ap;
	struct tui_list *info = data;
	struct tui_list_node *node;
	char *str = NULL;

	node = xmalloc(sizeof(*node));

	va_start(ap, fmt);
	xvasprintf(&str, fmt, ap);
	va_end(ap);

	/* remove trailing newline */
	str[strlen(str) - 1] = '\0';

	node->data = str;
	list_add_tail(&node->list, &info->head);
}

static struct tui_list * tui_info_init(struct opts *opts,
				       struct ftrace_file_handle *handle)
{
	INIT_LIST_HEAD(&tui_info.head);
	process_uftrace_info(handle, opts, build_info_node, &tui_info);

	tui_window_init(&tui_info.win, &info_ops);
			
	return &tui_info;
}

static void tui_info_finish(void)
{
	struct tui_list_node *node, *tmp;

	list_for_each_entry_safe(node, tmp, &tui_info.head, list) {
		list_del(&node->list);
		free(node->data);
		free(node);
	}
}

static void win_header_info(struct tui_window *win,
			    struct ftrace_file_handle *handle)
{

	printw("%-*.*s", COLS, COLS, "uftrace info");
}

#define print_buf(fmt, ...)						\
	({ int _x = snprintf(buf + len, sz - len, fmt, ## __VA_ARGS__); len += _x; })

static void win_footer_info(struct tui_window *win,
			    struct ftrace_file_handle *handle)
{
	char buf[256];
	size_t sz = sizeof(buf);
	int len = 0;

	print_buf("uftrace version: %s (+", UFTRACE_VERSION);

#ifdef HAVE_CXA_DEMANGLE
	print_buf(" demangle");
#endif

#ifdef HAVE_LIBPYTHON2
	print_buf(" python");
#endif

#ifdef HAVE_PERF_CLOCKID
	print_buf(" perf");
#endif

#ifdef HAVE_LIBNCURSES
	print_buf(" ncurses");
#endif

	if (unlikely(len == 0))
		print_buf(" none");

	print_buf(" )");

	printw("%-*.*s", COLS, COLS, buf);
}

static void win_display_info(struct tui_window *win, void *node)
{
	struct tui_list_node *curr = node;

	printw("%-*.*s", COLS, COLS, curr->data);
}

static const struct tui_window_ops info_ops = {
	.prev = win_prev_list,
	.next = win_next_list,
	.top = win_top_list,
	.parent = win_parent_no,
	.sibling_prev = win_sibling_prev_no,
	.sibling_next = win_sibling_next_no,
	.needs_blank = win_needs_blank_no,
	.header = win_header_info,
	.footer = win_footer_info,
	.display = win_display_info,
};

#define TUI_SESS_REPORT    1
#define TUI_SESS_INFO      2
#define TUI_SESS_HELP      3
#define TUI_SESS_QUIT      4
#define TUI_SESS_DUMMY_NR  4

/* per-window operations for session window */
static struct tui_list * tui_session_init(struct opts *opts)
{
	struct tui_graph *graph;
	struct tui_list_node *node;
	int i;

	INIT_LIST_HEAD(&tui_session.head);
	tui_session.nr_node = 0;

	list_for_each_entry(graph, &tui_graph_list, list) {
		node = xmalloc(sizeof(*node));

		node->data = graph->ug.sess;
		list_add_tail(&node->list, &tui_session.head);
		tui_session.nr_node++;
	}

	for (i = 1; i <= TUI_SESS_DUMMY_NR; i++) {
		node = xmalloc(sizeof(*node));
		node->data = (void *)(long)i;
		list_add_tail(&node->list, &tui_session.head);
	}

	tui_window_init(&tui_session.win, &session_ops);

	return &tui_session;
}

static void tui_session_finish(void)
{
	struct tui_list_node *node, *tmp;

	list_for_each_entry_safe(node, tmp, &tui_session.head, list) {
		list_del(&node->list);
		free(node);
	}
}

static void win_header_session(struct tui_window *win,
			       struct ftrace_file_handle *handle)
{
	printw("%s %-*s", "Key", COLS - 4, "uftrace command");
}

static void win_footer_session(struct tui_window *win,
			       struct ftrace_file_handle *handle)
{
	char buf[256];
	struct tui_list *s_list = (struct tui_list *)win;
	struct tui_list_node *node = win->curr;
	struct uftrace_session *s = node->data;

	switch ((long)node->data) {
	case TUI_SESS_REPORT:
	case TUI_SESS_INFO:
	case TUI_SESS_HELP:
	case TUI_SESS_QUIT:
		snprintf(buf, sizeof(buf), "uftrace: %d session(s)",
			 s_list->nr_node);
		break;
	default:
		snprintf(buf, sizeof(buf), "session %.*s:  exe image: %s",
			 SESSION_ID_LEN, s->sid, s->exename);
		break;
	}

	printw("%-*s", COLS, buf);
}

static struct tui_graph * get_current_graph(struct tui_list_node *node,
					    int *count)
{
	struct tui_graph *graph;
	int n = 1;

	list_for_each_entry(graph, &tui_graph_list, list) {
		if (graph->ug.sess == node->data) {
			if (count)
				*count = n;
			return graph;
		}
		n++;
	}

	if (count)
		*count = 0;
	return NULL;
}

static void win_display_session(struct tui_window *win, void *node)
{
	int len = 0;
	char buf[1024];
	size_t sz = sizeof(buf);
	struct tui_list_node *curr = node;
	struct uftrace_session *s = curr->data;
	struct uftrace_session *curr_sess = NULL;
	int count = 0;

	switch ((long)s) {
	case TUI_SESS_REPORT:
		print_buf(" R  Report functions");
		break;
	case TUI_SESS_INFO:
		print_buf(" I  uftrace Info");
		break;
	case TUI_SESS_HELP:
		print_buf(" h  Help message");
		break;
	case TUI_SESS_QUIT:
		print_buf(" q  quit");
		break;
	default:
		curr_sess = partial_graph.ug.sess;
		get_current_graph(node, &count);
		print_buf(" %c  %s #%d: %s", s == curr_sess ? 'G' : ' ',
			  "call Graph for session", count,
			  basename(s->exename));
		break;
	}

	printw("%-*.*s", COLS, COLS, buf);
}

static bool win_enter_session(struct tui_window *win, void *node)
{
	/* update partial graph for different session */
	struct tui_list_node *curr = node;
	struct uftrace_session *old = partial_graph.ug.sess;
	struct uftrace_session *new = curr->data;
	struct uftrace_graph_node *ugnode;
	struct tui_report_node *func;

	if ((unsigned long)curr->data <= TUI_SESS_DUMMY_NR)
		return true;

	if (old == new)
		return false;

	partial_graph.ug.sess = curr->data;

	/* get root node */
	ugnode = &partial_graph.ug.root;
	if (list_empty(&ugnode->head))
		return true;

	/* get function call node */
	ugnode = list_last_entry(&ugnode->head, typeof(*ugnode), list);
	/* get first child (= actual function) */
	ugnode = list_first_entry(&ugnode->head, typeof(*ugnode), list);

	func = find_report_node(&tui_report, ugnode->name);

	build_partial_graph(func, get_current_graph(node, NULL));
	return true;
}

static const struct tui_window_ops session_ops = {
	.prev = win_prev_list,
	.next = win_next_list,
	.top = win_top_list,
	.parent = win_parent_no,
	.sibling_prev = win_sibling_prev_no,
	.sibling_next = win_sibling_next_no,
	.needs_blank = win_needs_blank_no,
	.enter = win_enter_session,
	.header = win_header_session,
	.footer = win_footer_session,
	.display = win_display_session,
};

/* common window operations */
static void tui_window_move_up(struct tui_window *win)
{
	void *node;

	node = win->ops->prev(win, win->curr, false);
	if (node == NULL)
		return;
	win->curr_index--;

	if (win->ops->needs_blank(win, node, win->curr))
		win->curr_index--;

	if (win->curr_index < win->top_index) {
		win->top = win->ops->prev(win, win->top, true);
		win->top_index = win->curr_index;
	}
	win->curr = node;
}

static void tui_window_move_down(struct tui_window *win)
{
	void *node;

	node = win->ops->next(win, win->curr, false);
	if (node == NULL)
		return;
	win->curr_index++;

	if (win->ops->needs_blank(win, win->curr, node))
		win->curr_index++;

	win->curr = node;

	while (win->curr_index - win->top_index >= LINES - 2) {
		node = win->ops->next(win, win->top, true);
		win->top_index++;

		if (win->ops->needs_blank(win, win->top, node))
			win->top_index++;

		win->top = node;
	}
}

static void tui_window_page_up(struct tui_window *win)
{
	void *node;

	if (win->curr != win->top) {
		win->curr = win->top;
		win->curr_index = win->top_index;
		return;
	}

	while (win->top_index - win->curr_index < LINES - 2) {
		node = win->ops->prev(win, win->top, true);
		if (node == NULL)
			break;
		win->curr_index--;

		if (win->ops->needs_blank(win, node, win->top))
			win->curr_index--;

		win->top = node;
	}
	win->curr = win->top;
	win->top_index = win->curr_index;
}

static void tui_window_page_down(struct tui_window *win)
{
	int orig_index;
	int next_index;
	void *node;

	orig_index = win->top_index;
	next_index = win->curr_index;

	node = win->ops->next(win, win->curr, false);
	if (node == NULL)
		return;
	next_index++;

	if (win->ops->needs_blank(win, win->curr, node))
		next_index++;

	if (next_index - win->top_index >= LINES - 2) {
		/* we're already at the end of page - move to next page */
		orig_index = next_index;
	}

	do {
		/* move curr to the bottom from orig_index */
		win->curr = node;
		win->curr_index = next_index;

		node = win->ops->next(win, win->curr, false);
		if (node == NULL)
			break;
		next_index++;

		if (win->ops->needs_blank(win, win->curr, node))
			next_index++;
	}
	while (next_index - orig_index < LINES - 2);

	/* move top if page was moved */
	while (win->curr_index - win->top_index >= LINES - 2) {
		node = win->ops->next(win, win->top, true);
		win->top_index++;

		if (win->ops->needs_blank(win, win->top, node))
			win->top_index++;

		win->top = node;
	}
}

static void tui_window_move_home(struct tui_window *win)
{
	win->top = win->curr = win->ops->top(win, true);
	win->top_index = win->curr_index = 0;
}

static void tui_window_move_end(struct tui_window *win)
{
	void *node;

	/* move to the last node */
	while (true) {
		node = win->ops->next(win, win->curr, false);
		if (node == NULL)
			break;

		win->curr_index++;

		if (win->ops->needs_blank(win, win->curr, node))
			win->curr_index++;

		win->curr = node;
	}

	/* move top if page was moved */
	while (win->curr_index - win->top_index >= LINES - 2) {
		node = win->ops->next(win, win->top, true);
		win->top_index++;

		if (win->ops->needs_blank(win, win->top, node))
			win->top_index++;

		win->top = node;
	}
}

/* move to the previous sibling */
static bool tui_window_move_prev(struct tui_window *win)
{
	void *prev = win->ops->sibling_prev(win, win->curr);
	int count = 0;

	if (prev == NULL)
		return false;

	if (win->ops->collapse == NULL) {
		while (win->curr != prev)
			tui_window_move_up(win);
		return false;
	}

	/* fold the current node before moving to the previous sibling */
	count = win->ops->collapse(win, win->curr, 0);

	while (win->curr != prev)
		tui_window_move_up(win);

	/* collapse the current node after moving to the previous sibling */
	count += win->ops->collapse(win, win->curr, 1);

	return count;
}

/* move to the next sibling */
static bool tui_window_move_next(struct tui_window *win)
{
	void *next = win->ops->sibling_next(win, win->curr);
	int count = 0;

	if (next == NULL)
		return false;

	if (win->ops->collapse == NULL) {
		while (win->curr != next)
			tui_window_move_down(win);
		return false;
	}

	/* fold the current node before moving to the next sibling */
	count = win->ops->collapse(win, win->curr, 0);

	while (win->curr != next)
		tui_window_move_down(win);

	/* collapse the current node after moving to the next sibling */
	count += win->ops->collapse(win, win->curr, 1);

	return count;
}

static void tui_window_display(struct tui_window *win, bool full_redraw,
			       struct ftrace_file_handle *handle)
{
	int count;
	void *node = win->top;

	/* too small screen */
	if (LINES <= 2)
		return;

	move(0, 0);
	attron(COLOR_PAIR(C_HEADER) | A_BOLD);
	win->ops->header(win, handle);
	attroff(COLOR_PAIR(C_HEADER) | A_BOLD);

	for (count = 0; count < LINES - 2; count++) {
		void *next;

		if (!full_redraw && node != win->curr && node != win->old)
			goto next;

		if (node == win->curr)
			attron(A_REVERSE);

		move(count + 1, 0);
		win->ops->display(win, node);

		if (node == win->curr)
			attroff(A_REVERSE);

next:
		next = win->ops->next(win, node, false);
		if (next == NULL)
			break;

		if (win->ops->needs_blank(win, node, next)) {
			count++;
			move(count + 1, 0);
			win->ops->display(win, NULL);
		}

		node = next;
	}

	move(LINES - 1, 0);
	attron(COLOR_PAIR(C_HEADER) | A_BOLD);
	win->ops->footer(win, handle);
	attroff(COLOR_PAIR(C_HEADER) | A_BOLD);
}

static bool tui_window_can_search(struct tui_window *win)
{
	return win->ops->search != NULL;
}

static char * tui_search_start(void)
{
	WINDOW *win;
	int w = COLS / 2;
	int h = 8;
	char buf[512];
	int n = 0;
	char *str = NULL;
	struct tui_graph *graph;

	win = newwin(h, w, (LINES - h) / 2, (COLS - w) / 2);
	box(win, 0, 0);

	mvwprintw(win, 1, 1, "Search function:");
	mvwprintw(win, 2, 2, "(press ESC to exit)");
	wrefresh(win);

	wmove(win, 5, 3);
	wrefresh(win);
	buf[0] = '\0';

	while (true) {
		int k = wgetch(win);

		switch (k) {
		case KEY_ESCAPE:
			goto out;
		case KEY_BACKSPACE:
		case KEY_DC:
		case 127:
		case '\b':
			if (n > 0) {
				mvwprintw(win, 5, 3, "%*s", n, "");
				buf[--n] = '\0';
			}
			break;
		case KEY_ENTER:
		case '\n':
			str = xstrdup(buf);
			goto out;
		default:
			if (isprint(k))
				buf[n++] = k;
			buf[n] = '\0';
			break;
		}
		mvwprintw(win, 5, 3, "%-.*s", w - 5, buf);
		wmove(win, 5, 3 + n);
		wrefresh(win);
	}

out:
	list_for_each_entry(graph, &tui_graph_list, list)
		graph->win.search_count = -1;
	partial_graph.win.search_count = -1;
	tui_report.win.search_count = -1;

	delwin(win);
	return str;
}

static void tui_window_search_count(struct tui_window *win)
{
	void *node;

	if (tui_search == NULL || win->ops->search == NULL)
		return;

	if (win->search_count != -1)
		return;

	win->search_count = 0;

	node = win->ops->top(win, false);
	while (node) {
		if (win->ops->search(win, node, tui_search))
			win->search_count++;

		node = win->ops->next(win, node, false);
	}
}

static void tui_window_search_prev(struct tui_window *win)
{
	void *node = win->curr;

	if (tui_search == NULL || win->ops->search == NULL)
		return;

	while (true) {
		node = win->ops->prev(win, node, false);
		if (node == NULL)
			return;

		if (win->ops->search(win, node, tui_search))
			break;
	}

	while (win->curr != node)
		tui_window_move_up(win);
}

static void tui_window_search_next(struct tui_window *win)
{
	void *node = win->curr;

	if (tui_search == NULL || win->ops->search == NULL)
		return;

	while (true) {
		node = win->ops->next(win, node, false);
		if (node == NULL)
			return;

		if (win->ops->search(win, node, tui_search))
			break;
	}

	while (win->curr != node)
		tui_window_move_down(win);
}

static bool tui_window_change(struct tui_window *win,
			      struct tui_window *new_win)
{
	if (win == new_win)
		return false;

	tui_window_search_count(new_win);
	return true;
}

static bool tui_window_enter(struct tui_window *win,
			     struct tui_window *prev_win)
{
	if (win->ops->enter == NULL)
		return false;

	return win->ops->enter(win, win->curr);
}

static bool tui_window_collapse(struct tui_window *win)
{
	if (win->ops->collapse == NULL)
		return false;

	/* fold all the directly children */
	return win->ops->collapse(win, win->curr, 1);
}

static bool tui_window_expand(struct tui_window *win)
{
	if (win->ops->expand == NULL)
		return false;

	/* unfold all the directly children */
	return win->ops->expand(win, win->curr, 1);
}

static bool tui_window_move_parent(struct tui_window *win)
{
	void *parent = win->ops->parent(win, win->curr);

	if (parent == NULL)
		return false;

	while (win->curr != parent)
		tui_window_move_up(win);

	return tui_window_collapse(win);
}

static bool tui_window_longest_child(struct tui_window *win)
{
	if (win->ops->longest_child == NULL)
		return false;

	return win->ops->longest_child(win, win->curr);
}

static bool tui_window_open_editor(struct tui_window *win)
{
	struct debug_location *dloc;
	const char *editor = getenv("EDITOR");
	struct strv editor_strv;
	int pid, status;
	int ret;

	if (win->ops->location == NULL)
		return false;

	dloc = win->ops->location(win, win->curr);
	if (dloc == NULL || dloc->file == NULL)
		return false;

	/* can read file? */
	if (access(dloc->file->name, R_OK) < 0)
		return false;

	if (editor == NULL)
		editor = "vi";

	endwin();

	strv_split(&editor_strv, editor, " ");
	if (!strncmp(editor, "vi", 2) || !strncmp(editor, "emacs", 5)) {
		char buf[16];

		/* run 'vi +line file' */
		snprintf(buf, sizeof(buf), "+%d", dloc->line);
		strv_append(&editor_strv, buf);
		strv_append(&editor_strv, dloc->file->name);
	}
	else {
		/* I don't know what to do */
		strv_append(&editor_strv, dloc->file->name);
	}

	pid = fork();
	if (pid < 0) {
		int saved_errno = errno;

		endwin();

		errno = saved_errno;
		pr_err("forking editor failed");
	}

	if (pid == 0) {
		execvp(editor_strv.p[0], editor_strv.p);
		exit(1);
	}

	strv_free(&editor_strv);

	do {
		/* can return early by signal (e.g. SIGWINCH) */
		ret = waitpid(pid, &status, 0);
	}
	while (ret < 0 && errno == EINTR);

	refresh();
	return true;
}

static void tui_window_help(void)
{
	WINDOW *win;
	int w = 64;
	int h = ARRAY_SIZE(help) + 5;
	unsigned i;

	if (w > COLS)
		w = COLS;
	if (h > LINES)
		h = LINES;

	win = newwin(h, w, (LINES - h) / 2, (COLS - w) / 2);
	box(win, 0, 0);

	mvwprintw(win, 1, 1, "Help: (press any key to exit)");

	for (i = 0; i < ARRAY_SIZE(help); i++)
		mvwprintw(win, i + 3, 2, "%-*.*s", w-3, w-3, help[i]);

	mvwprintw(win, h-1, w-1, "");
	wrefresh(win);

	/* wait for key press */
	wgetch(win);

	delwin(win);
}

static void tui_main_loop(struct opts *opts, struct ftrace_file_handle *handle)
{
	int key = 0;
	bool full_redraw = true;
	struct tui_graph *graph;
	struct tui_report *report;
	struct tui_list *info;
	struct tui_list *session;
	struct tui_window *win;
	void *old_top;

	graph = tui_graph_init(opts);
	report = tui_report_init(opts);
	info = tui_info_init(opts, handle);
	session = tui_session_init(opts);

	/* start with graph only if there's one session */
	if (session->nr_node > 1)
		win = &session->win;
	else
		win = &graph->win;

	old_top = win->top;

	while (true) {
		switch (key) {
		case KEY_RESIZE:
			full_redraw = true;
			break;
		case KEY_UP:
		case 'k':
			tui_window_move_up(win);
			break;
		case KEY_DOWN:
		case 'j':
			tui_window_move_down(win);
			break;
		case KEY_PPAGE:
			tui_window_page_up(win);
			break;
		case KEY_NPAGE:
			tui_window_page_down(win);
			break;
		case KEY_HOME:
			tui_window_move_home(win);
			break;
		case KEY_END:
			tui_window_move_end(win);
			break;
		case KEY_ENTER:
		case '\n':
			full_redraw = tui_window_enter(win, win->curr);

			if (win == &session->win) {
				struct tui_list_node *cmd = win->curr;

				switch ((long)cmd->data) {
				case TUI_SESS_REPORT:
					win = &report->win;
					break;
				case TUI_SESS_INFO:
					win = &info->win;
					break;
				case TUI_SESS_HELP:
					tui_window_help();
					break;
				case TUI_SESS_QUIT:
					goto out;
				default:
					/* change window for the current graph */
					graph = get_current_graph(win->curr, NULL);
					win = &graph->win;
					break;
				}
			}
			break;
		case KEY_ESCAPE:
			free(tui_search);  /* cancel search */
			tui_search = NULL;
			break;
		case 'G':
			if (tui_window_change(win, &graph->win)) {
				/* full graph mode */
				win = &graph->win;
				full_redraw = true;
			}
			break;
		case 'g':
			if (win == &graph->win || win == &partial_graph.win) {
				struct tui_report_node *func;
				struct tui_graph_node *curr = win->curr;

				func = find_report_node(report, curr->n.name);
				build_partial_graph(func, graph);
			}
			else if (win == &report->win) {
				build_partial_graph(win->curr, graph);
			}

			win = &partial_graph.win;

			tui_window_move_home(win);
			tui_window_search_count(win);
			full_redraw = true;
			break;
		case 'R':
		case 'r':
			if (tui_window_change(win, &report->win)) {
				win = &report->win;
				full_redraw = true;
			}
			break;
		case 'I':
			if (tui_window_change(win, &info->win)) {
				win = &info->win;
				full_redraw = true;
			}
			break;
		case 'S':
			if (tui_window_change(win, &session->win)) {
				win = &session->win;
				full_redraw = true;
			}
			break;
		case 'O':
			full_redraw = tui_window_open_editor(win);
			break;
		case 'c':
			full_redraw = tui_window_collapse(win);
			break;
		case 'e':
			full_redraw = tui_window_expand(win);
			break;
		case 'p':
			full_redraw = tui_window_move_prev(win);
			break;
		case 'n':
			full_redraw = tui_window_move_next(win);
			break;
		case 'u':
			full_redraw = tui_window_move_parent(win);
			break;
		case 'l':
			full_redraw = tui_window_longest_child(win);
			break;
		case '/':
			if (tui_window_can_search(win)) {
				free(tui_search);
				tui_search = tui_search_start();
				tui_window_search_count(win);

				/* move to the next match if found */
				if (win->search_count > 0)
					tui_window_search_next(win);

				full_redraw = true;
			}
			break;
		case '<':
		case 'P':
			tui_window_search_prev(win);
			break;
		case '>':
		case 'N':
			tui_window_search_next(win);
			break;
		case 'v':
			tui_debug = !tui_debug;
			break;
		case 'h':
		case '?':
			tui_window_help();
			full_redraw = true;
			break;
		case 'q':
			goto out;
		default:
			break;
		}

		if (win->top != old_top)
			full_redraw = true;

		if (full_redraw)
			clear();

		tui_window_display(win, full_redraw, handle);
		refresh();

		full_redraw = false;

		win->old = win->curr;
		old_top = win->top;

		move(LINES-1, COLS-1);
		key = getch();
	}

out:
	tui_graph_finish();
	tui_report_finish();
	tui_info_finish();
	tui_session_finish();
}

int command_tui(int argc, char *argv[], struct opts *opts)
{
	int ret;
	struct ftrace_file_handle handle;
	struct ftrace_task_handle *task;

	ret = open_data_file(opts, &handle);
	if (ret < 0) {
		pr_warn("cannot open record data: %s: %m\n", opts->dirname);
		return -1;
	}

	setlocale(LC_ALL, "");

	initscr();
	init_colors();
	keypad(stdscr, true);
	noecho();

	atexit(tui_cleanup);

	tui_setup(&handle, opts);
	fstack_setup_filters(opts, &handle);

	while (read_rstack(&handle, &task) == 0 && !uftrace_done) {
		struct uftrace_record *rec = task->rstack;

		if (!fstack_check_opts(task, opts))
			continue;

		if (!fstack_check_filter(task))
			continue;

		ret = build_tui_node(task, rec);
		if (ret)
			break;
	}
	add_remaining_node(opts, &handle);

	tui_main_loop(opts, &handle);

	close_data_file(opts, &handle);

	tui_cleanup();
	return 0;
}

#else /* !HAVE_LIBNCURSES */

#include "uftrace.h"
#include "utils/utils.h"

int command_tui(int argc, char *argv[], struct opts *opts)
{
	pr_warn("TUI is unsupported (libncursesw.so is missing)\n");
	return 0;
}

#endif /* HAVE_LIBNCURSES */