summaryrefslogtreecommitdiff
path: root/src/VBox/Debugger/VBoxDbgStatsQt.cpp
blob: 27a5d789f03aec1a7bcd1af274b531d6568c852e (plain)
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
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
/* $Id$ */
/** @file
 * VBox Debugger GUI - Statistics.
 */

/*
 * Copyright (C) 2006-2023 Oracle and/or its affiliates.
 *
 * This file is part of VirtualBox base platform packages, as
 * available from https://www.virtualbox.org.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, in version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <https://www.gnu.org/licenses>.
 *
 * SPDX-License-Identifier: GPL-3.0-only
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#define LOG_GROUP LOG_GROUP_DBGG
#include "VBoxDbgStatsQt.h"

#include <QLocale>
#include <QPushButton>
#include <QSpinBox>
#include <QLabel>
#include <QClipboard>
#include <QApplication>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QKeySequence>
#include <QAction>
#include <QContextMenuEvent>
#include <QHeaderView>

#include <iprt/errcore.h>
#include <VBox/log.h>
#include <iprt/string.h>
#include <iprt/mem.h>
#include <iprt/assert.h>

#include "VBoxDbgGui.h"


/*********************************************************************************************************************************
*   Defined Constants And Macros                                                                                                 *
*********************************************************************************************************************************/
/** The number of column. */
#define DBGGUI_STATS_COLUMNS    9


/*********************************************************************************************************************************
*   Structures and Typedefs                                                                                                      *
*********************************************************************************************************************************/
/**
 * The state of a statistics sample node.
 *
 * This is used for two pass refresh (1. get data, 2. update the view) and
 * for saving the result of a diff.
 */
typedef enum DBGGUISTATSNODESTATE
{
    /** The typical invalid zeroth entry. */
    kDbgGuiStatsNodeState_kInvalid = 0,
    /** The node is the root node. */
    kDbgGuiStatsNodeState_kRoot,
    /** The node is visible. */
    kDbgGuiStatsNodeState_kVisible,
    /** The node should be refreshed. */
    kDbgGuiStatsNodeState_kRefresh,
    /** diff: The node equals. */
    kDbgGuiStatsNodeState_kDiffEqual,
    /** diff: The node in set 1 is less than the one in set 2. */
    kDbgGuiStatsNodeState_kDiffSmaller,
    /** diff: The node in set 1 is greater than the one in set 2. */
    kDbgGuiStatsNodeState_kDiffGreater,
    /** diff: The node is only in set 1. */
    kDbgGuiStatsNodeState_kDiffOnlyIn1,
    /** diff: The node is only in set 2. */
    kDbgGuiStatsNodeState_kDiffOnlyIn2,
    /** The end of the valid state values. */
    kDbgGuiStatsNodeState_kEnd
} DBGGUISTATENODESTATE;


/**
 * A tree node representing a statistic sample.
 *
 * The nodes carry a reference to the parent and to its position among its
 * siblings. Both of these need updating when the grand parent or parent adds a
 * new child. This will hopefully not be too expensive but rather pay off when
 * we need to create a parent index.
 */
typedef struct DBGGUISTATSNODE
{
    /** Pointer to the parent. */
    PDBGGUISTATSNODE        pParent;
    /** Array of pointers to the child nodes. */
    PDBGGUISTATSNODE       *papChildren;
    /** The number of children. */
    uint32_t                cChildren;
    /** Our index among the parent's children. */
    uint32_t                iSelf;
    /** The unit string. (not allocated) */
    const char             *pszUnit;
    /** The data type.
     * For filler nodes not containing data, this will be set to STAMTYPE_INVALID. */
    STAMTYPE                enmType;
    /** The data at last update. */
    union
    {
        /** STAMTYPE_COUNTER. */
        STAMCOUNTER         Counter;
        /** STAMTYPE_PROFILE. */
        STAMPROFILE         Profile;
        /** STAMTYPE_PROFILE_ADV. */
        STAMPROFILEADV      ProfileAdv;
        /** STAMTYPE_RATIO_U32. */
        STAMRATIOU32        RatioU32;
        /** STAMTYPE_U8 & STAMTYPE_U8_RESET. */
        uint8_t             u8;
        /** STAMTYPE_U16 & STAMTYPE_U16_RESET. */
        uint16_t            u16;
        /** STAMTYPE_U32 & STAMTYPE_U32_RESET. */
        uint32_t            u32;
        /** STAMTYPE_U64 & STAMTYPE_U64_RESET. */
        uint64_t            u64;
        /** STAMTYPE_BOOL and STAMTYPE_BOOL_RESET. */
        bool                f;
        /** STAMTYPE_CALLBACK. */
        QString            *pStr;
    } Data;
    /** The delta. */
    int64_t                 i64Delta;
    /** The name. */
    char                   *pszName;
    /** The length of the name. */
    size_t                  cchName;
    /** The description string. */
    QString                *pDescStr;
    /** The node state. */
    DBGGUISTATENODESTATE    enmState;
} DBGGUISTATSNODE;


/**
 * Recursion stack.
 */
typedef struct DBGGUISTATSSTACK
{
    /** The top stack entry. */
    int32_t iTop;
    /** The stack array. */
    struct DBGGUISTATSSTACKENTRY
    {
        /** The node. */
        PDBGGUISTATSNODE    pNode;
        /** The current child. */
        int32_t             iChild;
        /** Name string offset (if used). */
        uint16_t            cchName;
    } a[32];
} DBGGUISTATSSTACK;




/**
 * The item model for the statistics tree view.
 *
 * This manages the DBGGUISTATSNODE trees.
 */
class VBoxDbgStatsModel : public QAbstractItemModel
{
protected:
    /** The root of the sample tree. */
    PDBGGUISTATSNODE m_pRoot;

private:
    /** Next update child. This is UINT32_MAX when invalid. */
    uint32_t m_iUpdateChild;
    /** Pointer to the node m_szUpdateParent represent and m_iUpdateChild refers to. */
    PDBGGUISTATSNODE m_pUpdateParent;
    /** The length of the path. */
    size_t m_cchUpdateParent;
    /** The path to the current update parent, including a trailing slash. */
    char m_szUpdateParent[1024];
    /** Inserted or/and removed nodes during the update. */
    bool m_fUpdateInsertRemove;


public:
    /**
     * Constructor.
     *
     * @param   a_pParent       The parent object. See QAbstractItemModel in the Qt
     *                          docs for details.
     */
    VBoxDbgStatsModel(QObject *a_pParent);

    /**
     * Destructor.
     *
     * This will free all the data the model holds.
     */
    virtual ~VBoxDbgStatsModel();

    /**
     * Updates the data matching the specified pattern.
     *
     * This will should invoke updatePrep, updateCallback and updateDone.
     *
     * It is vitally important that updateCallback is fed the data in the right
     * order. The code make very definite ASSUMPTIONS about the ordering being
     * strictly sorted and taking the slash into account when doing so.
     *
     * @returns true if we reset the model and it's necessary to set the root index.
     * @param   a_rPatStr       The selection pattern.
     *
     * @remarks The default implementation is an empty stub.
     */
    virtual bool updateStatsByPattern(const QString &a_rPatStr);

    /**
     * Similar to updateStatsByPattern, except that it only works on a sub-tree and
     * will not remove anything that's outside that tree.
     *
     * @param   a_rIndex    The sub-tree root. Invalid index means root.
     *
     * @todo    Create a default implementation using updateStatsByPattern.
     */
    virtual void updateStatsByIndex(QModelIndex const &a_rIndex);

    /**
     * Reset the stats matching the specified pattern.
     *
     * @param   a_rPatStr   The selection pattern.
     *
     * @remarks The default implementation is an empty stub.
     */
    virtual void resetStatsByPattern(QString const &a_rPatStr);

    /**
     * Reset the stats of a sub-tree.
     *
     * @param   a_rIndex    The sub-tree root. Invalid index means root.
     * @param   a_fSubTree  Whether to reset the sub-tree as well. Default is true.
     *
     * @remarks The default implementation makes use of resetStatsByPattern
     */
    virtual void resetStatsByIndex(QModelIndex const &a_rIndex, bool a_fSubTree = true);

    /**
     * Iterator callback function.
     * @returns true to continue, false to stop.
     */
    typedef bool FNITERATOR(PDBGGUISTATSNODE pNode, QModelIndex const &a_rIndex, const char *pszFullName, void *pvUser);

    /**
     * Callback iterator.
     *
     * @param   a_rPatStr           The selection pattern.
     * @param   a_pfnCallback       Callback function.
     * @param   a_pvUser            Callback argument.
     * @param   a_fMatchChildren    How to handle children of matching nodes:
     *                                - @c true: continue with the children,
     *                                - @c false: skip children.
     */
    virtual void iterateStatsByPattern(QString const &a_rPatStr, FNITERATOR *a_pfnCallback, void *a_pvUser,
                                       bool a_fMatchChildren = true);

    /**
     * Gets the model index of the root node.
     *
     * @returns root index.
     */
    QModelIndex getRootIndex(void) const;


protected:
    /**
     * Set the root node.
     *
     * This will free all the current data before taking the ownership of the new
     * root node and its children.
     *
     * @param   a_pRoot         The new root node.
     */
    void setRootNode(PDBGGUISTATSNODE a_pRoot);

    /** Creates the root node. */
    static PDBGGUISTATSNODE createRootNode(void);

    /** Creates and insert a node under the given parent. */
    static PDBGGUISTATSNODE createAndInsertNode(PDBGGUISTATSNODE pParent, const char *pszName, size_t cchName, uint32_t iPosition);

    /** Creates and insert a node under the given parent with correct Qt
     * signalling. */
    PDBGGUISTATSNODE createAndInsert(PDBGGUISTATSNODE pParent, const char *pszName, size_t cchName, uint32_t iPosition);

    /**
     * Resets the node to a pristine state.
     *
     * @param   pNode       The node.
     */
    static void resetNode(PDBGGUISTATSNODE pNode);

    /**
     * Initializes a pristine node.
     */
    static int initNode(PDBGGUISTATSNODE pNode, STAMTYPE enmType, void *pvSample, const char *pszUnit, const char *pszDesc);

    /**
     * Updates (or reinitializes if you like) a node.
     */
    static void updateNode(PDBGGUISTATSNODE pNode, STAMTYPE enmType, void *pvSample, const char *pszUnit, const char *pszDesc);

    /**
     * Called by updateStatsByPattern(), makes the necessary preparations.
     *
     * @returns Success indicator.
     */
    bool updatePrepare(void);

    /**
     * Called by updateStatsByPattern(), finalizes the update.
     *
     * @return See updateStatsByPattern().
     *
     * @param  a_fSuccess   Whether the update was successful or not.
     *
     */
    bool updateDone(bool a_fSuccess);

    /**
     * updateCallback() worker taking care of in-tree inserts and removals.
     *
     * @returns The current node.
     * @param   pszName     The name of the tree element to update.
     */
    PDBGGUISTATSNODE updateCallbackHandleOutOfOrder(const char *pszName);

    /**
     * updateCallback() worker taking care of tail insertions.
     *
     * @returns The current node.
     * @param   pszName     The name of the tree element to update.
     */
    PDBGGUISTATSNODE updateCallbackHandleTail(const char *pszName);

    /**
     * updateCallback() worker that advances the update state to the next data node
     * in anticipation of the next updateCallback call.
     *
     * @returns The current node.
     * @param   pNode       The current node.
     */
    void updateCallbackAdvance(PDBGGUISTATSNODE pNode);

    /** Callback used by updateStatsByPattern() and updateStatsByIndex() to feed
     *  changes.
     * @copydoc FNSTAMR3ENUM */
    static DECLCALLBACK(int) updateCallback(const char *pszName, STAMTYPE enmType, void *pvSample, STAMUNIT enmUnit,
                                            const char *pszUnit, STAMVISIBILITY enmVisibility, const char *pszDesc, void *pvUser);

    /**
     * Calculates the full path of a node.
     *
     * @returns Number of bytes returned, negative value on buffer overflow
     *
     * @param   pNode       The node.
     * @param   psz         The output buffer.
     * @param   cch         The size of the buffer.
     */
    static ssize_t getNodePath(PCDBGGUISTATSNODE pNode, char *psz, ssize_t cch);

    /**
     * Calculates the full path of a node, returning the string pointer.
     *
     * @returns @a psz. On failure, NULL.
     *
     * @param   pNode       The node.
     * @param   psz         The output buffer.
     * @param   cch         The size of the buffer.
     */
    static char *getNodePath2(PCDBGGUISTATSNODE pNode, char *psz, ssize_t cch);

    /**
     * Check if the first node is an ancestor to the second one.
     *
     * @returns true/false.
     * @param   pAncestor   The first node, the alleged ancestor.
     * @param   pDescendant The second node, the alleged descendant.
     */
    static bool isNodeAncestorOf(PCDBGGUISTATSNODE pAncestor, PCDBGGUISTATSNODE pDescendant);

    /**
     * Advance to the next node in the tree.
     *
     * @returns Pointer to the next node, NULL if we've reached the end or
     *          was handed a NULL node.
     * @param   pNode       The current node.
     */
    static PDBGGUISTATSNODE nextNode(PDBGGUISTATSNODE pNode);

    /**
     * Advance to the next node in the tree that contains data.
     *
     * @returns Pointer to the next data node, NULL if we've reached the end or
     *          was handed a NULL node.
     * @param   pNode       The current node.
     */
    static PDBGGUISTATSNODE nextDataNode(PDBGGUISTATSNODE pNode);

    /**
     * Advance to the previous node in the tree.
     *
     * @returns Pointer to the previous node, NULL if we've reached the end or
     *          was handed a NULL node.
     * @param   pNode       The current node.
     */
    static PDBGGUISTATSNODE prevNode(PDBGGUISTATSNODE pNode);

    /**
     * Advance to the previous node in the tree that contains data.
     *
     * @returns Pointer to the previous data node, NULL if we've reached the end or
     *          was handed a NULL node.
     * @param   pNode       The current node.
     */
    static PDBGGUISTATSNODE prevDataNode(PDBGGUISTATSNODE pNode);

     /**
     * Removes a node from the tree.
     *
     * @returns pNode.
     * @param   pNode       The node.
     */
    static PDBGGUISTATSNODE removeNode(PDBGGUISTATSNODE pNode);

    /**
     * Removes a node from the tree and destroys it and all its descendants.
     *
     * @param   pNode       The node.
     */
    static void removeAndDestroyNode(PDBGGUISTATSNODE pNode);

    /** Removes a node from the tree and destroys it and all its descendants
     * performing the required Qt signalling. */
    void removeAndDestroy(PDBGGUISTATSNODE pNode);

    /**
     * Destroys a statistics tree.
     *
     * @param   a_pRoot     The root of the tree. NULL is fine.
     */
    static void destroyTree(PDBGGUISTATSNODE a_pRoot);

    /**
     * Stringifies exactly one node, no children.
     *
     * This is for logging and clipboard.
     *
     * @param   a_pNode     The node.
     * @param   a_rString   The string to append the stringified node to.
     */
    static void stringifyNodeNoRecursion(PDBGGUISTATSNODE a_pNode, QString &a_rString);

    /**
     * Stringifies a node and its children.
     *
     * This is for logging and clipboard.
     *
     * @param   a_pNode     The node.
     * @param   a_rString   The string to append the stringified node to.
     */
    static void stringifyNode(PDBGGUISTATSNODE a_pNode, QString &a_rString);

public:
    /**
     * Converts the specified tree to string.
     *
     * This is for logging and clipboard.
     *
     * @param   a_rRoot         Where to start. Use QModelIndex() to start at the root.
     * @param   a_rString       Where to return to return the string dump.
     */
    void stringifyTree(QModelIndex &a_rRoot, QString &a_rString) const;

    /**
     * Dumps the given (sub-)tree as XML.
     *
     * @param   a_rRoot         Where to start. Use QModelIndex() to start at the root.
     * @param   a_rString       Where to return to return the XML dump.
     */
    void xmlifyTree(QModelIndex &a_rRoot, QString &a_rString) const;

    /**
     * Puts the stringified tree on the clipboard.
     *
     * @param   a_rRoot         Where to start. Use QModelIndex() to start at the root.
     */
    void copyTreeToClipboard(QModelIndex &a_rRoot) const;


protected:
    /** Worker for logTree. */
    static void logNode(PDBGGUISTATSNODE a_pNode, bool a_fReleaseLog);

public:
    /** Logs a (sub-)tree.
     *
     * @param   a_rRoot         Where to start. Use QModelIndex() to start at the root.
     * @param   a_fReleaseLog   Whether to use the release log (true) or the debug log (false).
     */
    void logTree(QModelIndex &a_rRoot, bool a_fReleaseLog) const;

protected:
    /** Gets the unit. */
    static QString strUnit(PCDBGGUISTATSNODE pNode);
    /** Gets the value/times. */
    static QString strValueTimes(PCDBGGUISTATSNODE pNode);
    /** Gets the minimum value. */
    static QString strMinValue(PCDBGGUISTATSNODE pNode);
    /** Gets the average value. */
    static QString strAvgValue(PCDBGGUISTATSNODE pNode);
    /** Gets the maximum value. */
    static QString strMaxValue(PCDBGGUISTATSNODE pNode);
    /** Gets the total value. */
    static QString strTotalValue(PCDBGGUISTATSNODE pNode);
    /** Gets the delta value. */
    static QString strDeltaValue(PCDBGGUISTATSNODE pNode);

    /**
     * Destroys a node and all its children.
     *
     * @param   a_pNode         The node to destroy.
     */
    static void destroyNode(PDBGGUISTATSNODE a_pNode);

    /**
     * Converts an index to a node pointer.
     *
     * @returns Pointer to the node, NULL if invalid reference.
     * @param   a_rIndex        Reference to the index
     */
    inline PDBGGUISTATSNODE nodeFromIndex(const QModelIndex &a_rIndex) const
    {
        if (RT_LIKELY(a_rIndex.isValid()))
            return (PDBGGUISTATSNODE)a_rIndex.internalPointer();
        return NULL;
    }

public:

    /** @name Overridden QAbstractItemModel methods
     * @{ */
    virtual int columnCount(const QModelIndex &a_rParent) const;
    virtual QVariant data(const QModelIndex &a_rIndex, int a_eRole) const;
    virtual Qt::ItemFlags flags(const QModelIndex &a_rIndex) const;
    virtual bool hasChildren(const QModelIndex &a_rParent) const;
    virtual QVariant headerData(int a_iSection, Qt::Orientation a_ePrientation, int a_eRole) const;
    virtual QModelIndex index(int a_iRow, int a_iColumn, const QModelIndex &a_rParent) const;
    virtual QModelIndex parent(const QModelIndex &a_rChild) const;
    virtual int rowCount(const QModelIndex &a_rParent) const;
    ///virtual void sort(int a_iColumn, Qt::SortOrder a_eOrder);
    /** @}  */
};


/**
 * Model using the VM / STAM interface as data source.
 */
class VBoxDbgStatsModelVM : public VBoxDbgStatsModel, public VBoxDbgBase
{
public:
    /**
     * Constructor.
     *
     * @param   a_pDbgGui       Pointer to the debugger gui object.
     * @param   a_rPatStr       The selection pattern.
     * @param   a_pParent       The parent object. NULL is fine.
     * @param   a_pVMM          The VMM function table.
     */
    VBoxDbgStatsModelVM(VBoxDbgGui *a_pDbgGui, QString &a_rPatStr, QObject *a_pParent, PCVMMR3VTABLE a_pVMM);

    /** Destructor */
    virtual ~VBoxDbgStatsModelVM();

    virtual bool updateStatsByPattern(const QString &a_rPatStr);
    virtual void resetStatsByPattern(const QString &a_rPatStr);

protected:
    /**
     * Enumeration callback used by createNewTree.
     */
    static DECLCALLBACK(int) createNewTreeCallback(const char *pszName, STAMTYPE enmType, void *pvSample, STAMUNIT enmUnit,
                                                   const char *pszUnit, STAMVISIBILITY enmVisibility, const char *pszDesc,
                                                   void *pvUser);

    /**
     * Constructs a new statistics tree by query data from the VM.
     *
     * @returns Pointer to the root of the tree we've constructed. This will be NULL
     *          if the STAM API throws an error or we run out of memory.
     * @param   a_rPatStr       The selection pattern.
     */
    PDBGGUISTATSNODE createNewTree(QString &a_rPatStr);

    /** The VMM function table. */
    PCVMMR3VTABLE m_pVMM;
};


/*********************************************************************************************************************************
*   Internal Functions                                                                                                           *
*********************************************************************************************************************************/


/**
 * Formats a number into a 64-byte buffer.
 */
static char *formatNumber(char *psz, uint64_t u64)
{
    static const char s_szDigits[] = "0123456789";
    psz += 63;
    *psz-- = '\0';
    unsigned cDigits = 0;
    for (;;)
    {
        const unsigned iDigit = u64 % 10;
        u64 /= 10;
        *psz = s_szDigits[iDigit];
        if (!u64)
            break;
        psz--;
        if (!(++cDigits % 3))
            *psz-- = ',';
    }
    return psz;
}


/**
 * Formats a number into a 64-byte buffer.
 * (18 446 744 073 709 551 615)
 */
static char *formatNumberSigned(char *psz, int64_t i64)
{
    static const char s_szDigits[] = "0123456789";
    psz += 63;
    *psz-- = '\0';
    const bool fNegative = i64 < 0;
    uint64_t u64 = fNegative ? -i64 : i64;
    unsigned cDigits = 0;
    for (;;)
    {
        const unsigned iDigit = u64 % 10;
        u64 /= 10;
        *psz = s_szDigits[iDigit];
        if (!u64)
            break;
        psz--;
        if (!(++cDigits % 3))
            *psz-- = ',';
    }
    if (fNegative)
        *--psz = '-';
    return psz;
}


/**
 * Formats a unsigned hexadecimal number into a into a 64-byte buffer.
 */
static char *formatHexNumber(char *psz, uint64_t u64, unsigned cZeros)
{
    static const char s_szDigits[] = "0123456789abcdef";
    psz += 63;
    *psz-- = '\0';
    unsigned cDigits = 0;
    for (;;)
    {
        const unsigned iDigit = u64 % 16;
        u64 /= 16;
        *psz = s_szDigits[iDigit];
        ++cDigits;
        if (!u64 && cDigits >= cZeros)
            break;
        psz--;
        if (!(cDigits % 8))
            *psz-- = '\'';
    }
    return psz;
}


#if 0/* unused */
/**
 * Formats a sort key number.
 */
static void formatSortKey(char *psz, uint64_t u64)
{
    static const char s_szDigits[] = "0123456789abcdef";
    /* signed */
    *psz++ = '+';

    /* 16 hex digits */
    psz[16] = '\0';
    unsigned i = 16;
    while (i-- > 0)
    {
        if (u64)
        {
            const unsigned iDigit = u64 % 16;
            u64 /= 16;
            psz[i] = s_szDigits[iDigit];
        }
        else
            psz[i] = '0';
    }
}
#endif


#if 0/* unused */
/**
 * Formats a sort key number.
 */
static void formatSortKeySigned(char *psz, int64_t i64)
{
    static const char s_szDigits[] = "0123456789abcdef";

    /* signed */
    uint64_t u64;
    if (i64 >= 0)
    {
        *psz++ = '+';
        u64 = i64;
    }
    else
    {
        *psz++ = '-';
        u64 = -i64;
    }

    /* 16 hex digits */
    psz[16] = '\0';
    unsigned i = 16;
    while (i-- > 0)
    {
        if (u64)
        {
            const unsigned iDigit = u64 % 16;
            u64 /= 16;
            psz[i] = s_szDigits[iDigit];
        }
        else
            psz[i] = '0';
    }
}
#endif



/*
 *
 *      V B o x D b g S t a t s M o d e l
 *      V B o x D b g S t a t s M o d e l
 *      V B o x D b g S t a t s M o d e l
 *
 *
 */


VBoxDbgStatsModel::VBoxDbgStatsModel(QObject *a_pParent)
    : QAbstractItemModel(a_pParent),
    m_pRoot(NULL), m_iUpdateChild(UINT32_MAX), m_pUpdateParent(NULL), m_cchUpdateParent(0)
{
}



VBoxDbgStatsModel::~VBoxDbgStatsModel()
{
    destroyTree(m_pRoot);
    m_pRoot = NULL;
}


/*static*/ void
VBoxDbgStatsModel::destroyTree(PDBGGUISTATSNODE a_pRoot)
{
    if (!a_pRoot)
        return;
    Assert(!a_pRoot->pParent);
    Assert(!a_pRoot->iSelf);

    destroyNode(a_pRoot);
}


/* static*/ void
VBoxDbgStatsModel::destroyNode(PDBGGUISTATSNODE a_pNode)
{
    /* destroy all our children */
    uint32_t i = a_pNode->cChildren;
    while (i-- > 0)
    {
        destroyNode(a_pNode->papChildren[i]);
        a_pNode->papChildren[i] = NULL;
    }

    /* free the resources we're using */
    a_pNode->pParent = NULL;

    RTMemFree(a_pNode->papChildren);
    a_pNode->papChildren = NULL;

    if (a_pNode->enmType == STAMTYPE_CALLBACK)
    {
        delete a_pNode->Data.pStr;
        a_pNode->Data.pStr = NULL;
    }

    a_pNode->cChildren = 0;
    a_pNode->iSelf = UINT32_MAX;
    a_pNode->pszUnit = "";
    a_pNode->enmType = STAMTYPE_INVALID;

    RTMemFree(a_pNode->pszName);
    a_pNode->pszName = NULL;

    if (a_pNode->pDescStr)
    {
        delete a_pNode->pDescStr;
        a_pNode->pDescStr = NULL;
    }

#ifdef VBOX_STRICT
    /* poison it. */
    a_pNode->pParent++;
    a_pNode->Data.pStr++;
    a_pNode->pDescStr++;
    a_pNode->papChildren++;
    a_pNode->cChildren = 8442;
#endif

    /* Finally ourselves */
    a_pNode->enmState = kDbgGuiStatsNodeState_kInvalid;
    RTMemFree(a_pNode);
}


/*static*/ PDBGGUISTATSNODE
VBoxDbgStatsModel::createRootNode(void)
{
    PDBGGUISTATSNODE pRoot = (PDBGGUISTATSNODE)RTMemAllocZ(sizeof(DBGGUISTATSNODE));
    if (!pRoot)
        return NULL;
    pRoot->iSelf = 0;
    pRoot->enmType = STAMTYPE_INVALID;
    pRoot->pszUnit = "";
    pRoot->pszName = (char *)RTMemDup("/", sizeof("/"));
    pRoot->cchName = 1;
    pRoot->enmState = kDbgGuiStatsNodeState_kRoot;

    return pRoot;
}


/*static*/ PDBGGUISTATSNODE
VBoxDbgStatsModel::createAndInsertNode(PDBGGUISTATSNODE pParent, const char *pszName, size_t cchName, uint32_t iPosition)
{
    /*
     * Create it.
     */
    PDBGGUISTATSNODE pNode = (PDBGGUISTATSNODE)RTMemAllocZ(sizeof(DBGGUISTATSNODE));
    if (!pNode)
        return NULL;
    pNode->iSelf = UINT32_MAX;
    pNode->enmType = STAMTYPE_INVALID;
    pNode->pszUnit = "";
    pNode->pszName = (char *)RTMemDupEx(pszName, cchName, 1);
    pNode->cchName = cchName;
    pNode->enmState = kDbgGuiStatsNodeState_kVisible;

    /*
     * Do we need to expand the array?
     */
    if (!(pParent->cChildren & 31))
    {
        void *pvNew = RTMemRealloc(pParent->papChildren, sizeof(*pParent->papChildren) * (pParent->cChildren + 32));
        if (!pvNew)
        {
            destroyNode(pNode);
            return NULL;
        }
        pParent->papChildren = (PDBGGUISTATSNODE *)pvNew;
    }

    /*
     * Insert it.
     */
    pNode->pParent = pParent;
    if (iPosition >= pParent->cChildren)
        /* Last. */
        iPosition = pParent->cChildren;
    else
    {
        /* Shift all the items after ours. */
        uint32_t iShift = pParent->cChildren;
        while (iShift-- > iPosition)
        {
            PDBGGUISTATSNODE pChild = pParent->papChildren[iShift];
            pParent->papChildren[iShift + 1] = pChild;
            pChild->iSelf = iShift + 1;
        }
    }

    /* Insert ours */
    pNode->iSelf = iPosition;
    pParent->papChildren[iPosition] = pNode;
    pParent->cChildren++;

    return pNode;
}


PDBGGUISTATSNODE
VBoxDbgStatsModel::createAndInsert(PDBGGUISTATSNODE pParent, const char *pszName, size_t cchName, uint32_t iPosition)
{
    PDBGGUISTATSNODE pNode;
    if (m_fUpdateInsertRemove)
        pNode = createAndInsertNode(pParent, pszName, cchName, iPosition);
    else
    {
        beginInsertRows(createIndex(pParent->iSelf, 0, pParent), 0, 0);
        pNode = createAndInsertNode(pParent, pszName, cchName, iPosition);
        endInsertRows();
    }
    return pNode;
}

/*static*/ PDBGGUISTATSNODE
VBoxDbgStatsModel::removeNode(PDBGGUISTATSNODE pNode)
{
    PDBGGUISTATSNODE pParent = pNode->pParent;
    if (pParent)
    {
        uint32_t iPosition = pNode->iSelf;
        Assert(pParent->papChildren[iPosition] == pNode);
        uint32_t const cChildren = --pParent->cChildren;
        for (; iPosition < cChildren; iPosition++)
        {
            PDBGGUISTATSNODE pChild = pParent->papChildren[iPosition + 1];
            pParent->papChildren[iPosition] = pChild;
            pChild->iSelf = iPosition;
        }
#ifdef VBOX_STRICT /* poison */
        pParent->papChildren[iPosition] = (PDBGGUISTATSNODE)0x42;
#endif
    }
    return pNode;
}


/*static*/ void
VBoxDbgStatsModel::removeAndDestroyNode(PDBGGUISTATSNODE pNode)
{
    removeNode(pNode);
    destroyNode(pNode);
}


void
VBoxDbgStatsModel::removeAndDestroy(PDBGGUISTATSNODE pNode)
{
    if (m_fUpdateInsertRemove)
        removeAndDestroyNode(pNode);
    else
    {
        /*
         * Removing is fun since the docs are imprecise as to how persistent
         * indexes are updated (or aren't). So, let try a few different ideas
         * and see which works.
         */
#if 1
        /* destroy the children first with the appropriate begin/endRemoveRows signals. */
        DBGGUISTATSSTACK    Stack;
        Stack.a[0].pNode  = pNode;
        Stack.a[0].iChild = -1;
        Stack.iTop = 0;
        while (Stack.iTop >= 0)
        {
            /* get top element */
            PDBGGUISTATSNODE pCurNode = Stack.a[Stack.iTop].pNode;
            uint32_t         iChild   = ++Stack.a[Stack.iTop].iChild;
            if (iChild < pCurNode->cChildren)
            {
                /* push */
                Stack.iTop++;
                Assert(Stack.iTop < (int32_t)RT_ELEMENTS(Stack.a));
                Stack.a[Stack.iTop].pNode  = pCurNode->papChildren[iChild];
                Stack.a[Stack.iTop].iChild = 0;
            }
            else
            {
                /* pop and destroy all the children. */
                Stack.iTop--;
                uint32_t i = pCurNode->cChildren;
                if (i)
                {
                    beginRemoveRows(createIndex(pCurNode->iSelf, 0, pCurNode), 0, i - 1);
                    while (i-- > 0)
                        destroyNode(pCurNode->papChildren[i]);
                    pCurNode->cChildren = 0;
                    endRemoveRows();
                }
            }
        }
        Assert(!pNode->cChildren);

        /* finally the node it self. */
        PDBGGUISTATSNODE pParent = pNode->pParent;
        beginRemoveRows(createIndex(pParent->iSelf, 0, pParent), pNode->iSelf, pNode->iSelf);
        removeAndDestroyNode(pNode);
        endRemoveRows();

#elif 0
        /* This ain't working, leaves invalid indexes behind. */
        PDBGGUISTATSNODE pParent = pNode->pParent;
        beginRemoveRows(createIndex(pParent->iSelf, 0, pParent), pNode->iSelf, pNode->iSelf);
        removeAndDestroyNode(pNode);
        endRemoveRows();
#else
        /* Force reset() of the model after the update. */
        m_fUpdateInsertRemove = true;
        removeAndDestroyNode(pNode);
#endif
    }
}


/*static*/ void
VBoxDbgStatsModel::resetNode(PDBGGUISTATSNODE pNode)
{
    /* free and reinit the data. */
    if (pNode->enmType == STAMTYPE_CALLBACK)
    {
        delete pNode->Data.pStr;
        pNode->Data.pStr = NULL;
    }
    pNode->enmType = STAMTYPE_INVALID;

    /* free the description. */
    if (pNode->pDescStr)
    {
        delete pNode->pDescStr;
        pNode->pDescStr = NULL;
    }
}


/*static*/ int
VBoxDbgStatsModel::initNode(PDBGGUISTATSNODE pNode, STAMTYPE enmType, void *pvSample,
                            const char *pszUnit, const char *pszDesc)
{
    /*
     * Copy the data.
     */
    pNode->pszUnit = pszUnit;
    Assert(pNode->enmType == STAMTYPE_INVALID);
    pNode->enmType = enmType;
    if (pszDesc)
        pNode->pDescStr = new QString(pszDesc); /* ignore allocation failure (well, at least up to the point we can ignore it) */

    switch (enmType)
    {
        case STAMTYPE_COUNTER:
            pNode->Data.Counter = *(PSTAMCOUNTER)pvSample;
            break;

        case STAMTYPE_PROFILE:
        case STAMTYPE_PROFILE_ADV:
            pNode->Data.Profile = *(PSTAMPROFILE)pvSample;
            break;

        case STAMTYPE_RATIO_U32:
        case STAMTYPE_RATIO_U32_RESET:
            pNode->Data.RatioU32 = *(PSTAMRATIOU32)pvSample;
            break;

        case STAMTYPE_CALLBACK:
        {
            const char *pszString = (const char *)pvSample;
            pNode->Data.pStr = new QString(pszString);
            break;
        }

        case STAMTYPE_U8:
        case STAMTYPE_U8_RESET:
        case STAMTYPE_X8:
        case STAMTYPE_X8_RESET:
            pNode->Data.u8 = *(uint8_t *)pvSample;
            break;

        case STAMTYPE_U16:
        case STAMTYPE_U16_RESET:
        case STAMTYPE_X16:
        case STAMTYPE_X16_RESET:
            pNode->Data.u16 = *(uint16_t *)pvSample;
            break;

        case STAMTYPE_U32:
        case STAMTYPE_U32_RESET:
        case STAMTYPE_X32:
        case STAMTYPE_X32_RESET:
            pNode->Data.u32 = *(uint32_t *)pvSample;
            break;

        case STAMTYPE_U64:
        case STAMTYPE_U64_RESET:
        case STAMTYPE_X64:
        case STAMTYPE_X64_RESET:
            pNode->Data.u64 = *(uint64_t *)pvSample;
            break;

        case STAMTYPE_BOOL:
        case STAMTYPE_BOOL_RESET:
            pNode->Data.f = *(bool *)pvSample;
            break;

        default:
            AssertMsgFailed(("%d\n", enmType));
            break;
    }

    return VINF_SUCCESS;
}




/*static*/ void
VBoxDbgStatsModel::updateNode(PDBGGUISTATSNODE pNode, STAMTYPE enmType, void *pvSample, const char *pszUnit, const char *pszDesc)
{
    /*
     * Reset and init the node if the type changed.
     */
    if (enmType != pNode->enmType)
    {
        if (pNode->enmType != STAMTYPE_INVALID)
            resetNode(pNode);
        initNode(pNode, enmType, pvSample, pszUnit, pszDesc);
        pNode->enmState = kDbgGuiStatsNodeState_kRefresh;
    }
    else
    {
        /*
         * ASSUME that only the sample value will change and that the unit, visibility
         * and description remains the same.
         */

        int64_t iDelta;
        switch (enmType)
        {
            case STAMTYPE_COUNTER:
            {
                uint64_t cPrev = pNode->Data.Counter.c;
                pNode->Data.Counter = *(PSTAMCOUNTER)pvSample;
                iDelta = pNode->Data.Counter.c - cPrev;
                if (iDelta || pNode->i64Delta)
                {
                    pNode->i64Delta = iDelta;
                    pNode->enmState = kDbgGuiStatsNodeState_kRefresh;
                }
                break;
            }

            case STAMTYPE_PROFILE:
            case STAMTYPE_PROFILE_ADV:
            {
                uint64_t cPrevPeriods = pNode->Data.Profile.cPeriods;
                pNode->Data.Profile = *(PSTAMPROFILE)pvSample;
                iDelta = pNode->Data.Profile.cPeriods - cPrevPeriods;
                if (iDelta || pNode->i64Delta)
                {
                    pNode->i64Delta = iDelta;
                    pNode->enmState = kDbgGuiStatsNodeState_kRefresh;
                }
                break;
            }

            case STAMTYPE_RATIO_U32:
            case STAMTYPE_RATIO_U32_RESET:
            {
                STAMRATIOU32 Prev = pNode->Data.RatioU32;
                pNode->Data.RatioU32 = *(PSTAMRATIOU32)pvSample;
                int32_t iDeltaA = pNode->Data.RatioU32.u32A - Prev.u32A;
                int32_t iDeltaB = pNode->Data.RatioU32.u32B - Prev.u32B;
                if (iDeltaA == 0 && iDeltaB == 0)
                {
                    if (pNode->i64Delta)
                    {
                        pNode->i64Delta = 0;
                        pNode->enmState = kDbgGuiStatsNodeState_kRefresh;
                    }
                }
                else
                {
                    if (iDeltaA >= 0)
                        pNode->i64Delta = iDeltaA + (iDeltaB >= 0 ? iDeltaB : -iDeltaB);
                    else
                        pNode->i64Delta = iDeltaA + (iDeltaB <  0 ? iDeltaB : -iDeltaB);
                    pNode->enmState = kDbgGuiStatsNodeState_kRefresh;
                }
                break;
            }

            case STAMTYPE_CALLBACK:
            {
                const char *pszString = (const char *)pvSample;
                if (!pNode->Data.pStr)
                {
                    pNode->Data.pStr = new QString(pszString);
                    pNode->enmState = kDbgGuiStatsNodeState_kRefresh;
                }
                else if (*pNode->Data.pStr == pszString)
                {
                    delete pNode->Data.pStr;
                    pNode->Data.pStr = new QString(pszString);
                    pNode->enmState = kDbgGuiStatsNodeState_kRefresh;
                }
                break;
            }

            case STAMTYPE_U8:
            case STAMTYPE_U8_RESET:
            case STAMTYPE_X8:
            case STAMTYPE_X8_RESET:
            {
                uint8_t uPrev = pNode->Data.u8;
                pNode->Data.u8 = *(uint8_t *)pvSample;
                iDelta = (int32_t)pNode->Data.u8 - (int32_t)uPrev;
                if (iDelta || pNode->i64Delta)
                {
                    pNode->i64Delta = iDelta;
                    pNode->enmState = kDbgGuiStatsNodeState_kRefresh;
                }
                break;
            }

            case STAMTYPE_U16:
            case STAMTYPE_U16_RESET:
            case STAMTYPE_X16:
            case STAMTYPE_X16_RESET:
            {
                uint16_t uPrev = pNode->Data.u16;
                pNode->Data.u16 = *(uint16_t *)pvSample;
                iDelta = (int32_t)pNode->Data.u16 - (int32_t)uPrev;
                if (iDelta || pNode->i64Delta)
                {
                    pNode->i64Delta = iDelta;
                    pNode->enmState = kDbgGuiStatsNodeState_kRefresh;
                }
                break;
            }

            case STAMTYPE_U32:
            case STAMTYPE_U32_RESET:
            case STAMTYPE_X32:
            case STAMTYPE_X32_RESET:
            {
                uint32_t uPrev = pNode->Data.u32;
                pNode->Data.u32 = *(uint32_t *)pvSample;
                iDelta = (int64_t)pNode->Data.u32 - (int64_t)uPrev;
                if (iDelta || pNode->i64Delta)
                {
                    pNode->i64Delta = iDelta;
                    pNode->enmState = kDbgGuiStatsNodeState_kRefresh;
                }
                break;
            }

            case STAMTYPE_U64:
            case STAMTYPE_U64_RESET:
            case STAMTYPE_X64:
            case STAMTYPE_X64_RESET:
            {
                uint64_t uPrev = pNode->Data.u64;
                pNode->Data.u64 = *(uint64_t *)pvSample;
                iDelta = pNode->Data.u64 - uPrev;
                if (iDelta || pNode->i64Delta)
                {
                    pNode->i64Delta = iDelta;
                    pNode->enmState = kDbgGuiStatsNodeState_kRefresh;
                }
                break;
            }

            case STAMTYPE_BOOL:
            case STAMTYPE_BOOL_RESET:
            {
                bool fPrev = pNode->Data.f;
                pNode->Data.f = *(bool *)pvSample;
                iDelta = pNode->Data.f - fPrev;
                if (iDelta || pNode->i64Delta)
                {
                    pNode->i64Delta = iDelta;
                    pNode->enmState = kDbgGuiStatsNodeState_kRefresh;
                }
                break;
            }

            default:
                AssertMsgFailed(("%d\n", enmType));
                break;
        }
    }
}


/*static*/ ssize_t
VBoxDbgStatsModel::getNodePath(PCDBGGUISTATSNODE pNode, char *psz, ssize_t cch)
{
    ssize_t off;
    if (!pNode->pParent)
    {
        /* root - don't add it's slash! */
        AssertReturn(cch >= 1, -1);
        off = 0;
        *psz = '\0';
    }
    else
    {
        cch -= pNode->cchName + 1;
        AssertReturn(cch > 0, -1);
        off = getNodePath(pNode->pParent, psz, cch);
        if (off >= 0)
        {
            psz[off++] = '/';
            memcpy(&psz[off], pNode->pszName, pNode->cchName + 1);
            off += pNode->cchName;
        }
    }
    return off;
}


/*static*/ char *
VBoxDbgStatsModel::getNodePath2(PCDBGGUISTATSNODE pNode, char *psz, ssize_t cch)
{
    if (VBoxDbgStatsModel::getNodePath(pNode, psz, cch) < 0)
        return NULL;
    return psz;
}



/*static*/ bool
VBoxDbgStatsModel::isNodeAncestorOf(PCDBGGUISTATSNODE pAncestor, PCDBGGUISTATSNODE pDescendant)
{
    while (pDescendant)
    {
        pDescendant = pDescendant->pParent;
        if (pDescendant == pAncestor)
            return true;
    }
    return false;
}


/*static*/ PDBGGUISTATSNODE
VBoxDbgStatsModel::nextNode(PDBGGUISTATSNODE pNode)
{
    if (!pNode)
        return NULL;

    /* descend to children. */
    if (pNode->cChildren)
        return pNode->papChildren[0];

    PDBGGUISTATSNODE pParent = pNode->pParent;
    if (!pParent)
        return NULL;

    /* next sibling. */
    if (pNode->iSelf + 1 < pNode->pParent->cChildren)
        return pParent->papChildren[pNode->iSelf + 1];

    /* ascend and advanced to a parent's sibiling. */
    for (;;)
    {
        uint32_t iSelf = pParent->iSelf;
        pParent = pParent->pParent;
        if (!pParent)
            return NULL;
        if (iSelf + 1 < pParent->cChildren)
            return pParent->papChildren[iSelf + 1];
    }
}


/*static*/ PDBGGUISTATSNODE
VBoxDbgStatsModel::nextDataNode(PDBGGUISTATSNODE pNode)
{
    do
        pNode = nextNode(pNode);
    while (     pNode
           &&   pNode->enmType == STAMTYPE_INVALID);
    return pNode;
}


/*static*/ PDBGGUISTATSNODE
VBoxDbgStatsModel::prevNode(PDBGGUISTATSNODE pNode)
{
    if (!pNode)
        return NULL;
    PDBGGUISTATSNODE pParent = pNode->pParent;
    if (!pParent)
        return NULL;

    /* previous sibling's latest descendant (better expression anyone?). */
    if (pNode->iSelf > 0)
    {
        pNode = pParent->papChildren[pNode->iSelf - 1];
        while (pNode->cChildren)
            pNode = pNode->papChildren[pNode->cChildren - 1];
        return pNode;
    }

    /* ascend to the parent. */
    return pParent;
}


/*static*/ PDBGGUISTATSNODE
VBoxDbgStatsModel::prevDataNode(PDBGGUISTATSNODE pNode)
{
    do
        pNode = prevNode(pNode);
    while (     pNode
           &&   pNode->enmType == STAMTYPE_INVALID);
    return pNode;
}


#if 0
/*static*/ PDBGGUISTATSNODE
VBoxDbgStatsModel::createNewTree(IMachineDebugger *a_pIMachineDebugger)
{
    /** @todo  */
    return NULL;
}
#endif


#if 0
/*static*/ PDBGGUISTATSNODE
VBoxDbgStatsModel::createNewTree(const char *pszFilename)
{
    /** @todo  */
    return NULL;
}
#endif


#if 0
/*static*/ PDBGGUISTATSNODE
VBoxDbgStatsModel::createDiffTree(PDBGGUISTATSNODE pTree1, PDBGGUISTATSNODE pTree2)
{
    /** @todo  */
    return NULL;
}
#endif


PDBGGUISTATSNODE
VBoxDbgStatsModel::updateCallbackHandleOutOfOrder(const char *pszName)
{
#if defined(VBOX_STRICT) || defined(LOG_ENABLED)
    char szStrict[1024];
#endif

    /*
     * We might be inserting a new node between pPrev and pNode
     * or we might be removing one or more nodes. Either case is
     * handled in the same rough way.
     *
     * Might consider optimizing insertion at some later point since this
     * is a normal occurrence (dynamic statistics in PATM, IOM, MM, ++).
     */
    Assert(pszName[0] == '/');
    Assert(m_szUpdateParent[m_cchUpdateParent - 1] == '/');

    /*
     * Start with the current parent node and look for a common ancestor
     * hoping that this is faster than going from the root (saves lookup).
     */
    PDBGGUISTATSNODE pNode = m_pUpdateParent->papChildren[m_iUpdateChild];
    PDBGGUISTATSNODE const pPrev = prevDataNode(pNode);
    AssertMsg(strcmp(pszName, getNodePath2(pNode, szStrict, sizeof(szStrict))), ("%s\n", szStrict));
    AssertMsg(!pPrev || strcmp(pszName, getNodePath2(pPrev, szStrict, sizeof(szStrict))), ("%s\n", szStrict));
    Log(("updateCallbackHandleOutOfOrder: pszName='%s' m_szUpdateParent='%s' m_cchUpdateParent=%u pNode='%s'\n",
         pszName, m_szUpdateParent, m_cchUpdateParent, getNodePath2(pNode, szStrict, sizeof(szStrict))));

    pNode = pNode->pParent;
    while (pNode != m_pRoot)
    {
        if (!strncmp(pszName, m_szUpdateParent, m_cchUpdateParent))
            break;
        Assert(m_cchUpdateParent > pNode->cchName);
        m_cchUpdateParent -= pNode->cchName + 1;
        m_szUpdateParent[m_cchUpdateParent] = '\0';
        Log2(("updateCallbackHandleOutOfOrder: m_szUpdateParent='%s' m_cchUpdateParent=%u, removed '/%s' (%u)\n", m_szUpdateParent, m_cchUpdateParent, pNode->pszName, __LINE__));
        pNode = pNode->pParent;
    }
    Assert(m_szUpdateParent[m_cchUpdateParent - 1] == '/');

    /*
     * Descend until we've found/created the node pszName indicates,
     * modifying m_szUpdateParent as we go along.
     */
    while (pszName[m_cchUpdateParent - 1] == '/')
    {
        /* Find the end of this component. */
        const char * const pszSubName = &pszName[m_cchUpdateParent];
        const char *pszEnd = strchr(pszSubName, '/');
        if (!pszEnd)
            pszEnd = strchr(pszSubName, '\0');
        size_t cchSubName = pszEnd - pszSubName;

        /* Add the name to the path. */
        memcpy(&m_szUpdateParent[m_cchUpdateParent], pszSubName, cchSubName);
        m_cchUpdateParent += cchSubName;
        m_szUpdateParent[m_cchUpdateParent++] = '/';
        m_szUpdateParent[m_cchUpdateParent] = '\0';
        Assert(m_cchUpdateParent < sizeof(m_szUpdateParent));
        Log2(("updateCallbackHandleOutOfOrder: m_szUpdateParent='%s' m_cchUpdateParent=%u (%u)\n", m_szUpdateParent, m_cchUpdateParent, __LINE__));

        if (!pNode->cChildren)
        {
            /* first child */
            pNode = createAndInsert(pNode, pszSubName, cchSubName, 0);
            AssertReturn(pNode, NULL);
        }
        else
        {
            /* binary search. */
            int32_t iStart = 0;
            int32_t iLast = pNode->cChildren - 1;
            for (;;)
            {
                int32_t i = iStart + (iLast + 1 - iStart) / 2;
                int iDiff;
                size_t const cchCompare = RT_MIN(pNode->papChildren[i]->cchName, cchSubName);
                iDiff = memcmp(pszSubName, pNode->papChildren[i]->pszName, cchCompare);
                if (!iDiff)
                {
                    iDiff = cchSubName == cchCompare ? 0 : cchSubName > cchCompare ? 1 : -1;
                    /* For cases when exisiting node name is same as new node name with additional characters. */
                    if (!iDiff)
                        iDiff = cchSubName == pNode->papChildren[i]->cchName ? 0 : cchSubName > pNode->papChildren[i]->cchName ? 1 : -1;
                }
                if (iDiff > 0)
                {
                    iStart = i + 1;
                    if (iStart > iLast)
                    {
                        pNode = createAndInsert(pNode, pszSubName, cchSubName, iStart);
                        AssertReturn(pNode, NULL);
                        break;
                    }
                }
                else if (iDiff < 0)
                {
                    iLast = i - 1;
                    if (iLast < iStart)
                    {
                        pNode = createAndInsert(pNode, pszSubName, cchSubName, i);
                        AssertReturn(pNode, NULL);
                        break;
                    }
                }
                else
                {
                    pNode = pNode->papChildren[i];
                    break;
                }
            }
        }
    }
    Assert(   !memcmp(pszName, m_szUpdateParent, m_cchUpdateParent - 2)
           && pszName[m_cchUpdateParent - 1] == '\0');

    /*
     * Remove all the nodes between pNode and pPrev but keep all
     * of pNode's ancestors (or it'll get orphaned).
     */
    PDBGGUISTATSNODE pCur = prevNode(pNode);
    while (pCur != pPrev)
    {
        PDBGGUISTATSNODE pAdv = prevNode(pCur); Assert(pAdv || !pPrev);
        if (!isNodeAncestorOf(pCur, pNode))
        {
            Assert(pCur != m_pRoot);
            removeAndDestroy(pCur);
        }
        pCur = pAdv;
    }

    /*
     * Remove the data from all ancestors of pNode that it doesn't
     * share them pPrev.
     */
    if (pPrev)
    {
        pCur = pNode->pParent;
        while (!isNodeAncestorOf(pCur, pPrev))
        {
            resetNode(pNode);
            pCur = pCur->pParent;
        }
    }

    /*
     * Finally, adjust the globals (szUpdateParent is one level too deep).
     */
    Assert(m_cchUpdateParent > pNode->cchName + 1);
    m_cchUpdateParent -= pNode->cchName + 1;
    m_szUpdateParent[m_cchUpdateParent] = '\0';
    m_pUpdateParent = pNode->pParent;
    m_iUpdateChild = pNode->iSelf;
    Log2(("updateCallbackHandleOutOfOrder: m_szUpdateParent='%s' m_cchUpdateParent=%u (%u)\n", m_szUpdateParent, m_cchUpdateParent, __LINE__));

    return pNode;
}


PDBGGUISTATSNODE
VBoxDbgStatsModel::updateCallbackHandleTail(const char *pszName)
{
    /*
     * Insert it at the end of the tree.
     *
     * Do the same as we're doing down in createNewTreeCallback, walk from the
     * root and create whatever we need.
     */
    AssertReturn(*pszName == '/' && pszName[1] != '/', NULL);
    PDBGGUISTATSNODE pNode = m_pRoot;
    const char *pszCur = pszName + 1;
    while (*pszCur)
    {
        /* Find the end of this component. */
        const char *pszNext = strchr(pszCur, '/');
        if (!pszNext)
            pszNext = strchr(pszCur, '\0');
        size_t cchCur = pszNext - pszCur;

        /* Create it if it doesn't exist (it will be last if it exists). */
        if (    !pNode->cChildren
            ||  strncmp(pNode->papChildren[pNode->cChildren - 1]->pszName, pszCur, cchCur)
            ||  pNode->papChildren[pNode->cChildren - 1]->pszName[cchCur])
        {
            pNode = createAndInsert(pNode, pszCur, pszNext - pszCur, pNode->cChildren);
            AssertReturn(pNode, NULL);
        }
        else
            pNode = pNode->papChildren[pNode->cChildren - 1];

        /* Advance */
        pszCur = *pszNext ? pszNext + 1 : pszNext;
    }

    return pNode;
}


void
VBoxDbgStatsModel::updateCallbackAdvance(PDBGGUISTATSNODE pNode)
{
    /*
     * Advance to the next node with data.
     *
     * ASSUMES a leaf *must* have data and again we're ASSUMING the sorting
     * on slash separated sub-strings.
     */
    if (m_iUpdateChild != UINT32_MAX)
    {
#ifdef VBOX_STRICT
        PDBGGUISTATSNODE const pCorrectNext = nextDataNode(pNode);
#endif
        PDBGGUISTATSNODE pParent = pNode->pParent;
        if (pNode->cChildren)
        {
            /* descend to the first child. */
            Assert(m_cchUpdateParent + pNode->cchName + 2 < sizeof(m_szUpdateParent));
            memcpy(&m_szUpdateParent[m_cchUpdateParent], pNode->pszName, pNode->cchName);
            m_cchUpdateParent += pNode->cchName;
            m_szUpdateParent[m_cchUpdateParent++] = '/';
            m_szUpdateParent[m_cchUpdateParent] = '\0';

            pNode = pNode->papChildren[0];
        }
        else if (pNode->iSelf + 1 < pParent->cChildren)
        {
            /* next sibling or one if its descendants. */
            Assert(m_pUpdateParent == pParent);
            pNode = pParent->papChildren[pNode->iSelf + 1];
        }
        else
        {
            /* move up and down- / on-wards */
            for (;;)
            {
                /* ascend */
                pNode = pParent;
                pParent = pParent->pParent;
                if (!pParent)
                {
                    Assert(pNode == m_pRoot);
                    m_iUpdateChild = UINT32_MAX;
                    m_szUpdateParent[0] = '\0';
                    m_cchUpdateParent = 0;
                    m_pUpdateParent = NULL;
                    break;
                }
                Assert(m_cchUpdateParent > pNode->cchName + 1);
                m_cchUpdateParent -= pNode->cchName + 1;

                /* try advance */
                if (pNode->iSelf + 1 < pParent->cChildren)
                {
                    pNode = pParent->papChildren[pNode->iSelf + 1];
                    m_szUpdateParent[m_cchUpdateParent] = '\0';
                    break;
                }
            }
        }

        /* descend to a node containing data and finalize the globals. (ASSUMES leaf has data.) */
        if (m_iUpdateChild != UINT32_MAX)
        {
            while (   pNode->enmType == STAMTYPE_INVALID
                   && pNode->cChildren > 0)
            {
                Assert(pNode->enmState == kDbgGuiStatsNodeState_kVisible);

                Assert(m_cchUpdateParent + pNode->cchName + 2 < sizeof(m_szUpdateParent));
                memcpy(&m_szUpdateParent[m_cchUpdateParent], pNode->pszName, pNode->cchName);
                m_cchUpdateParent += pNode->cchName;
                m_szUpdateParent[m_cchUpdateParent++] = '/';
                m_szUpdateParent[m_cchUpdateParent] = '\0';

                pNode = pNode->papChildren[0];
            }
            Assert(pNode->enmType != STAMTYPE_INVALID);
            m_iUpdateChild = pNode->iSelf;
            m_pUpdateParent = pNode->pParent;
            Assert(pNode == pCorrectNext);
        }
    }
    /* else: we're at the end */
}


/*static*/ DECLCALLBACK(int)
VBoxDbgStatsModel::updateCallback(const char *pszName, STAMTYPE enmType, void *pvSample, STAMUNIT enmUnit,
                                  const char *pszUnit, STAMVISIBILITY enmVisibility, const char *pszDesc, void *pvUser)
{
    VBoxDbgStatsModelVM *pThis = (VBoxDbgStatsModelVM *)pvUser;
    Log3(("updateCallback: %s\n", pszName));
    RT_NOREF(enmUnit);

    /*
     * Skip the ones which shouldn't be visible in the GUI.
     */
    if (enmVisibility == STAMVISIBILITY_NOT_GUI)
        return 0;

    /*
     * The default assumption is that nothing has changed.
     * For now we'll reset the model when ever something changes.
     */
    PDBGGUISTATSNODE pNode;
    if (pThis->m_iUpdateChild != UINT32_MAX)
    {
        pNode = pThis->m_pUpdateParent->papChildren[pThis->m_iUpdateChild];
        if (    !strncmp(pszName, pThis->m_szUpdateParent, pThis->m_cchUpdateParent)
            &&  !strcmp(pszName + pThis->m_cchUpdateParent, pNode->pszName))
            /* got it! */;
        else
        {
            /* insert/remove */
            pNode = pThis->updateCallbackHandleOutOfOrder(pszName);
            if (!pNode)
                return VERR_NO_MEMORY;
        }
    }
    else
    {
        /* append */
        pNode = pThis->updateCallbackHandleTail(pszName);
        if (!pNode)
            return VERR_NO_MEMORY;
    }

    /*
     * Perform the update and advance to the next one.
     */
    updateNode(pNode, enmType, pvSample, pszUnit, pszDesc);
    pThis->updateCallbackAdvance(pNode);

    return VINF_SUCCESS;
}


bool
VBoxDbgStatsModel::updatePrepare(void)
{
    /*
     * Find the first child with data and set it up as the 'next'
     * node to be updated.
     */
    Assert(m_pRoot);
    Assert(m_pRoot->enmType == STAMTYPE_INVALID);
    PDBGGUISTATSNODE pFirst = nextDataNode(m_pRoot);
    if (pFirst)
    {
        m_iUpdateChild = pFirst->iSelf;
        m_pUpdateParent = pFirst->pParent; Assert(m_pUpdateParent);
        m_cchUpdateParent = getNodePath(m_pUpdateParent, m_szUpdateParent, sizeof(m_szUpdateParent) - 1);
        AssertReturn(m_cchUpdateParent >= 1, false);
        m_szUpdateParent[m_cchUpdateParent++] = '/';
        m_szUpdateParent[m_cchUpdateParent] = '\0';
    }
    else
    {
        m_iUpdateChild = UINT32_MAX;
        m_pUpdateParent = NULL;
        m_szUpdateParent[0] = '\0';
        m_cchUpdateParent = 0;
    }

    /*
     * Set the flag and signal possible layout change.
     */
    m_fUpdateInsertRemove = false;
    /* emit layoutAboutToBeChanged(); - debug this, it gets stuck... */
    return true;
}


bool
VBoxDbgStatsModel::updateDone(bool a_fSuccess)
{
    /*
     * Remove any nodes following the last in the update (unless the update failed).
     */
    if (    a_fSuccess
        &&  m_iUpdateChild != UINT32_MAX)
    {
        PDBGGUISTATSNODE const pLast = prevDataNode(m_pUpdateParent->papChildren[m_iUpdateChild]);
        if (!pLast)
        {
            /* nuking the whole tree. */
            setRootNode(createRootNode());
            m_fUpdateInsertRemove = true;
        }
        else
        {
            PDBGGUISTATSNODE pNode;
            while ((pNode = nextNode(pLast)))
            {
                Assert(pNode != m_pRoot);
                removeAndDestroy(pNode);
            }
        }
    }

    /*
     * We're done making layout changes (if I understood it correctly), so,
     * signal this and then see what to do next. If we did too many removals
     * we'll just reset the whole shebang.
     */
    if (m_fUpdateInsertRemove)
    {
        /* emit layoutChanged(); - hrmpf, doesn't work reliably... */
        beginResetModel();
        endResetModel();
    }
    else
    {
        /*
         * Send dataChanged events.
         *
         * We do this here instead of from the updateCallback because it reduces
         * the clutter in that method and allow us to emit bulk signals in an
         * easier way because we can traverse the tree in a different fashion.
         */
        DBGGUISTATSSTACK    Stack;
        Stack.a[0].pNode = m_pRoot;
        Stack.a[0].iChild = -1;
        Stack.iTop = 0;

        while (Stack.iTop >= 0)
        {
            /* get top element */
            PDBGGUISTATSNODE pNode  = Stack.a[Stack.iTop].pNode;
            uint32_t         iChild = ++Stack.a[Stack.iTop].iChild;
            if (iChild < pNode->cChildren)
            {
                /* push */
                Stack.iTop++;
                Assert(Stack.iTop < (int32_t)RT_ELEMENTS(Stack.a));
                Stack.a[Stack.iTop].pNode = pNode->papChildren[iChild];
                Stack.a[Stack.iTop].iChild = 0;
            }
            else
            {
                /* pop */
                Stack.iTop--;

                /* do the actual work. */
                iChild = 0;
                while (iChild < pNode->cChildren)
                {
                    /* skip to the first needing updating. */
                    while (     iChild < pNode->cChildren
                           &&   pNode->papChildren[iChild]->enmState != kDbgGuiStatsNodeState_kRefresh)
                        iChild++;
                    if (iChild >= pNode->cChildren)
                        break;
                    QModelIndex TopLeft = createIndex(iChild, 0, pNode->papChildren[iChild]);
                    pNode->papChildren[iChild]->enmState = kDbgGuiStatsNodeState_kVisible;

                    /* any subsequent nodes that also needs refreshing? */
                    if (   ++iChild < pNode->cChildren
                        && pNode->papChildren[iChild]->enmState == kDbgGuiStatsNodeState_kRefresh)
                    {
                        do  pNode->papChildren[iChild]->enmState = kDbgGuiStatsNodeState_kVisible;
                        while (   ++iChild < pNode->cChildren
                               && pNode->papChildren[iChild]->enmState == kDbgGuiStatsNodeState_kRefresh);
                        QModelIndex BottomRight = createIndex(iChild - 1, DBGGUI_STATS_COLUMNS - 1, pNode->papChildren[iChild - 1]);

                        /* emit the refresh signal */
                        emit dataChanged(TopLeft, BottomRight);
                    }
                    else
                    {
                        /* emit the refresh signal */
                        emit dataChanged(TopLeft, TopLeft);
                    }
                }
            }
        }
        /* emit layoutChanged(); - hrmpf, doesn't work reliably... */
    }

    return m_fUpdateInsertRemove;
}


bool
VBoxDbgStatsModel::updateStatsByPattern(const QString &a_rPatStr)
{
    /* stub */
    NOREF(a_rPatStr);
    return false;
}


void
VBoxDbgStatsModel::updateStatsByIndex(QModelIndex const &a_rIndex)
{
    /** @todo implement this based on updateStatsByPattern. */
    NOREF(a_rIndex);
}


void
VBoxDbgStatsModel::resetStatsByPattern(QString const &a_rPatStr)
{
    /* stub */
    NOREF(a_rPatStr);
}


void
VBoxDbgStatsModel::resetStatsByIndex(QModelIndex const &a_rIndex, bool fSubTree /*= true*/)
{
    PCDBGGUISTATSNODE pNode = nodeFromIndex(a_rIndex);
    if (pNode == m_pRoot || !a_rIndex.isValid())
    {
        if (fSubTree)
        {
            /* everything from the root down. */
            resetStatsByPattern(QString());
        }
    }
    else if (pNode)
    {
        /* the node pattern. */
        char szPat[1024+1024+4];
        ssize_t cch = getNodePath(pNode, szPat, 1024);
        AssertReturnVoid(cch >= 0);

        /* the sub-tree pattern. */
        if (fSubTree && pNode->cChildren)
        {
            char *psz = &szPat[cch];
            *psz++ = '|';
            memcpy(psz, szPat, cch);
            psz += cch;
            *psz++ = '/';
            *psz++ = '*';
            *psz++ = '\0';
        }

        resetStatsByPattern(szPat);
    }
}


void
VBoxDbgStatsModel::iterateStatsByPattern(QString const &a_rPatStr, VBoxDbgStatsModel::FNITERATOR *a_pfnCallback, void *a_pvUser,
                                         bool a_fMatchChildren /*= true*/)
{
    const QByteArray   &PatBytes   = a_rPatStr.toUtf8();
    const char * const  pszPattern = PatBytes.constData();
    size_t const        cchPattern = strlen(pszPattern);

    DBGGUISTATSSTACK Stack;
    Stack.a[0].pNode   = m_pRoot;
    Stack.a[0].iChild  = 0;
    Stack.a[0].cchName = 0;
    Stack.iTop         = 0;

    char szName[1024];
    szName[0] = '\0';

    while (Stack.iTop >= 0)
    {
        /* get top element */
        PDBGGUISTATSNODE const pNode   = Stack.a[Stack.iTop].pNode;
        uint16_t               cchName = Stack.a[Stack.iTop].cchName;
        uint32_t const         iChild  = Stack.a[Stack.iTop].iChild++;
        if (iChild < pNode->cChildren)
        {
            PDBGGUISTATSNODE pChild = pNode->papChildren[iChild];

            /* Build the name and match the pattern. */
            Assert(cchName + 1 + pChild->cchName < sizeof(szName));
            szName[cchName++] = '/';
            memcpy(&szName[cchName], pChild->pszName, pChild->cchName);
            cchName += (uint16_t)pChild->cchName;
            szName[cchName] = '\0';

            if (RTStrSimplePatternMultiMatch(pszPattern, cchPattern, szName, cchName, NULL))
            {
                /* Do callback. */
                QModelIndex const Index = createIndex(iChild, 0, pChild);
                if (!a_pfnCallback(pChild, Index, szName, a_pvUser))
                    return;
                if (!a_fMatchChildren)
                    continue;
            }

            /* push */
            Stack.iTop++;
            Assert(Stack.iTop < (int32_t)RT_ELEMENTS(Stack.a));
            Stack.a[Stack.iTop].pNode   = pChild;
            Stack.a[Stack.iTop].iChild  = 0;
            Stack.a[Stack.iTop].cchName = cchName;
        }
        else
        {
            /* pop */
            Stack.iTop--;
        }
    }
}


QModelIndex
VBoxDbgStatsModel::getRootIndex(void) const
{
    if (!m_pRoot)
        return QModelIndex();
    return createIndex(0, 0, m_pRoot);
}


void
VBoxDbgStatsModel::setRootNode(PDBGGUISTATSNODE a_pRoot)
{
    PDBGGUISTATSNODE pOldTree = m_pRoot;
    m_pRoot = a_pRoot;
    destroyTree(pOldTree);
    beginResetModel();
    endResetModel();
}


Qt::ItemFlags
VBoxDbgStatsModel::flags(const QModelIndex &a_rIndex) const
{
    Qt::ItemFlags fFlags = QAbstractItemModel::flags(a_rIndex);
    return fFlags;
}


int
VBoxDbgStatsModel::columnCount(const QModelIndex &a_rParent) const
{
    NOREF(a_rParent);
    return DBGGUI_STATS_COLUMNS;
}


int
VBoxDbgStatsModel::rowCount(const QModelIndex &a_rParent) const
{
    PDBGGUISTATSNODE pParent = nodeFromIndex(a_rParent);
    return pParent ? pParent->cChildren : 1 /* root */;
}


bool
VBoxDbgStatsModel::hasChildren(const QModelIndex &a_rParent) const
{
    PDBGGUISTATSNODE pParent = nodeFromIndex(a_rParent);
    return pParent ? pParent->cChildren > 0 : true /* root */;
}


QModelIndex
VBoxDbgStatsModel::index(int iRow, int iColumn, const QModelIndex &a_rParent) const
{
    PDBGGUISTATSNODE pParent = nodeFromIndex(a_rParent);
    if (!pParent)
    {
        if (    a_rParent.isValid()
            ||  iRow
            ||  (unsigned)iColumn < DBGGUI_STATS_COLUMNS)
        {
            Assert(!a_rParent.isValid());
            Assert(!iRow);
            Assert((unsigned)iColumn < DBGGUI_STATS_COLUMNS);
            return QModelIndex();
        }

        /* root */
        return createIndex(0, iColumn, m_pRoot);
    }
    if ((unsigned)iRow >= pParent->cChildren)
    {
        Log(("index: iRow=%d >= cChildren=%u (iColumn=%d)\n", iRow, (unsigned)pParent->cChildren, iColumn));
        return QModelIndex(); /* bug? */
    }
    if ((unsigned)iColumn >= DBGGUI_STATS_COLUMNS)
    {
        Log(("index: iColumn=%d (iRow=%d)\n", iColumn, iRow));
        return QModelIndex(); /* bug? */
    }
    PDBGGUISTATSNODE pChild = pParent->papChildren[iRow];
    return createIndex(iRow, iColumn, pChild);
}


QModelIndex
VBoxDbgStatsModel::parent(const QModelIndex &a_rChild) const
{
    PDBGGUISTATSNODE pChild = nodeFromIndex(a_rChild);
    if (!pChild)
    {
        Log(("parent: invalid child\n"));
        return QModelIndex(); /* bug */
    }
    PDBGGUISTATSNODE pParent = pChild->pParent;
    if (!pParent)
        return QModelIndex(); /* ultimate root */

    return createIndex(pParent->iSelf, 0, pParent);
}


QVariant
VBoxDbgStatsModel::headerData(int a_iSection, Qt::Orientation a_eOrientation, int a_eRole) const
{
    if (    a_eOrientation == Qt::Horizontal
        &&  a_eRole == Qt::DisplayRole)
        switch (a_iSection)
        {
            case 0: return tr("Name");
            case 1: return tr("Unit");
            case 2: return tr("Value/Times");
            case 3: return tr("Min");
            case 4: return tr("Average");
            case 5: return tr("Max");
            case 6: return tr("Total");
            case 7: return tr("dInt");
            case 8: return tr("Description");
            default:
                AssertCompile(DBGGUI_STATS_COLUMNS == 9);
                return QVariant(); /* bug */
        }
    else if (   a_eOrientation == Qt::Horizontal
             && a_eRole == Qt::TextAlignmentRole)
        switch (a_iSection)
        {
            case 0:
            case 1:
                return QVariant();
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
                return (int)(Qt::AlignRight | Qt::AlignVCenter);
            case 8:
                return QVariant();
            default:
                AssertCompile(DBGGUI_STATS_COLUMNS == 9);
                return QVariant(); /* bug */
        }

    return QVariant();
}


/*static*/ QString
VBoxDbgStatsModel::strUnit(PCDBGGUISTATSNODE pNode)
{
    return pNode->pszUnit;
}


/*static*/ QString
VBoxDbgStatsModel::strValueTimes(PCDBGGUISTATSNODE pNode)
{
    char sz[128];

    switch (pNode->enmType)
    {
        case STAMTYPE_COUNTER:
            return formatNumber(sz, pNode->Data.Counter.c);

        case STAMTYPE_PROFILE:
        case STAMTYPE_PROFILE_ADV:
            if (!pNode->Data.Profile.cPeriods)
                return "0";
            return formatNumber(sz, pNode->Data.Profile.cPeriods);

        case STAMTYPE_RATIO_U32:
        case STAMTYPE_RATIO_U32_RESET:
        {
            char szTmp[64];
            char *psz  = formatNumber(szTmp, pNode->Data.RatioU32.u32A);
            size_t off = strlen(psz);
            memcpy(sz, psz, off);
            sz[off++] = ':';
            strcpy(&sz[off], formatNumber(szTmp, pNode->Data.RatioU32.u32B));
            return sz;
        }

        case STAMTYPE_CALLBACK:
            return *pNode->Data.pStr;

        case STAMTYPE_U8:
        case STAMTYPE_U8_RESET:
            return formatNumber(sz, pNode->Data.u8);

        case STAMTYPE_X8:
        case STAMTYPE_X8_RESET:
            return formatHexNumber(sz, pNode->Data.u8, 2);

        case STAMTYPE_U16:
        case STAMTYPE_U16_RESET:
            return formatNumber(sz, pNode->Data.u16);

        case STAMTYPE_X16:
        case STAMTYPE_X16_RESET:
            return formatHexNumber(sz, pNode->Data.u16, 4);

        case STAMTYPE_U32:
        case STAMTYPE_U32_RESET:
            return formatNumber(sz, pNode->Data.u32);

        case STAMTYPE_X32:
        case STAMTYPE_X32_RESET:
            return formatHexNumber(sz, pNode->Data.u32, 8);

        case STAMTYPE_U64:
        case STAMTYPE_U64_RESET:
            return formatNumber(sz, pNode->Data.u64);

        case STAMTYPE_X64:
        case STAMTYPE_X64_RESET:
            return formatHexNumber(sz, pNode->Data.u64, 16);

        case STAMTYPE_BOOL:
        case STAMTYPE_BOOL_RESET:
            return pNode->Data.f ? "true" : "false";

        default:
            AssertMsgFailed(("%d\n", pNode->enmType));
            RT_FALL_THRU();
        case STAMTYPE_INVALID:
            return "";
    }
}


/*static*/ QString
VBoxDbgStatsModel::strMinValue(PCDBGGUISTATSNODE pNode)
{
    char sz[128];

    switch (pNode->enmType)
    {
        case STAMTYPE_PROFILE:
        case STAMTYPE_PROFILE_ADV:
            if (!pNode->Data.Profile.cPeriods)
                return "0";
            return formatNumber(sz, pNode->Data.Profile.cTicksMin);
        default:
            return "";
    }
}


/*static*/ QString
VBoxDbgStatsModel::strAvgValue(PCDBGGUISTATSNODE pNode)
{
    char sz[128];

    switch (pNode->enmType)
    {
        case STAMTYPE_PROFILE:
        case STAMTYPE_PROFILE_ADV:
            if (!pNode->Data.Profile.cPeriods)
                return "0";
            return formatNumber(sz, pNode->Data.Profile.cTicks / pNode->Data.Profile.cPeriods);
        default:
            return "";
    }
}


/*static*/ QString
VBoxDbgStatsModel::strMaxValue(PCDBGGUISTATSNODE pNode)
{
    char sz[128];

    switch (pNode->enmType)
    {
        case STAMTYPE_PROFILE:
        case STAMTYPE_PROFILE_ADV:
            if (!pNode->Data.Profile.cPeriods)
                return "0";
            return formatNumber(sz, pNode->Data.Profile.cTicksMax);
        default:
            return "";
    }
}


/*static*/ QString
VBoxDbgStatsModel::strTotalValue(PCDBGGUISTATSNODE pNode)
{
    char sz[128];

    switch (pNode->enmType)
    {
        case STAMTYPE_PROFILE:
        case STAMTYPE_PROFILE_ADV:
            if (!pNode->Data.Profile.cPeriods)
                return "0";
            return formatNumber(sz, pNode->Data.Profile.cTicks);
        default:
            return "";
    }
}


/*static*/ QString
VBoxDbgStatsModel::strDeltaValue(PCDBGGUISTATSNODE pNode)
{
    char sz[128];

    switch (pNode->enmType)
    {
        case STAMTYPE_PROFILE:
        case STAMTYPE_PROFILE_ADV:
            if (!pNode->Data.Profile.cPeriods)
                return "0";
            RT_FALL_THRU();
        case STAMTYPE_COUNTER:
        case STAMTYPE_RATIO_U32:
        case STAMTYPE_RATIO_U32_RESET:
        case STAMTYPE_U8:
        case STAMTYPE_U8_RESET:
        case STAMTYPE_X8:
        case STAMTYPE_X8_RESET:
        case STAMTYPE_U16:
        case STAMTYPE_U16_RESET:
        case STAMTYPE_X16:
        case STAMTYPE_X16_RESET:
        case STAMTYPE_U32:
        case STAMTYPE_U32_RESET:
        case STAMTYPE_X32:
        case STAMTYPE_X32_RESET:
        case STAMTYPE_U64:
        case STAMTYPE_U64_RESET:
        case STAMTYPE_X64:
        case STAMTYPE_X64_RESET:
        case STAMTYPE_BOOL:
        case STAMTYPE_BOOL_RESET:
            return formatNumberSigned(sz, pNode->i64Delta);
        default:
            return "";
    }
}


QVariant
VBoxDbgStatsModel::data(const QModelIndex &a_rIndex, int a_eRole) const
{
    unsigned iCol = a_rIndex.column();
    if (iCol >= DBGGUI_STATS_COLUMNS)
        return QVariant();

    if (a_eRole == Qt::DisplayRole)
    {
        PDBGGUISTATSNODE pNode = nodeFromIndex(a_rIndex);
        if (!pNode)
            return QVariant();

        switch (iCol)
        {
            case 0:
                return QString(pNode->pszName);
            case 1:
                return strUnit(pNode);
            case 2:
                return strValueTimes(pNode);
            case 3:
                return strMinValue(pNode);
            case 4:
                return strAvgValue(pNode);
            case 5:
                return strMaxValue(pNode);
            case 6:
                return strTotalValue(pNode);
            case 7:
                return strDeltaValue(pNode);
            case 8:
                return pNode->pDescStr ? QString(*pNode->pDescStr) : QString("");
            default:
                AssertCompile(DBGGUI_STATS_COLUMNS == 9);
                return QVariant();
        }
    }
    else if (a_eRole == Qt::TextAlignmentRole)
        switch (iCol)
        {
            case 0:
            case 1:
                return QVariant();
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
                return (int)(Qt::AlignRight | Qt::AlignVCenter);
            case 8:
                return QVariant();
            default:
                AssertCompile(DBGGUI_STATS_COLUMNS == 9);
                return QVariant(); /* bug */
        }
    return QVariant();
}


/*static*/ void
VBoxDbgStatsModel::stringifyNodeNoRecursion(PDBGGUISTATSNODE a_pNode, QString &a_rString)
{
    /*
     * Get the path, padding it to 32-chars and add it to the string.
     */
    char szBuf[1024];
    ssize_t off = getNodePath(a_pNode, szBuf, sizeof(szBuf) - 2);
    AssertReturnVoid(off >= 0);
    if (off < 32)
    {
        memset(&szBuf[off], ' ', 32 - off);
        szBuf[32] = '\0';
        off = 32;
    }
    szBuf[off++] = ' ';
    szBuf[off]   = '\0';
    a_rString += szBuf;

    /*
     * The following is derived from stamR3PrintOne, except
     * we print to szBuf, do no visibility checks and can skip
     * the path bit.
     */
    switch (a_pNode->enmType)
    {
        case STAMTYPE_COUNTER:
            RTStrPrintf(szBuf, sizeof(szBuf), "%8llu %s", a_pNode->Data.Counter.c, a_pNode->pszUnit);
            break;

        case STAMTYPE_PROFILE:
        case STAMTYPE_PROFILE_ADV:
        {
            uint64_t u64 = a_pNode->Data.Profile.cPeriods ? a_pNode->Data.Profile.cPeriods : 1;
            RTStrPrintf(szBuf, sizeof(szBuf),
                        "%8llu %s (%12llu ticks, %7llu times, max %9llu, min %7lld)",
                        a_pNode->Data.Profile.cTicks / u64, a_pNode->pszUnit,
                        a_pNode->Data.Profile.cTicks, a_pNode->Data.Profile.cPeriods, a_pNode->Data.Profile.cTicksMax, a_pNode->Data.Profile.cTicksMin);
            break;
        }

        case STAMTYPE_RATIO_U32:
        case STAMTYPE_RATIO_U32_RESET:
            RTStrPrintf(szBuf, sizeof(szBuf),
                        "%8u:%-8u %s",
                        a_pNode->Data.RatioU32.u32A, a_pNode->Data.RatioU32.u32B, a_pNode->pszUnit);
            break;

        case STAMTYPE_CALLBACK:
            if (a_pNode->Data.pStr)
                a_rString += *a_pNode->Data.pStr;
            RTStrPrintf(szBuf, sizeof(szBuf), " %s", a_pNode->pszUnit);
            break;

        case STAMTYPE_U8:
        case STAMTYPE_U8_RESET:
            RTStrPrintf(szBuf, sizeof(szBuf), "%8u %s", a_pNode->Data.u8, a_pNode->pszUnit);
            break;

        case STAMTYPE_X8:
        case STAMTYPE_X8_RESET:
            RTStrPrintf(szBuf, sizeof(szBuf), "%8x %s", a_pNode->Data.u8, a_pNode->pszUnit);
            break;

        case STAMTYPE_U16:
        case STAMTYPE_U16_RESET:
            RTStrPrintf(szBuf, sizeof(szBuf), "%8u %s", a_pNode->Data.u16, a_pNode->pszUnit);
            break;

        case STAMTYPE_X16:
        case STAMTYPE_X16_RESET:
            RTStrPrintf(szBuf, sizeof(szBuf), "%8x %s", a_pNode->Data.u16, a_pNode->pszUnit);
            break;

        case STAMTYPE_U32:
        case STAMTYPE_U32_RESET:
            RTStrPrintf(szBuf, sizeof(szBuf), "%8u %s", a_pNode->Data.u32, a_pNode->pszUnit);
            break;

        case STAMTYPE_X32:
        case STAMTYPE_X32_RESET:
            RTStrPrintf(szBuf, sizeof(szBuf), "%8x %s", a_pNode->Data.u32, a_pNode->pszUnit);
            break;

        case STAMTYPE_U64:
        case STAMTYPE_U64_RESET:
            RTStrPrintf(szBuf, sizeof(szBuf), "%8llu %s", a_pNode->Data.u64, a_pNode->pszUnit);
            break;

        case STAMTYPE_X64:
        case STAMTYPE_X64_RESET:
            RTStrPrintf(szBuf, sizeof(szBuf), "%8llx %s", a_pNode->Data.u64, a_pNode->pszUnit);
            break;

        case STAMTYPE_BOOL:
        case STAMTYPE_BOOL_RESET:
            RTStrPrintf(szBuf, sizeof(szBuf), "%s %s", a_pNode->Data.f ? "true    " : "false   ", a_pNode->pszUnit);
            break;

        default:
            AssertMsgFailed(("enmType=%d\n", a_pNode->enmType));
            return;
    }

    a_rString += szBuf;
}


/*static*/ void
VBoxDbgStatsModel::stringifyNode(PDBGGUISTATSNODE a_pNode, QString &a_rString)
{
    /* this node (if it has data) */
    if (a_pNode->enmType != STAMTYPE_INVALID)
    {
        if (!a_rString.isEmpty())
            a_rString += "\n";
        stringifyNodeNoRecursion(a_pNode, a_rString);
    }

    /* the children */
    uint32_t const cChildren = a_pNode->cChildren;
    for (uint32_t i = 0; i < cChildren; i++)
        stringifyNode(a_pNode->papChildren[i], a_rString);
}


void
VBoxDbgStatsModel::stringifyTree(QModelIndex &a_rRoot, QString &a_rString) const
{
    PDBGGUISTATSNODE pRoot = a_rRoot.isValid() ? nodeFromIndex(a_rRoot) : m_pRoot;
    if (pRoot)
        stringifyNode(pRoot, a_rString);
}


void
VBoxDbgStatsModel::copyTreeToClipboard(QModelIndex &a_rRoot) const
{
    QString String;
    stringifyTree(a_rRoot, String);

    QClipboard *pClipboard = QApplication::clipboard();
    if (pClipboard)
        pClipboard->setText(String, QClipboard::Clipboard);
}


/*static*/ void
VBoxDbgStatsModel::logNode(PDBGGUISTATSNODE a_pNode, bool a_fReleaseLog)
{
    /* this node (if it has data) */
    if (a_pNode->enmType != STAMTYPE_INVALID)
    {
        QString SelfStr;
        stringifyNodeNoRecursion(a_pNode, SelfStr);
        QByteArray SelfByteArray = SelfStr.toUtf8();
        if (a_fReleaseLog)
            RTLogRelPrintf("%s\n", SelfByteArray.constData());
        else
            RTLogPrintf("%s\n", SelfByteArray.constData());
    }

    /* the children */
    uint32_t const cChildren = a_pNode->cChildren;
    for (uint32_t i = 0; i < cChildren; i++)
        logNode(a_pNode->papChildren[i], a_fReleaseLog);
}


void
VBoxDbgStatsModel::logTree(QModelIndex &a_rRoot, bool a_fReleaseLog) const
{
    PDBGGUISTATSNODE pRoot = a_rRoot.isValid() ? nodeFromIndex(a_rRoot) : m_pRoot;
    if (pRoot)
        logNode(pRoot, a_fReleaseLog);
}







/*
 *
 *      V B o x D b g S t a t s M o d e l V M
 *      V B o x D b g S t a t s M o d e l V M
 *      V B o x D b g S t a t s M o d e l V M
 *
 *
 */


VBoxDbgStatsModelVM::VBoxDbgStatsModelVM(VBoxDbgGui *a_pDbgGui, QString &a_rPatStr, QObject *a_pParent, PCVMMR3VTABLE a_pVMM)
    : VBoxDbgStatsModel(a_pParent), VBoxDbgBase(a_pDbgGui), m_pVMM(a_pVMM)
{
    /*
     * Create a model containing the STAM entries matching the pattern.
     * (The original idea was to get everything and rely on some hide/visible
     * flag that it turned out didn't exist.)
     */
    PDBGGUISTATSNODE pTree = createNewTree(a_rPatStr);
    setRootNode(pTree);
}


VBoxDbgStatsModelVM::~VBoxDbgStatsModelVM()
{
    /* nothing to do here. */
}


bool
VBoxDbgStatsModelVM::updateStatsByPattern(const QString &a_rPatStr)
{
    /** @todo the way we update this stuff is independent of the source (XML, file, STAM), our only
     * ASSUMPTION is that the input is strictly ordered by (fully slashed) name. So, all this stuff
     * should really move up into the parent class. */
    bool fRc = updatePrepare();
    if (fRc)
    {
        int rc = stamEnum(a_rPatStr, updateCallback, this);
        fRc = updateDone(RT_SUCCESS(rc));
    }
    return fRc;
}


void
VBoxDbgStatsModelVM::resetStatsByPattern(QString const &a_rPatStr)
{
    stamReset(a_rPatStr);
}


/*static*/ DECLCALLBACK(int)
VBoxDbgStatsModelVM::createNewTreeCallback(const char *pszName, STAMTYPE enmType, void *pvSample, STAMUNIT enmUnit,
                                           const char *pszUnit, STAMVISIBILITY enmVisibility, const char *pszDesc, void *pvUser)
{
    PDBGGUISTATSNODE pRoot = (PDBGGUISTATSNODE)pvUser;
    Log3(("createNewTreeCallback: %s\n", pszName));
    RT_NOREF(enmUnit);

    /*
     * Skip the ones which shouldn't be visible in the GUI.
     */
    if (enmVisibility == STAMVISIBILITY_NOT_GUI)
        return 0;

    /*
     * Perform a mkdir -p like operation till we've walked / created the entire path down
     * to the node specfied node. Remember the last node as that will be the one we will
     * stuff the data into.
     */
    AssertReturn(*pszName == '/' && pszName[1] != '/', VERR_INTERNAL_ERROR);
    PDBGGUISTATSNODE pNode = pRoot;
    const char *pszCur = pszName + 1;
    while (*pszCur)
    {
        /* find the end of this component. */
        const char *pszNext = strchr(pszCur, '/');
        if (!pszNext)
            pszNext = strchr(pszCur, '\0');
        size_t cchCur = pszNext - pszCur;

        /* Create it if it doesn't exist (it will be last if it exists). */
        if (    !pNode->cChildren
            ||  strncmp(pNode->papChildren[pNode->cChildren - 1]->pszName, pszCur, cchCur)
            ||  pNode->papChildren[pNode->cChildren - 1]->pszName[cchCur])
        {
            pNode = createAndInsertNode(pNode, pszCur, pszNext - pszCur, UINT32_MAX);
            if (!pNode)
                return VERR_NO_MEMORY;
        }
        else
            pNode = pNode->papChildren[pNode->cChildren - 1];

        /* Advance */
        pszCur = *pszNext ? pszNext + 1 : pszNext;
    }

    /*
     * Save the data.
     */
    return initNode(pNode, enmType, pvSample, pszUnit, pszDesc);
}


PDBGGUISTATSNODE
VBoxDbgStatsModelVM::createNewTree(QString &a_rPatStr)
{
    PDBGGUISTATSNODE pRoot = createRootNode();
    if (pRoot)
    {
        int rc = stamEnum(a_rPatStr, createNewTreeCallback, pRoot);
        if (RT_SUCCESS(rc))
            return pRoot;

        /* failed, cleanup. */
        destroyTree(pRoot);
    }

    return NULL;
}








/*
 *
 *      V B o x D b g S t a t s V i e w
 *      V B o x D b g S t a t s V i e w
 *      V B o x D b g S t a t s V i e w
 *
 *
 */


VBoxDbgStatsView::VBoxDbgStatsView(VBoxDbgGui *a_pDbgGui, VBoxDbgStatsModel *a_pModel, VBoxDbgStats *a_pParent/* = NULL*/)
    : QTreeView(a_pParent), VBoxDbgBase(a_pDbgGui), m_pModel(a_pModel), m_PatStr(), m_pParent(a_pParent),
    m_pLeafMenu(NULL), m_pBranchMenu(NULL), m_pViewMenu(NULL), m_pCurMenu(NULL), m_CurIndex()

{
    /*
     * Set the model and view defaults.
     */
    setRootIsDecorated(true);
    setModel(m_pModel);
    QModelIndex RootIdx = m_pModel->getRootIndex(); /* This should really be QModelIndex(), but Qt on darwin does wrong things then. */
    setRootIndex(RootIdx);
    setItemsExpandable(true);
    setAlternatingRowColors(true);
    setSelectionBehavior(SelectRows);
    setSelectionMode(SingleSelection);
    /// @todo sorting setSortingEnabled(true);

    /*
     * Create and setup the actions.
     */
    m_pExpandAct   = new QAction("Expand Tree", this);
    m_pCollapseAct = new QAction("Collapse Tree", this);
    m_pRefreshAct  = new QAction("&Refresh", this);
    m_pResetAct    = new QAction("Rese&t", this);
    m_pCopyAct     = new QAction("&Copy", this);
    m_pToLogAct    = new QAction("To &Log", this);
    m_pToRelLogAct = new QAction("T&o Release Log", this);
    m_pAdjColumns  = new QAction("&Adjust Columns", this);

    m_pCopyAct->setShortcut(QKeySequence::Copy);
    m_pExpandAct->setShortcut(QKeySequence("Ctrl+E"));
    m_pCollapseAct->setShortcut(QKeySequence("Ctrl+D"));
    m_pRefreshAct->setShortcut(QKeySequence("Ctrl+R"));
    m_pResetAct->setShortcut(QKeySequence("Alt+R"));
    m_pToLogAct->setShortcut(QKeySequence("Ctrl+Z"));
    m_pToRelLogAct->setShortcut(QKeySequence("Alt+Z"));
    m_pAdjColumns->setShortcut(QKeySequence("Ctrl+A"));

    addAction(m_pCopyAct);
    addAction(m_pExpandAct);
    addAction(m_pCollapseAct);
    addAction(m_pRefreshAct);
    addAction(m_pResetAct);
    addAction(m_pToLogAct);
    addAction(m_pToRelLogAct);
    addAction(m_pAdjColumns);

    connect(m_pExpandAct,   SIGNAL(triggered(bool)), this, SLOT(actExpand()));
    connect(m_pCollapseAct, SIGNAL(triggered(bool)), this, SLOT(actCollapse()));
    connect(m_pRefreshAct,  SIGNAL(triggered(bool)), this, SLOT(actRefresh()));
    connect(m_pResetAct,    SIGNAL(triggered(bool)), this, SLOT(actReset()));
    connect(m_pCopyAct,     SIGNAL(triggered(bool)), this, SLOT(actCopy()));
    connect(m_pToLogAct,    SIGNAL(triggered(bool)), this, SLOT(actToLog()));
    connect(m_pToRelLogAct, SIGNAL(triggered(bool)), this, SLOT(actToRelLog()));
    connect(m_pAdjColumns,  SIGNAL(triggered(bool)), this, SLOT(actAdjColumns()));


    /*
     * Create the menus and populate them.
     */
    setContextMenuPolicy(Qt::DefaultContextMenu);

    m_pLeafMenu = new QMenu();
    m_pLeafMenu->addAction(m_pCopyAct);
    m_pLeafMenu->addAction(m_pRefreshAct);
    m_pLeafMenu->addAction(m_pResetAct);
    m_pLeafMenu->addAction(m_pToLogAct);
    m_pLeafMenu->addAction(m_pToRelLogAct);

    m_pBranchMenu = new QMenu(this);
    m_pBranchMenu->addAction(m_pCopyAct);
    m_pBranchMenu->addAction(m_pRefreshAct);
    m_pBranchMenu->addAction(m_pResetAct);
    m_pBranchMenu->addAction(m_pToLogAct);
    m_pBranchMenu->addAction(m_pToRelLogAct);
    m_pBranchMenu->addSeparator();
    m_pBranchMenu->addAction(m_pExpandAct);
    m_pBranchMenu->addAction(m_pCollapseAct);

    m_pViewMenu = new QMenu();
    m_pViewMenu->addAction(m_pCopyAct);
    m_pViewMenu->addAction(m_pRefreshAct);
    m_pViewMenu->addAction(m_pResetAct);
    m_pViewMenu->addAction(m_pToLogAct);
    m_pViewMenu->addAction(m_pToRelLogAct);
    m_pViewMenu->addSeparator();
    m_pViewMenu->addAction(m_pExpandAct);
    m_pViewMenu->addAction(m_pCollapseAct);
    m_pViewMenu->addSeparator();
    m_pViewMenu->addAction(m_pAdjColumns);

    /* the header menu */
    QHeaderView *pHdrView = header();
    pHdrView->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(pHdrView, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(headerContextMenuRequested(const QPoint &)));
}


VBoxDbgStatsView::~VBoxDbgStatsView()
{
    m_pParent = NULL;
    m_pCurMenu = NULL;
    m_CurIndex = QModelIndex();

#define DELETE_IT(m) if (m) { delete m; m = NULL; } else do {} while (0)
    DELETE_IT(m_pModel);

    DELETE_IT(m_pLeafMenu);
    DELETE_IT(m_pBranchMenu);
    DELETE_IT(m_pViewMenu);

    DELETE_IT(m_pExpandAct);
    DELETE_IT(m_pCollapseAct);
    DELETE_IT(m_pRefreshAct);
    DELETE_IT(m_pResetAct);
    DELETE_IT(m_pCopyAct);
    DELETE_IT(m_pToLogAct);
    DELETE_IT(m_pToRelLogAct);
    DELETE_IT(m_pAdjColumns);
#undef DELETE_IT
}


void
VBoxDbgStatsView::updateStats(const QString &rPatStr)
{
    m_PatStr = rPatStr;
    if (m_pModel->updateStatsByPattern(rPatStr))
        setRootIndex(m_pModel->getRootIndex()); /* hack */
}


void
VBoxDbgStatsView::resizeColumnsToContent()
{
    for (int i = 0; i <= 8; i++)
    {
        resizeColumnToContents(i);
        /* Some extra room for distinguishing numbers better in Value, Min, Avg, Max, Total, dInt columns. */
        if (i >= 2 && i <= 7)
            setColumnWidth(i, columnWidth(i) + 10);
    }
}


/*static*/ bool
VBoxDbgStatsView::expandMatchingCallback(PDBGGUISTATSNODE pNode, QModelIndex const &a_rIndex,
                                         const char *pszFullName, void *pvUser)
{
    VBoxDbgStatsView *pThis = (VBoxDbgStatsView *)pvUser;

    pThis->setExpanded(a_rIndex, true);

    QModelIndex ParentIndex = pThis->m_pModel->parent(a_rIndex);
    while (ParentIndex.isValid() && !pThis->isExpanded(ParentIndex))
    {
        pThis->setExpanded(ParentIndex, true);
        ParentIndex = pThis->m_pModel->parent(ParentIndex);
    }

    RT_NOREF(pNode, pszFullName);
    return true;
}


void
VBoxDbgStatsView::expandMatching(const QString &rPatStr)
{
    m_pModel->iterateStatsByPattern(rPatStr, expandMatchingCallback, this);
}


void
VBoxDbgStatsView::setSubTreeExpanded(QModelIndex const &a_rIndex, bool a_fExpanded)
{
    int cRows = m_pModel->rowCount(a_rIndex);
    if (a_rIndex.model())
        for (int i = 0; i < cRows; i++)
            setSubTreeExpanded(a_rIndex.model()->index(i, 0, a_rIndex), a_fExpanded);
    setExpanded(a_rIndex, a_fExpanded);
}


void
VBoxDbgStatsView::contextMenuEvent(QContextMenuEvent *a_pEvt)
{
    /*
     * Get the selected item.
     * If it's a mouse event select the item under the cursor (if any).
     */
    QModelIndex Idx;
    if (a_pEvt->reason() == QContextMenuEvent::Mouse)
    {
        Idx = indexAt(a_pEvt->pos());
        if (Idx.isValid())
            setCurrentIndex(Idx);
    }
    else
    {
        QModelIndexList SelIdx = selectedIndexes();
        if (!SelIdx.isEmpty())
            Idx = SelIdx.at(0);
    }

    /*
     * Popup the corresponding menu.
     */
    QMenu *pMenu;
    if (!Idx.isValid())
        pMenu = m_pViewMenu;
    else if (m_pModel->hasChildren(Idx))
        pMenu = m_pBranchMenu;
    else
        pMenu = m_pLeafMenu;
    if (pMenu)
    {
        m_pRefreshAct->setEnabled(!Idx.isValid() || Idx == m_pModel->getRootIndex());
        m_CurIndex = Idx;
        m_pCurMenu = pMenu;

        pMenu->exec(a_pEvt->globalPos());

        m_pCurMenu = NULL;
        m_CurIndex = QModelIndex();
        if (m_pRefreshAct)
            m_pRefreshAct->setEnabled(true);
    }
    a_pEvt->accept();
}


void
VBoxDbgStatsView::headerContextMenuRequested(const QPoint &a_rPos)
{
    /*
     * Show the view menu.
     */
    if (m_pViewMenu)
    {
        m_pRefreshAct->setEnabled(true);
        m_CurIndex = m_pModel->getRootIndex();
        m_pCurMenu = m_pViewMenu;

        m_pViewMenu->exec(header()->mapToGlobal(a_rPos));

        m_pCurMenu = NULL;
        m_CurIndex = QModelIndex();
        if (m_pRefreshAct)
            m_pRefreshAct->setEnabled(true);
    }
}


void
VBoxDbgStatsView::actExpand()
{
    QModelIndex Idx = m_pCurMenu ? m_CurIndex : currentIndex();
    if (Idx.isValid())
        setSubTreeExpanded(Idx, true /* a_fExpanded */);
}


void
VBoxDbgStatsView::actCollapse()
{
    QModelIndex Idx = m_pCurMenu ? m_CurIndex : currentIndex();
    if (Idx.isValid())
        setSubTreeExpanded(Idx, false /* a_fExpanded */);
}


void
VBoxDbgStatsView::actRefresh()
{
    QModelIndex Idx = m_pCurMenu ? m_CurIndex : currentIndex();
    if (!Idx.isValid() || Idx == m_pModel->getRootIndex())
    {
        if (m_pModel->updateStatsByPattern(m_PatStr))
            setRootIndex(m_pModel->getRootIndex()); /* hack */
    }
    else
        m_pModel->updateStatsByIndex(Idx);
}


void
VBoxDbgStatsView::actReset()
{
    QModelIndex Idx = m_pCurMenu ? m_CurIndex : currentIndex();
    if (!Idx.isValid() || Idx == m_pModel->getRootIndex())
        m_pModel->resetStatsByPattern(m_PatStr);
    else
        m_pModel->resetStatsByIndex(Idx);
}


void
VBoxDbgStatsView::actCopy()
{
    QModelIndex Idx = m_pCurMenu ? m_CurIndex : currentIndex();
    m_pModel->copyTreeToClipboard(Idx);
}


void
VBoxDbgStatsView::actToLog()
{
    QModelIndex Idx = m_pCurMenu ? m_CurIndex : currentIndex();
    m_pModel->logTree(Idx, false /* a_fReleaseLog */);
}


void
VBoxDbgStatsView::actToRelLog()
{
    QModelIndex Idx = m_pCurMenu ? m_CurIndex : currentIndex();
    m_pModel->logTree(Idx, true /* a_fReleaseLog */);
}


void
VBoxDbgStatsView::actAdjColumns()
{
    resizeColumnsToContent();
}






/*
 *
 *      V B o x D b g S t a t s
 *      V B o x D b g S t a t s
 *      V B o x D b g S t a t s
 *
 *
 */


VBoxDbgStats::VBoxDbgStats(VBoxDbgGui *a_pDbgGui, const char *pszFilter /*= NULL*/, const char *pszExpand /*= NULL*/,
                           unsigned uRefreshRate/* = 0*/, QWidget *pParent/* = NULL*/)
    : VBoxDbgBaseWindow(a_pDbgGui, pParent, "Statistics")
    , m_PatStr(pszFilter), m_pPatCB(NULL), m_uRefreshRate(0), m_pTimer(NULL), m_pView(NULL)
{
    /* Delete dialog on close: */
    setAttribute(Qt::WA_DeleteOnClose);

    /*
     * On top, a horizontal box with the pattern field, buttons and refresh interval.
     */
    QHBoxLayout *pHLayout = new QHBoxLayout;

    QLabel *pLabel = new QLabel(" Pattern ");
    pHLayout->addWidget(pLabel);
    pLabel->setMaximumSize(pLabel->sizeHint());
    pLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);

    m_pPatCB = new QComboBox();
    m_pPatCB->setCompleter(0);
    pHLayout->addWidget(m_pPatCB);
    if (!m_PatStr.isEmpty())
        m_pPatCB->addItem(m_PatStr);
    m_pPatCB->setDuplicatesEnabled(false);
    m_pPatCB->setEditable(true);
    connect(m_pPatCB, SIGNAL(activated(const QString &)), this, SLOT(apply(const QString &)));

    QPushButton *pPB = new QPushButton("&All");
    pHLayout->addWidget(pPB);
    pPB->setMaximumSize(pPB->sizeHint());
    connect(pPB, SIGNAL(clicked()), this, SLOT(applyAll()));

    pLabel = new QLabel("  Interval ");
    pHLayout->addWidget(pLabel);
    pLabel->setMaximumSize(pLabel->sizeHint());
    pLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);

    QSpinBox *pSB = new QSpinBox();
    pHLayout->addWidget(pSB);
    pSB->setMinimum(0);
    pSB->setMaximum(60);
    pSB->setSingleStep(1);
    pSB->setValue(uRefreshRate);
    pSB->setSuffix(" s");
    pSB->setWrapping(false);
    pSB->setButtonSymbols(QSpinBox::PlusMinus);
    pSB->setMaximumSize(pSB->sizeHint());
    connect(pSB, SIGNAL(valueChanged(int)), this, SLOT(setRefresh(int)));

    /*
     * Create the tree view and setup the layout.
     */
    VBoxDbgStatsModelVM *pModel = new VBoxDbgStatsModelVM(a_pDbgGui, m_PatStr, NULL, a_pDbgGui->getVMMFunctionTable());
    m_pView = new VBoxDbgStatsView(a_pDbgGui, pModel, this);

    QWidget *pHBox = new QWidget;
    pHBox->setLayout(pHLayout);

    QVBoxLayout *pVLayout = new QVBoxLayout;
    pVLayout->addWidget(pHBox);
    pVLayout->addWidget(m_pView);
    setLayout(pVLayout);

    /*
     * Resize the columns.
     * Seems this has to be done with all nodes expanded.
     */
    m_pView->expandAll();
    m_pView->resizeColumnsToContent();
    m_pView->collapseAll();

    if (pszExpand && *pszExpand)
        m_pView->expandMatching(QString(pszExpand));

    /*
     * Create a refresh timer and start it.
     */
    m_pTimer = new QTimer(this);
    connect(m_pTimer, SIGNAL(timeout()), this, SLOT(refresh()));
    setRefresh(uRefreshRate);

    /*
     * And some shortcuts.
     */
    m_pFocusToPat = new QAction("", this);
    m_pFocusToPat->setShortcut(QKeySequence("Ctrl+L"));
    addAction(m_pFocusToPat);
    connect(m_pFocusToPat, SIGNAL(triggered(bool)), this, SLOT(actFocusToPat()));
}


VBoxDbgStats::~VBoxDbgStats()
{
    if (m_pTimer)
    {
        delete m_pTimer;
        m_pTimer = NULL;
    }

    if (m_pPatCB)
    {
        delete m_pPatCB;
        m_pPatCB = NULL;
    }

    if (m_pView)
    {
        delete m_pView;
        m_pView = NULL;
    }
}


void
VBoxDbgStats::closeEvent(QCloseEvent *a_pCloseEvt)
{
    a_pCloseEvt->accept();
}


void
VBoxDbgStats::apply(const QString &Str)
{
    m_PatStr = Str;
    refresh();
}


void
VBoxDbgStats::applyAll()
{
    apply("");
}



void
VBoxDbgStats::refresh()
{
    m_pView->updateStats(m_PatStr);
}


void
VBoxDbgStats::setRefresh(int iRefresh)
{
    if ((unsigned)iRefresh != m_uRefreshRate)
    {
        if (!m_uRefreshRate || iRefresh)
            m_pTimer->start(iRefresh * 1000);
        else
            m_pTimer->stop();
        m_uRefreshRate = iRefresh;
    }
}


void
VBoxDbgStats::actFocusToPat()
{
    if (!m_pPatCB->hasFocus())
        m_pPatCB->setFocus(Qt::ShortcutFocusReason);
}