Skip to content

c2f4dt.main_window

c2f4dt.main_window

MainWindow

Bases: QMainWindow

Main GUI window for C2F4DT.

This class manages the main application window, including the menu, toolbars, status bar, central widgets, plugin management, and the 3D/2D viewers. It also handles the import and visualization of point clouds and meshes, as well as user interactions with the dataset tree.

Source code in src/c2f4dt/main_window.py
 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
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
class MainWindow(QtWidgets.QMainWindow):
    """
    Main GUI window for C2F4DT.

    This class manages the main application window, including the menu, toolbars, status bar,
    central widgets, plugin management, and the 3D/2D viewers. It also handles the import and
    visualization of point clouds and meshes, as well as user interactions with the dataset tree.
    """

    def __init__(self, parent: Optional[QtWidgets.QWidget] = None) -> None:
        super().__init__(parent)
        self.setWindowTitle("C2F4DT – Release 1.0")
        apply_user_theme(self)
        self._apply_styles()

        self._compute_initial_geometry()

        self.mcts = {}
        self.mct = {}

        self.undo_stack = QtGui.QUndoStack(self)
        self._build_actions()
        self._build_menus()
        self._build_toolbars()
        self._build_central_area()
        self._build_statusbar()

        self.plugin_manager = PluginManager(self, plugins_dir=self._default_plugins_dir())

        self._cloud2fem = Cloud2FEMPlugin(self)

        self._populate_plugins_ui()

        self._start_disk_timer()

        # Debouncer to rebuild the 3D scene once after bursts of changes
        self._rebuild_timer = QtCore.QTimer(self)
        self._rebuild_timer.setSingleShot(True)
        self._rebuild_timer.timeout.connect(self._reset_viewer3d_from_tree)

        self.undo_stack.cleanChanged.connect(self._on_undo_changed)
        self.undo_stack.indexChanged.connect(self._on_undo_changed)
        self._on_undo_changed()

        # Preferences
        self.downsample_method = "random"  # or "voxel"
        self._session_path: Optional[str] = None

        # Tree update guard to avoid cascading on auto-updates/partial states
        # Explicitly ensure the flag exists and starts false
        self._tree_updating = False

        self._mount_cloud2fem_panel()

    def _iter_children(self, item: QtWidgets.QTreeWidgetItem):
        """Yield direct children of *item* safely."""
        for i in range(item.childCount()):
            yield item.child(i)

    def _set_item_checked(self, item: QtWidgets.QTreeWidgetItem, on: bool) -> None:
        """Set the checkbox state of *item* without recursive signal storms."""
        try:
            self._tree_updating = True
            item.setCheckState(0, QtCore.Qt.CheckState.Checked if on else QtCore.Qt.CheckState.Unchecked)
        finally:
            self._tree_updating = False

    @QtCore.Slot(QtWidgets.QTreeWidgetItem, int)
    # def _on_tree_item_changed(self, item: QtWidgets.QTreeWidgetItem, column: int) -> None:
    #     """
    #     Handle checkbox toggles in treeMCTS.

    #     Behavior:
    #     - If 'Tree ➜ Parent check toggles children' is ON, propagate the state to children.
    #     - Toggle dataset visibility for nodes that carry {'kind': 'points'|'mesh'|'normals', 'ds': int}.
    #     - Ensure actors are (re)created when turning visibility ON.
    #     - Keep self.mcts and viewer._datasets['visible'] in sync.
    #     """
    #     # Guard against programmatic changes
    #     if getattr(self, "_tree_updating", False):
    #         return
    #     try:
    #         role = QtCore.Qt.ItemDataRole.UserRole
    #         data = item.data(0, role)
    #         checked = item.checkState(0) == QtCore.Qt.CheckState.Checked
    #         propagate = False
    #         try:
    #             propagate = bool(self.act_tree_propagate.isChecked())
    #         except Exception:
    #             propagate = False

    #         # 1) Propagate to children if requested
    #         if propagate:
    #             try:
    #                 self._tree_updating = True
    #                 for ch in self._iter_children(item):
    #                     ch.setCheckState(0, QtCore.Qt.CheckState.Checked if checked else QtCore.Qt.CheckState.Unchecked)
    #             finally:
    #                 self._tree_updating = False

    #         # 2) If this node maps to a dataset, toggle visibility accordingly
    #         if isinstance(data, dict):
    #             kind = data.get("kind")
    #             ds = data.get("ds")
    #             if isinstance(ds, int) and kind in ("points", "mesh", "normals"):
    #                 if kind in ("points", "mesh"):
    #                     # Main dataset visibility
    #                     self._viewer_set_visibility(kind, ds, bool(checked))
    #                     # Persist visible flag into cache + session dicts
    #                     try:
    #                         self._persist_dataset_prop(ds, "visible", bool(checked))
    #                     except Exception:
    #                         pass
    #                     # If we just turned OFF points, force normals OFF for that ds
    #                     if kind == "points" and not checked:
    #                         try:
    #                             self._viewer_set_visibility("normals", ds, False)
    #                         except Exception:
    #                             pass
    #                 elif kind == "normals":
    #                     # Normals visibility only if dataset exists
    #                     try:
    #                         getattr(self.viewer3d, "set_normals_visibility", lambda *_: None)(ds, bool(checked))
    #                     except Exception:
    #                         pass
    #                     try:
    #                         self._persist_dataset_prop(ds, "normals_visible", bool(checked))
    #                     except Exception:
    #                         pass

    #         # 3) If a parent WITHOUT explicit kind was toggled, and propagate=False,
    #         #    try to reflect the parent checkbox on immediate children that have ds/kind.
    #         if (not propagate) and (not isinstance(data, dict)):
    #             for ch in self._iter_children(item):
    #                 dch = ch.data(0, role)
    #                 if isinstance(dch, dict):
    #                     kind = dch.get("kind")
    #                     ds = dch.get("ds")
    #                     if isinstance(ds, int) and kind in ("points", "mesh", "normals"):
    #                         # Do not change checkbox UI; only re-sync visibility with current child state
    #                         on = ch.checkState(0) == QtCore.Qt.CheckState.Checked
    #                         if kind in ("points", "mesh"):
    #                             self._viewer_set_visibility(kind, ds, bool(on))
    #                         elif kind == "normals":
    #                             try:
    #                                 getattr(self.viewer3d, "set_normals_visibility", lambda *_: None)(ds, bool(on))
    #                             except Exception:
    #                                 pass
    #                         try:
    #                             if kind == "normals":
    #                                 self._persist_dataset_prop(ds, "normals_visible", bool(on))
    #                             else:
    #                                 self._persist_dataset_prop(ds, "visible", bool(on))
    #                         except Exception:
    #                             pass

    #         # 4) Best-effort overlays refresh and viewer refresh
    #         try:
    #             self._reapply_overlays_safe()
    #         except Exception:
    #             pass
    #         try:
    #             self.viewer3d.refresh()
    #         except Exception:
    #             pass
    #     except Exception:
    #         # Avoid breaking the UI due to unexpected data
    #         pass

    #     # 3D view preferences (dataclass-like dict, for settings dialog)
    #     self._view_prefs = {
    #         "bg": (82, 87, 110),
    #         "grid": True,
    #         "points_as_spheres": False,
    #         "colorbar_mode": "vertical-tr",
    #         "colorbar_title": "",
    #     }

    def _schedule_scene_rebuild(self, delay_ms: int = 60) -> None:
        """Schedule a single full-scene rebuild after a short delay (debounced)."""
        try:
            self._rebuild_timer.start(int(max(1, delay_ms)))
        except Exception:
            # Fallback: rebuild immediately
            self._reset_viewer3d_from_tree()

    def _apply_styles(self) -> None:
            """
            Apply custom CSS styles to the main window widgets for a consistent look and feel.
            """
            css = r'''
                    QPushButton#buttonCANCEL {
                        background-color: #c62828;
                        color: white;
                        border: 1px solid #8e0000;
                        padding: 2px 8px;
                        border-radius: 3px;
                    }
                    QPushButton#buttonCANCEL:disabled {
                        background-color: #ef9a9a;
                        color: #333;
                        border-color: #e57373;
                    }

                    QProgressBar#barPROGRESS {
                        border: 1px solid #3c3f41;
                        border-radius: 3px;
                        text-align: center;
                        background: #2b2b2b;
                        color: #e6e6e6;
                    }
                    QProgressBar#barPROGRESS::chunk {
                        background-color: #43a047;
                    }

                    QProgressBar#diskUsageBar {
                        border: 1px solid #3c3f41;
                        border-radius: 3px;
                        background: #2b2b2b;
                        text-align: center;
                        color: #e6e6e6;
                    }
                    QProgressBar#diskUsageBar::chunk {
                        background-color: #5dade2;
                    }
                    '''
            self.setStyleSheet(css)

    def _compute_initial_geometry(self) -> None:
        scr = QtGui.QGuiApplication.screenAt(QtGui.QCursor.pos())
        if scr is None:
            scr = QtGui.QGuiApplication.primaryScreen()
        avail = scr.availableGeometry()
        w = int(avail.width() * 0.78)
        h = int(avail.height() * 0.78)
        x = avail.x() + (avail.width() - w) // 2
        y = avail.y() + (avail.height() - h) // 2
        self.setGeometry(x, y, w, h)

    def _default_plugins_dir(self) -> str:
        base = os.path.dirname(os.path.dirname(__file__))  # .../C2F4DT/c2f4dt
        return os.path.join(base, "c2f4dt/plugins")

    def _build_actions(self) -> None:
        self.act_new = QtGui.QAction(qicon("32x32_document-new.png"), "New", self)
        self.act_new.setShortcut(QtGui.QKeySequence.New)
        self.act_open = QtGui.QAction(qicon("32x32_document-open.png"), "Open…", self)
        self.act_open.setShortcut(QtGui.QKeySequence.Open)
        self.act_save = QtGui.QAction(qicon("32x32_document-save.png"), "Save", self)
        self.act_save.setShortcut(QtGui.QKeySequence.Save)
        self.act_save_as = QtGui.QAction(qicon("32x32_document-save-as.png"), "Save As…", self)
        self.act_save_as.setShortcut(QtGui.QKeySequence.SaveAs)
        self.act_new.triggered.connect(self._on_new_session)
        self.act_open.triggered.connect(self._on_open_session)
        self.act_save.triggered.connect(self._on_save_session)
        self.act_save_as.triggered.connect(self._on_save_session_as)
        self.act_import_cloud = QtGui.QAction(qicon("32x32_import_cloud.png"), "Import Cloud", self)
        self.act_import_cloud.triggered.connect(self._on_import_cloud)

        self.act_undo = self.undo_stack.createUndoAction(self, "Undo"); self.act_undo.setIcon(qicon("32x32_edit-undo.png"))
        self.act_undo.setShortcut(QtGui.QKeySequence.Undo)
        self.act_redo = self.undo_stack.createRedoAction(self, "Redo"); self.act_redo.setIcon(qicon("32x32_edit-redo.png"))
        self.act_redo.setShortcut(QtGui.QKeySequence.Redo)
        self.act_clear = QtGui.QAction(qicon("32x32_edit-clear.png"), "Clear", self)

        self.act_tab_interaction = QtGui.QAction(qicon("32x32_3D_inspector.png"), "Interaction", self)
        self.act_tab_slices = QtGui.QAction(qicon("32x32_slice.png"), "Slices", self)
        self.act_tab_fem = QtGui.QAction(qicon("32x32_mesh_generation.png"), "FEM/Mesh", self)
        self.act_tab_inspector = QtGui.QAction(qicon("32x32_model_info.png"), "Inspector", self)
        self.act_open_2d = QtGui.QAction(qicon("32x32_2D_window.png"), "Open 2D Viewer", self)

        self.act_create_grid = QtGui.QAction(qicon("32x32_grid_generation.png"), "Create Grid", self)
        self.act_toggle_grid = QtGui.QAction(qicon("32x32_3D_grid.png"), "Toggle Grid", self); self.act_toggle_grid.setCheckable(True)
        self.act_toggle_normals = QtGui.QAction(qicon("32x32_normals.png"), "Toggle Normals", self); self.act_toggle_normals.setCheckable(True)

        self.act_fit = QtGui.QAction(qicon("32x32_view-fullscreen.png"), "Fit view", self)
        self.act_xp = QtGui.QAction(qicon("32x32_view_Xp.png"), "View +X", self)
        self.act_xm = QtGui.QAction(qicon("32x32_view_Xm.png"), "View −X", self)
        self.act_yp = QtGui.QAction(qicon("32x32_view_Yp.png"), "View +Y", self)
        self.act_ym = QtGui.QAction(qicon("32x32_view_Ym.png"), "View −Y", self)
        self.act_zp = QtGui.QAction(qicon("32x32_view_Zp.png"), "View +Z", self)
        self.act_zm = QtGui.QAction(qicon("32x32_view_Zm.png"), "View −Z", self)
        self.act_iso_p = QtGui.QAction(qicon("32x32_view_Isometric_p.png"), "Isometric +", self)
        self.act_iso_m = QtGui.QAction(qicon("32x32_view_Isometric_m.png"), "Isometric −", self)
        self.act_invert = QtGui.QAction(qicon("32x32_view_inverted.png"), "Invert view", self)
        self.act_refresh = QtGui.QAction(qicon("32x32_view-refresh.png"), "Refresh", self)

    def _build_menus(self) -> None:
        menubar = self.menuBar()
        m_file = menubar.addMenu("&File")
        for a in [self.act_new, self.act_open, self.act_save, self.act_save_as, self.act_import_cloud]: m_file.addAction(a)
        m_edit = menubar.addMenu("&Edit")
        for a in [self.act_undo, self.act_redo, self.act_clear]: m_edit.addAction(a)
        m_view = menubar.addMenu("&View")
        for a in [self.act_tab_interaction, self.act_tab_slices, self.act_tab_fem, self.act_tab_inspector, self.act_open_2d]: m_view.addAction(a)
        # Add a separator and a new action for 3D View Settings dialog
        self.act_view_settings = QtGui.QAction("3D View Settings…", self)
        self.act_view_settings.setIcon(qicon("32x32_settings.png")) if qicon else None
        self.act_view_settings.triggered.connect(self._on_open_view_settings)
        m_view.addSeparator()
        m_view.addAction(self.act_view_settings)
        m_tools = menubar.addMenu("&Tools")
        for a in [self.act_create_grid, self.act_toggle_grid, self.act_toggle_normals]:
            m_tools.addAction(a)

        # --- Tree behaviour submenu -----------------------------------
        m_tree = m_tools.addMenu("Tree")
        self.act_tree_propagate = QtGui.QAction("Parent check toggles children", self)
        self.act_tree_propagate.setCheckable(True)
        self.act_tree_propagate.setChecked(False)  # default: come ora (propaga ai figli)
        m_tree.addAction(self.act_tree_propagate)


        # Activate Plugins menu
        self.m_plugins = menubar.addMenu("&Plugins")
        self.m_plugins.setToolTipsVisible(True)
        self.m_plugins_about_to_show = False


        # Rendering submenu
        self.act_safe_render = QtGui.QAction("Safe Rendering (macOS)", self)
        self.act_safe_render.setCheckable(True)
        self.act_safe_render.toggled.connect(lambda on: getattr(self.viewer3d, "enable_safe_rendering", lambda *_: None)(on))

        self.act_points_as_spheres = QtGui.QAction("Points as spheres", self)
        self.act_points_as_spheres.setCheckable(True)
        self.act_points_as_spheres.setChecked(True)
        self.act_points_as_spheres.toggled.connect(lambda on: getattr(self.viewer3d, "set_points_as_spheres", lambda *_: None)(on))

        m_render = m_tools.addMenu("Rendering")
        m_render.addAction(self.act_safe_render)
        m_render.addAction(self.act_points_as_spheres)

        # Downsampling submenu (import-time behavior)
        m_ds = m_tools.addMenu("Downsampling")
        group_ds = QtGui.QActionGroup(self)
        group_ds.setExclusive(True)
        self.act_ds_random = QtGui.QAction("Random (accurate %)", self, checkable=True)
        self.act_ds_voxel = QtGui.QAction("Voxel (spatial)", self, checkable=True)
        self.act_ds_random.setChecked(True)
        for a in (self.act_ds_random, self.act_ds_voxel):
            group_ds.addAction(a)
            m_ds.addAction(a)
        self.act_ds_random.triggered.connect(lambda: setattr(self, "downsample_method", "random"))
        self.act_ds_voxel.triggered.connect(lambda: setattr(self, "downsample_method", "voxel"))

        # Testing submenu: run external Python scripts in the console context
        m_test = m_tools.addMenu("Testing")
        self.act_run_script = QtGui.QAction("Run Script…", self)
        self.act_run_script.triggered.connect(self._on_run_script)
        m_test.addAction(self.act_run_script)

        # Example convenience action (optional) to run project triplet tests
        self.act_run_triplet = QtGui.QAction("Run Triplet Import (tests/*.ply)", self)
        self.act_run_triplet.triggered.connect(self._on_run_tests_triplet)
        m_test.addAction(self.act_run_triplet)

        menubar.addMenu("&Help")

    def _build_toolbars(self) -> None:
        self.top_toolbar = QtWidgets.QToolBar("barTOPCOMMAND", self)
        self.top_toolbar.setIconSize(QtCore.QSize(32, 32))
        self.addToolBar(QtCore.Qt.TopToolBarArea, self.top_toolbar)

        for a in [self.act_new, self.act_open, self.act_save, self.act_save_as, self.act_import_cloud]:
            self.top_toolbar.addAction(a)
        self.top_toolbar.addSeparator()
        for a in [self.act_undo, self.act_redo, self.act_clear]:
            self.top_toolbar.addAction(a)
        self.top_toolbar.addSeparator()
        for a in [self.act_tab_interaction, self.act_tab_slices, self.act_tab_fem, self.act_tab_inspector, self.act_open_2d]:
            self.top_toolbar.addAction(a)
        self.top_toolbar.addSeparator()
        for a in [self.act_create_grid,  self.act_toggle_normals]:
            self.top_toolbar.addAction(a)

        self.left_toolbar = QtWidgets.QToolBar("barVERTICALCOMMAND_left", self)
        self.left_toolbar.setIconSize(QtCore.QSize(32, 32))
        self.left_toolbar.setOrientation(QtCore.Qt.Vertical)
        self.addToolBar(QtCore.Qt.LeftToolBarArea, self.left_toolbar)
        # for a in [self.act_fit, self.act_refresh, self.act_xp, self.act_xm, self.act_yp, self.act_ym, self.act_zp, self.act_zm, self.act_iso_p, self.act_iso_m, self.act_invert, self.act_toggle_grid,]:
        #     self.left_toolbar.addAction(a)
        for a in [self.act_fit, self.act_refresh, self.act_xp, self.act_yp, self.act_zp,  self.act_iso_p, self.act_iso_m, self.act_invert, self.act_toggle_grid,]:
            self.left_toolbar.addAction(a)

        self.right_toolbar = QtWidgets.QToolBar("barVERTICALCOMMAND_right", self)
        self.right_toolbar.setIconSize(QtCore.QSize(32, 32))
        self.right_toolbar.setOrientation(QtCore.Qt.Vertical)
        self.addToolBar(QtCore.Qt.RightToolBarArea, self.right_toolbar)

        # Connect view actions
        self.act_fit.triggered.connect(lambda: self.viewer3d.view_fit())
        self.act_xp.triggered.connect(lambda: self.viewer3d.view_axis("+X"))
        self.act_xm.triggered.connect(lambda: self.viewer3d.view_axis("-X"))
        self.act_yp.triggered.connect(lambda: self.viewer3d.view_axis("+Y"))
        self.act_ym.triggered.connect(lambda: self.viewer3d.view_axis("-Y"))
        self.act_zp.triggered.connect(lambda: self.viewer3d.view_axis("+Z"))
        self.act_zm.triggered.connect(lambda: self.viewer3d.view_axis("-Z"))
        self.act_iso_p.triggered.connect(lambda: self.viewer3d.view_iso(True))
        self.act_iso_m.triggered.connect(lambda: self.viewer3d.view_iso(False))
        self.act_invert.triggered.connect(lambda: self.viewer3d.invert_view())
        self.act_refresh.triggered.connect(lambda: self.viewer3d.refresh())
        #
        self.act_toggle_normals.toggled.connect(self._on_toggle_normals_clicked)

        self.act_toggle_grid.toggled.connect(
            lambda on: (
                getattr(self.viewer3d, "set_grid_enabled",
                        getattr(self.viewer3d, "set_grid_visible",
                                getattr(self.viewer3d, "toggle_grid", lambda *_: None)))(on),
                getattr(self.viewer3d, "reapply_overlays",
                        getattr(self.viewer3d, "_apply_overlays", lambda: None))()
            )
        )

    def _mount_cloud2fem_panel(self):
        """Mount Cloud2FEM panel into right toolbar."""
        try:
            hooks = HostHooks(
                window=self,
                viewer3d=self.viewer3d,
                log=lambda lvl, msg: self.txtMessages.appendPlainText(f"[{lvl}] {msg}"),
                progress_begin=lambda title: self._progress_start(title),
                progress_update=lambda p, m: self._import_progress_update(percent=p, message=m),
                progress_end=lambda: self._progress_finish(),
                add_badge=lambda name, txt: self.statusBar().showMessage(f"{name}: {txt}", 2000),
            )
            self._cloud2fem.mount(hooks)
        except Exception:
            pass



    def _build_central_area(self) -> None:
        central = QtWidgets.QWidget(self)
        central_layout = QtWidgets.QVBoxLayout(central)
        central_layout.setContentsMargins(4, 4, 4, 4); central_layout.setSpacing(6)

        mid_split = QtWidgets.QSplitter(QtCore.Qt.Horizontal, central)

        self.tabINTERACTION = QtWidgets.QTabWidget(mid_split)
        self.tabINTERACTION.setObjectName("tabINTERACTION")
        self.tabINTERACTION.setMinimumWidth(334)  # Set minimum width to 320 for better alignment with scrollDISPLAY

        self.tabDISPLAY = QtWidgets.QWidget()
        v = QtWidgets.QVBoxLayout(self.tabDISPLAY); v.setContentsMargins(4, 4, 4, 4)
        split = QtWidgets.QSplitter(QtCore.Qt.Vertical, self.tabDISPLAY)

        self.treeMCTS = QtWidgets.QTreeWidget()
        self.treeMCTS.setHeaderLabels(["Object"]); self.treeMCTS.setColumnCount(1)
        self.treeMCTS.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.treeMCTS.customContextMenuRequested.connect(self._on_tree_context_menu)
        self.treeMCTS.itemSelectionChanged.connect(self._on_tree_selection_changed)
        split.addWidget(self.treeMCTS)


        self.scrollDISPLAY = QtWidgets.QScrollArea(); self.scrollDISPLAY.setWidgetResizable(True)
        self.displayPanel = DisplayPanel(); self.scrollDISPLAY.setWidget(self.displayPanel)
        # --- Wire normals UI from DisplayPanel ---
        dp = self.displayPanel
        dp.sigNormalsStyleChanged.connect(self._on_normals_style_changed)
        dp.sigNormalsColorChanged.connect(self._on_normals_color_changed)
        dp.sigNormalsPercentChanged.connect(self._on_normals_percent_changed)
        dp.sigNormalsScaleChanged.connect(self._on_normals_scale_changed)
        dp.sigComputeNormals.connect(self._on_compute_normals)       # già esistente, riusa il tuo handler
        dp.sigFastNormalsChanged.connect(self._on_fast_normals_toggled)  # opzionale: salva preferenza FAST
        split.addWidget(self.scrollDISPLAY)

        v.addWidget(split)
        self.tabINTERACTION.addTab(self.tabDISPLAY, "DISPLAY")

        self.tabSLICING = QtWidgets.QWidget()
        v2 = QtWidgets.QVBoxLayout(self.tabSLICING)
        self.scrollSLICING = QtWidgets.QScrollArea(); self.scrollSLICING.setWidgetResizable(True)
        v2.addWidget(self.scrollSLICING)
        self.tabINTERACTION.addTab(self.tabSLICING, "SLICING")

        self.tabFEM = QtWidgets.QWidget()
        v3 = QtWidgets.QVBoxLayout(self.tabFEM)
        self.scrollFEM = QtWidgets.QScrollArea(); self.scrollFEM.setWidgetResizable(True)
        v3.addWidget(self.scrollFEM)
        self.tabINTERACTION.addTab(self.tabFEM, "FEM")

        self.tabINSPECTOR = QtWidgets.QWidget()
        v4 = QtWidgets.QVBoxLayout(self.tabINSPECTOR)

        # Top bar with a Refresh button for the Inspector
        bar_ins = QtWidgets.QHBoxLayout()
        bar_ins.addStretch(1)
        self.btnRefreshInspector = QtWidgets.QPushButton("Refresh")
        self.btnRefreshInspector.setObjectName("btnRefreshInspector")
        bar_ins.addWidget(self.btnRefreshInspector)
        v4.addLayout(bar_ins)

        # Tree that shows the current MCT content
        self.treeMCT = QtWidgets.QTreeWidget()
        self.treeMCT.setObjectName("treeMCT")
        self.treeMCT.setHeaderLabels(["Key", "Value"])
        self.treeMCT.setColumnCount(2)
        self.treeMCT.header().setStretchLastSection(True)
        v4.addWidget(self.treeMCT, 1)

        # Hook up refresh
        self.btnRefreshInspector.clicked.connect(self._refresh_inspector_tree)

        self.tabINTERACTION.addTab(self.tabINSPECTOR, "INSPECTOR")

        viewer_container = QtWidgets.QWidget()
        viewer_layout = QtWidgets.QVBoxLayout(viewer_container)
        viewer_layout.setContentsMargins(4, 4, 4, 4); viewer_layout.setSpacing(4)

        bar_plugin = QtWidgets.QHBoxLayout()
        self.comboPlugins = QtWidgets.QComboBox()
        self.comboPlugins.addItem("— No plugins installed —"); self.comboPlugins.setEnabled(False)
        bar_plugin.addWidget(QtWidgets.QLabel("Plugin scope:"))
        bar_plugin.addWidget(self.comboPlugins, 1)
        self.comboPlugins.activated.connect(self._on_plugin_combo_activated)

        viewer_layout.addLayout(bar_plugin)

        self.viewer3d = _Viewer3D()
        viewer_layout.addWidget(self.viewer3d, 1)
        # React to check/uncheck from the MCTS tree (avoid duplicates)
        self.treeMCTS.itemChanged.connect(
            self._on_tree_item_changed,
            QtCore.Qt.ConnectionType.UniqueConnection
        )
        # Ora che viewer3d esiste, aggiorna la visibilità
        self._refresh_tree_visibility()

        mid_split.addWidget(self.tabINTERACTION)
        mid_split.addWidget(viewer_container)
        mid_split.setStretchFactor(0, 0); mid_split.setStretchFactor(1, 1)

        # central_layout.addWidget(mid_split, 1)   # REMOVE this line, replaced by splitter below

        self.tabCONSOLE_AND_MESSAGES = QtWidgets.QTabWidget()
        self.tabMESSAGES = QtWidgets.QWidget()
        vm = QtWidgets.QVBoxLayout(self.tabMESSAGES)
        self.txtMessages = QtWidgets.QPlainTextEdit(); self.txtMessages.setReadOnly(True)
        vm.addWidget(self.txtMessages)
        self.tabCONSOLE_AND_MESSAGES.addTab(self.tabMESSAGES, "Messages")

        self.console = ConsoleWidget(context_provider=self._console_context)
        self.console.sigExecuted.connect(self._on_console_executed)
        self.tabCONSOLE_AND_MESSAGES.addTab(self.console, "Console")

        # central_layout.addWidget(self.tabCONSOLE_AND_MESSAGES, 0)   # REMOVE this line, replaced by splitter below

        # --- Make the upper (interaction+viewer) and lower (messages/console) panes vertically resizable ---
        main_split = QtWidgets.QSplitter(QtCore.Qt.Vertical, central)
        main_split.setObjectName("splitMAIN_VERTICAL")
        main_split.setChildrenCollapsible(False)
        # put the big middle UI (tabs + viewer) on top, and the messages/console tabs below
        main_split.addWidget(mid_split)
        main_split.addWidget(self.tabCONSOLE_AND_MESSAGES)
        # sizing hints: top takes most of the space, bottom a fixed minimum height
        self.tabCONSOLE_AND_MESSAGES.setMinimumHeight(140)  # tweak if you want a different minimum
        main_split.setStretchFactor(0, 1)
        main_split.setStretchFactor(1, 0)
        try:
            # give an initial 80/20 split (best-effort; works after first show)
            main_split.setSizes([self.height() * 4 // 5, self.height() * 1 // 5])
        except Exception:
            pass

        # Add the vertical splitter to the central layout (instead of adding the two widgets separately)
        central_layout.addWidget(main_split, 1)

        self.setCentralWidget(central)

        # Collega il DisplayPanel agli handler specifici.
        # Wire the DisplayPanel to specific handlers.
        self.displayPanel.sigPointSizeChanged.connect(self._on_point_size_changed)
        self.displayPanel.sigPointBudgetChanged.connect(self._on_point_budget_changed)
        self.displayPanel.sigColorModeChanged.connect(self._on_color_mode_changed)
        self.displayPanel.sigSolidColorChanged.connect(self._on_solid_color_changed)
        self.displayPanel.sigColormapChanged.connect(self._on_colormap_changed)
        self.displayPanel.sigMeshRepresentationChanged.connect(self._on_mesh_rep_changed)
        self.displayPanel.sigMeshOpacityChanged.connect(self._on_mesh_opacity_changed)
        # --- Normals visualization ---
        self.displayPanel.sigNormalsStyleChanged.connect(self._on_normals_style_changed)
        self.displayPanel.sigNormalsColorChanged.connect(self._on_normals_color_changed)
        self.displayPanel.sigNormalsPercentChanged.connect(self._on_normals_percent_changed)
        self.displayPanel.sigNormalsScaleChanged.connect(self._on_normals_scale_changed)
        #

    def _on_console_executed(self, cmd: str) -> None:
        """Append executed console command to the MESSAGES panel."""
        try:
            self.txtMessages.appendPlainText(cmd)
        except Exception:
            pass

    def _on_tree_selection_changed(self) -> None:
        """
        Synchronize the `mct` dictionary with the currently selected item in the treeMCTS widget.
        Updates the display panel with the parameters of the selected dataset (point size, budget, color mode, etc).

        This ensures that when a user selects a node in the tree, the display panel reflects the properties
        of the corresponding dataset, allowing for correct editing and visualization.
        """
        item = self.treeMCTS.currentItem()
        if item is None:
            return
        # Find the root (file node) and its name
        root = item
        while root.parent() is not None:
            root = root.parent()
        name = root.text(0)
        entry = self.mcts.get(name)
        if not entry:
            return
        # Find dataset info and ds_index
        info = self._dataset_info_from_item(item)
        ds_index = info.get("ds") if info else None
        #
        # ... dopo aver determinato ds_index / entry_to_use ...
        try:
            ds = self._current_dataset_index()
            if ds is not None:
                recs = getattr(self.viewer3d, "_datasets", [])
                if 0 <= ds < len(recs):
                    nvis = bool(recs[ds].get("normals_visible", False))
                    self.act_toggle_normals.blockSignals(True)
                    self.act_toggle_normals.setChecked(nvis)
                    self.act_toggle_normals.blockSignals(False)
        except Exception:
            pass
        # Select the correct entry if it exists for ds_index
        entry_to_use = entry
        if ds_index is not None:
            for e in self.mcts.values():
                if e.get("ds_index") == ds_index:
                    entry_to_use = e
                    break
        self.mct = entry_to_use
        # Update the display panel with the selected dataset's parameters
        if info:
            self.displayPanel.set_mode(info.get("kind", "points"))
            self.displayPanel.apply_properties(entry_to_use)
        # Keep the INSPECTOR tab in sync with the current MCT
        try:
            self._refresh_inspector_tree()
        except Exception:
            pass


    def _refresh_inspector_tree(self) -> None:
        """Rebuild the Inspector tree from a synthesized snapshot of the current state.
        Includes: current mct entry, viewer settings, per-dataset details and app options.
        """
        try:
            data = self._inspector_current_payload()
            self._populate_inspector_tree(data)
        except Exception:
            # Best effort: clear on failure
            try:
                self.treeMCT.clear()
            except Exception:
                pass

    def _inspector_current_payload(self) -> dict:
        """Collect a rich snapshot of the current session for the INSPECTOR tab.

        Structure:
            {
                'mct': ...,                    # currently selected entry (as-is)
                'options': { ... },            # app/UI options affecting behavior
                'plugins': [ ... ],            # plugins summary from PluginManager
                'viewer': { ... },             # global viewer settings
                'dataset': { ... },            # details for the currently selected dataset
            }
        """
        payload: dict = {}

        # --- mct (as-is) -----------------------------------------------------
        try:
            payload['mct'] = self.mct
        except Exception:
            payload['mct'] = None

        # --- options (app-wide knobs) ----------------------------------------
        opts = {}
        try:
            opts['downsample_method'] = getattr(self, 'downsample_method', None)
        except Exception:
            pass
        # Normals controls (from DisplayPanel if available)
        try:
            fast = None
            if hasattr(self, 'displayPanel') and self.displayPanel is not None:
                # `fast_normals_enabled()` is our helper; fallback to attr
                try:
                    fast = bool(self.displayPanel.fast_normals_enabled())
                except Exception:
                    fast = None
            if fast is None:
                fast = bool(getattr(self, 'normals_fast_enabled', False))
            opts['normals_fast_enabled'] = fast
        except Exception:
            pass
        for k, default in (('normals_k', 16), ('normals_fast_max_points', 250_000)):
            try:
                opts[k] = getattr(self, k)
            except Exception:
                opts[k] = default
        payload['options'] = opts

        # --- plugins summary --------------------------------------------------
        plugs = []
        try:
            items = self.plugin_manager.ui_combo_items()
            for it in items:
                plugs.append({
                    'key': it.get('key'),
                    'label': it.get('label'),
                    'enabled': it.get('enabled', True),
                    'color': it.get('color'),
                    'tooltip': it.get('tooltip', ''),
                    'order': it.get('order'),
                })
        except Exception:
            pass
        payload['plugins'] = plugs

        # --- viewer global settings ------------------------------------------
        viewer = {}
        try:
            v = self.viewer3d
            viewer['color_mode'] = getattr(v, '_color_mode', None)
            viewer['colormap'] = getattr(v, '_cmap', None)
            viewer['point_size'] = getattr(v, '_point_size', None)
            viewer['view_budget_percent'] = getattr(v, '_view_budget_percent', None)
            viewer['points_as_spheres'] = getattr(v, '_points_as_spheres', None)
            # Safe rendering toggle (if exposed via menu action)
            try:
                viewer['safe_rendering'] = bool(self.act_safe_render.isChecked())
            except Exception:
                viewer['safe_rendering'] = None
            # Counts
            try:
                recs = getattr(v, '_datasets', [])
                viewer['datasets_count'] = len(recs)
            except Exception:
                viewer['datasets_count'] = None
        except Exception:
            pass
        payload['viewer'] = viewer

        # --- current dataset details -----------------------------------------
        ds_info = {}
        try:
            ds = self._current_dataset_index()
            ds_info['index'] = ds
            v = self.viewer3d
            recs = getattr(v, '_datasets', [])
            if isinstance(ds, int) and 0 <= ds < len(recs):
                rec = recs[ds]
                # Basic flags
                ds_info['visible'] = bool(rec.get('visible', True))
                ds_info['kind'] = rec.get('kind', 'points')
                ds_info['solid_color'] = tuple(rec.get('solid_color', (1.0, 1.0, 1.0)))
                # PolyData summary
                try:
                    pdata = rec.get('pdata')
                    ds_info['n_points'] = int(getattr(pdata, 'n_points', 0)) if pdata is not None else None
                    ds_info['n_cells'] = int(getattr(pdata, 'n_cells', 0)) if pdata is not None else None
                    # Available arrays
                    pt_names = []
                    try:
                        if hasattr(pdata, 'point_data'):
                            pt_names = list(pdata.point_data.keys())
                    except Exception:
                        pass
                    ds_info['point_arrays'] = pt_names
                except Exception:
                    pass
                # Normals section (per-dataset state kept by viewer)
                norms = {
                    'has_normals_array': False,
                    'normals_visible': bool(rec.get('normals_visible', False)),
                    'normals_style': rec.get('normals_style'),
                    'normals_color': tuple(rec.get('normals_color', (1.0, 0.8, 0.2))),
                    'normals_percent': int(rec.get('normals_percent', getattr(v, '_normals_percent', 1))),
                    'normals_scale': int(rec.get('normals_scale', getattr(v, '_normals_scale', 20))),
                    'actor_exists': rec.get('actor_normals') is not None,
                }
                try:
                    pdata = rec.get('pdata')
                    norms['has_normals_array'] = bool(pdata is not None and ('Normals' in getattr(pdata, 'point_data', {})))
                except Exception:
                    pass
                ds_info['normals'] = norms
            else:
                ds_info['note'] = 'No valid dataset selected.'
        except Exception:
            pass
        payload['dataset'] = ds_info

        return payload

    def _populate_inspector_tree(self, data) -> None:
        """Populate the Inspector QTreeWidget with a nested view of *data*."""
        try:
            self.treeMCT.clear()
        except Exception:
            return

        root = QtWidgets.QTreeWidgetItem(["session", self._format_inspector_value(data)])
        self.treeMCT.addTopLevelItem(root)
        self._inspector_add_children(root, data)
        try:
            self.treeMCT.expandAll()
        except Exception:
            pass

    def _inspector_add_children(self, parent: QtWidgets.QTreeWidgetItem, obj) -> None:
        """Recursive expansion of mappings, sequences, numpy arrays, and PyVista datasets."""
        # Avoid deep expansion of basic/leaf values
        try:
            import numpy as _np
        except Exception:
            _np = None
        try:
            import pyvista as _pv  # type: ignore
        except Exception:
            _pv = None

        # Dict-like
        try:
            from collections.abc import Mapping, Sequence
        except Exception:
            Mapping, Sequence = dict, (list, tuple)  # fallbacks

        if isinstance(obj, Mapping):
            for k, v in obj.items():
                key = str(k)
                val = self._format_inspector_value(v)
                child = QtWidgets.QTreeWidgetItem([key, val])
                parent.addChild(child)
                self._inspector_add_children(child, v)
            return

        # List/tuple-like (but not str/bytes)
        if isinstance(obj, Sequence) and not isinstance(obj, (str, bytes, bytearray)):
            for i, v in enumerate(obj):
                key = f"[{i}]"
                val = self._format_inspector_value(v)
                child = QtWidgets.QTreeWidgetItem([key, val])
                parent.addChild(child)
                self._inspector_add_children(child, v)
            return

        # numpy arrays: show shape/dtype
        if _np is not None and isinstance(obj, _np.ndarray):
            # Already summarized in the value; also expose shape/dtype explicitly
            sh = tuple(obj.shape)
            dt = str(obj.dtype)
            parent.addChild(QtWidgets.QTreeWidgetItem(["shape", str(sh)]))
            parent.addChild(QtWidgets.QTreeWidgetItem(["dtype", dt]))
            return

        # PyVista datasets: summarize counts and arrays
        if _pv is not None and isinstance(obj, _pv.DataSet):
            try:
                parent.addChild(QtWidgets.QTreeWidgetItem(["type", type(obj).__name__]))
            except Exception:
                pass
            try:
                parent.addChild(QtWidgets.QTreeWidgetItem(["n_points", str(getattr(obj, "n_points", "?"))]))
            except Exception:
                pass
            try:
                parent.addChild(QtWidgets.QTreeWidgetItem(["n_cells", str(getattr(obj, "n_cells", "?"))]))
            except Exception:
                pass
            # Point data arrays
            try:
                if hasattr(obj, "point_data") and len(obj.point_data) > 0:
                    pd = QtWidgets.QTreeWidgetItem(["point_data", f"{len(obj.point_data)} arrays"])
                    parent.addChild(pd)
                    for name in obj.point_data.keys():
                        arr = obj.point_data[name]
                        label = f"{name}  shape={getattr(arr, 'shape', '?')} dtype={getattr(arr, 'dtype', '?')}"
                        pd.addChild(QtWidgets.QTreeWidgetItem([name, label]))
            except Exception:
                pass
            # Cell data arrays
            try:
                if hasattr(obj, "cell_data") and len(obj.cell_data) > 0:
                    cd = QtWidgets.QTreeWidgetItem(["cell_data", f"{len(obj.cell_data)} arrays"])
                    parent.addChild(cd)
                    for name in obj.cell_data.keys():
                        arr = obj.cell_data[name]
                        label = f"{name}  shape={getattr(arr, 'shape', '?')} dtype={getattr(arr, 'dtype', '?')}"
                        cd.addChild(QtWidgets.QTreeWidgetItem([name, label]))
            except Exception:
                pass
            return
        # Other types are treated as leaves

    def _format_inspector_value(self, v) -> str:
        """Short one-line summary for Inspector values."""
        try:
            import numpy as _np
        except Exception:
            _np = None
        try:
            import pyvista as _pv  # type: ignore
        except Exception:
            _pv = None

        if v is None:
            return "None"
        if isinstance(v, (bool, int, float, str)):
            return str(v)
        if isinstance(v, dict):
            return f"dict[{len(v)}]"
        if isinstance(v, (list, tuple)):
            return f"{type(v).__name__}[{len(v)}]"
        if _np is not None and isinstance(v, _np.ndarray):
            try:
                return f"ndarray shape={v.shape} dtype={v.dtype}"
            except Exception:
                return "ndarray"
        if _pv is not None and isinstance(v, _pv.DataSet):
            try:
                npts = getattr(v, 'n_points', '?')
                ncells = getattr(v, 'n_cells', '?')
                return f"{type(v).__name__} (pts={npts}, cells={ncells})"
            except Exception:
                return type(v).__name__
        # Generic fallback
        return type(v).__name__

    def _defer(self, ms: int, fn) -> None:
        """Run callable *fn* after *ms* milliseconds on the GUI thread (best-effort)."""
        try:
            QtCore.QTimer.singleShot(int(max(0, ms)), fn)
        except Exception:
            try:
                fn()
            except Exception:
                pass

    def _apply_cached_visuals(self, ds: int) -> None:
        """Reapply cached per-dataset visual properties to the live actor.

        Ensures that after a full-scene rebuild or actor creation, the dataset
        keeps its styling (point size, color mode, colormap, solid color, opacity).
        """
        v = getattr(self, "viewer3d", None)
        if v is None:
            return
        try:
            recs = getattr(v, "_datasets", [])
            if not (isinstance(ds, int) and 0 <= ds < len(recs)):
                return
            rec = recs[ds]
            if "point_size" in rec:
                try:
                    getattr(v, "set_point_size", lambda *_: None)(int(rec.get("point_size", 3)), ds)
                except Exception:
                    pass
            # Point budget / visible percentage for points datasets
            if "point_budget" in rec:
                try:
                    getattr(v, "set_point_budget", lambda *_: None)(int(rec.get("point_budget", 100)), ds)
                except Exception:
                    pass
            if "color_mode" in rec:
                try:
                    getattr(v, "set_color_mode", lambda *_: None)(str(rec.get("color_mode")), ds)
                except Exception:
                    pass
            if "colormap" in rec:
                try:
                    getattr(v, "set_colormap", lambda *_: None)(str(rec.get("colormap")), ds)
                except Exception:
                    pass
            if "solid_color" in rec:
                try:
                    r, g, b = rec["solid_color"]
                    if all(isinstance(c, float) and 0.0 <= c <= 1.0 for c in (r, g, b)):
                        r, g, b = int(r*255), int(g*255), int(b*255)
                    getattr(v, "set_dataset_color", lambda *_: None)(ds, int(r), int(g), int(b))
                except Exception:
                    pass
            if "opacity" in rec:
                try:
                    getattr(v, "set_mesh_opacity", lambda *_: None)(ds, int(rec.get("opacity", 100)))
                except Exception:
                    pass
            # Mesh representation (e.g., 'Surface', 'Wireframe')
            if "representation" in rec:
                try:
                    getattr(v, "set_mesh_representation", lambda *_: None)(ds, str(rec.get("representation")))
                except Exception:
                    pass
            # Points rendering style (if exposed)
            try:
                if "points_as_spheres" in rec:
                    getattr(v, "set_points_as_spheres", lambda *_: None)(bool(rec.get("points_as_spheres", True)))
            except Exception:
                pass
            # Honor cached normals visibility without enabling when False
            try:
                if bool(rec.get("normals_visible", False)):
                    getattr(v, "set_normals_visibility", lambda *_: None)(ds, True)
                else:
                    self._hide_normals_actor(ds)
            except Exception:
                pass
        except Exception:
            pass

    def _hide_normals_actor(self, ds: int) -> None:
        """Ensure normals are hidden for dataset *ds* (actor off + cache flag)."""
        v = getattr(self, "viewer3d", None)
        if v is None:
            return
        try:
            getattr(v, "set_normals_visibility", lambda *_: None)(ds, False)
        except Exception:
            pass
        try:
            recs = getattr(v, "_datasets", [])
            if 0 <= ds < len(recs):
                rec = recs[ds]
                rec["normals_visible"] = False
                act = rec.get("actor_normals") or rec.get("normals_actor")
                if act is not None:
                    try:
                        act.SetVisibility(0)
                    except Exception:
                        try:
                            act.visibility = False  # type: ignore[attr-defined]
                        except Exception:
                            pass
        except Exception:
            pass

    def _reset_viewer3d_from_tree(self) -> None:
        """
        Clear the 3D scene and rebuild visibility/actors of all objects based solely on each node's own check state.
        Also restores normals visibility based on a dedicated 'normals' node or per-dataset state.
        """
        v = getattr(self, "viewer3d", None)
        if v is None:
            return

        # 1) Clear scene
        try:
            if hasattr(v, "clear"):
                v.clear()
            else:
                getattr(v, "refresh", lambda: None)()
        except Exception:
            pass

        # 2) Re-apply according to each dataset node's own check (no propagation)
        normals_requests: list[tuple[int, bool]] = []  # (ds, visible)
        try:
            def recurse(node: QtWidgets.QTreeWidgetItem) -> None:
                data = node.data(0, QtCore.Qt.ItemDataRole.UserRole)
                if isinstance(data, dict):
                    kind = data.get("kind")
                    ds = data.get("ds")
                    if ds is not None and kind in ("points", "mesh", "normals"):
                        visible = self._node_self_checked(node)
                        # Build (or ensure) actors for data-bearing kinds
                        if kind in ("points", "mesh"):
                            # Ensure actor exists before toggling visibility
                            if bool(visible):
                                self._viewer_ensure_actor(kind, int(ds))
                            # Reapply cached visuals after actor creation
                            self._apply_cached_visuals(int(ds))
                            self._viewer_set_visibility(kind, int(ds), bool(visible))
                        elif kind == "normals":
                            normals_requests.append((int(ds), bool(visible)))
                # Recurse
                for i in range(node.childCount()):
                    recurse(node.child(i))

            for i in range(self.treeMCTS.topLevelItemCount()):
                recurse(self.treeMCTS.topLevelItem(i))
        except Exception:
            pass

        # 3) Apply normals visibility AFTER points actors exist
        try:
            for ds, on in normals_requests:
                getattr(v, "set_normals_visibility", lambda *_: None)(ds, bool(on))
                if not on:
                    self._hide_normals_actor(ds)
        except Exception:
            pass

        # 4) If no explicit normals node exists, restore per-dataset state (best effort)
        try:
            recs = getattr(v, "_datasets", [])
            for ds, rec in enumerate(recs):
                want = bool(rec.get("normals_visible", False))
                # Only if we didn't already apply an explicit request for this ds
                if all(ds_req != ds for ds_req, _ in normals_requests):
                    if want:
                        getattr(v, "set_normals_visibility", lambda *_: None)(ds, True)
        except Exception:
            pass

        # 5) Restore overlays (grid, units) and refresh
        try:
            self._restore_default_overlays()
        except Exception:
            pass
        try:
            v.refresh()
        except Exception:
            pass

    def _node_self_checked(self, item: QtWidgets.QTreeWidgetItem) -> bool:
        """Return True if the item's own checkbox is checked (no parent/child propagation)."""
        try:
            return item.checkState(0) == QtCore.Qt.CheckState.Checked
        except Exception:
            return False

    def _reapply_overlays_safe(self) -> None:
        """
        Ask the viewer to re-apply overlays (grid, units overlay, etc.) without changing camera.
        Safe no-op if the viewer does not implement it.
        """
        v = getattr(self, "viewer3d", None)
        if v is None:
            return
        # Prefer a public method if available; otherwise accept a private one.
        for name in ("reapply_overlays", "_apply_overlays"):
            fn = getattr(v, name, None)
            if callable(fn):
                try:
                    fn()
                    return
                except Exception:
                    continue
        # Fallback: ripristina come in _restore_default_overlays
        try:
            self._restore_default_overlays()
        except Exception:
            pass

    def _restore_default_overlays(self) -> None:
        """
        Re-enable default viewer overlays after a full scene reset:
        - Grid (according to toolbar toggle)
        - Units overlay/ruler if UnitsPlugin is available
        """
        v = getattr(self, "viewer3d", None)
        if v is None:
            return
        # Grid
        try:
            on = bool(self.act_toggle_grid.isChecked())
        except Exception:
            on = True
        try:
            for name in ("set_grid_visible", "toggle_grid", "show_grid"):
                fn = getattr(v, name, None)
                if callable(fn):
                    try:
                        fn(on)
                        break
                    except Exception:
                        continue
        except Exception:
            pass
        # Units overlay (best effort)
        try:
            pm = getattr(self, "plugin_manager", None)
            if pm is not None:
                units = None
                for getter in ("get", "plugin_by_key"):
                    fn = getattr(pm, getter, None)
                    if callable(fn):
                        units = fn("units")
                        if units:
                            break
                if units and hasattr(units, "overlay") and hasattr(units, "state"):
                    try:
                        units.overlay.show_text(units.state)
                    except Exception:
                        pass
        except Exception:
            pass

    def _dataset_info_from_item(self, item: QtWidgets.QTreeWidgetItem | None):
        """
        Retrieve dataset info from the given tree item or its neighbors.

        Args:
            item (QtWidgets.QTreeWidgetItem | None): The tree item to extract info from.

        Returns:
            dict | None: The dataset info dictionary if found, otherwise None.
        """
        if item is None:
            return None
        data = item.data(0, QtCore.Qt.ItemDataRole.UserRole)
        if isinstance(data, dict) and data.get("ds") is not None:
            return data
        for i in range(item.childCount()):
            found = self._dataset_info_from_item(item.child(i))
            if found:
                return found
        parent = item.parent()
        if parent is not None:
            return self._dataset_info_from_item(parent)
        return None

    def _viewer_set_visibility(self, kind: str, ds: int, visible: bool) -> None:
        """Toggle dataset visibility in the 3D viewer; ensure actor exists when turning ON.
        Also: when POINTS are OFF, force normals OFF for the same dataset."""
        v = getattr(self, "viewer3d", None)
        if v is None:
            return

        # Ensure actor exists if we are turning ON after a clear()
        if visible and kind in ("points", "mesh"):
            self._viewer_ensure_actor(kind, ds)
        # Re-apply cached visuals so color/colormap don't reset to white defaults
        if visible:
            try:
                self._apply_cached_visuals(ds)
            except Exception:
                pass

        # Preferred explicit API
        for name in ("set_dataset_visibility", "set_visibility", "set_points_visibility", "set_mesh_visibility"):
            fn = getattr(v, name, None)
            if callable(fn):
                try:
                    try:
                        fn(ds, bool(visible))
                    except TypeError:
                        fn(kind, ds, bool(visible))
                    if kind == "points" and not visible:
                        getattr(v, "set_normals_visibility", lambda *_: None)(ds, False)
                    # Persist visible flag into cache + session dicts
                    try:
                        if kind == "points":
                            self._persist_dataset_prop(ds, "visible", bool(visible))
                        elif kind == "mesh":
                            self._persist_dataset_prop(ds, "visible", bool(visible))
                    except Exception:
                        pass
                    v.refresh()
                    return
                except Exception:
                    pass

        # Fallback: cached record + actor toggling
        try:
            recs = getattr(v, "_datasets", [])
            if not (isinstance(ds, int) and 0 <= ds < len(recs)):
                return
            rec = recs[ds]
            rec["visible"] = bool(visible)
            actor = rec.get("actor") or rec.get("actor_mesh") or rec.get("actor_points")
            if actor is None and visible:
                # Try again to build (another safety)
                self._viewer_ensure_actor(kind, ds)
                actor = rec.get("actor") or rec.get("actor_mesh") or rec.get("actor_points")
            # After (re)creating the actor, re-apply cached styling (solid color, colormap, rep, etc.)
            if visible:
                try:
                    self._apply_cached_visuals(ds)
                except Exception:
                    pass
            if actor is not None:
                try:
                    actor.SetVisibility(1 if visible else 0)
                except Exception:
                    try:
                        actor.visibility = bool(visible)  # type: ignore[attr-defined]
                    except Exception:
                        pass
            if kind == "points" and not visible:
                try:
                    getattr(v, "set_normals_visibility", lambda *_: None)(ds, False)
                except Exception:
                    pass
            # Persist visible flag into cache + session dicts
            try:
                if kind == "points":
                    self._persist_dataset_prop(ds, "visible", bool(visible))
                elif kind == "mesh":
                    self._persist_dataset_prop(ds, "visible", bool(visible))
            except Exception:
                pass
            v.refresh()
        except Exception:
            pass

    def _viewer_ensure_actor(self, kind: str, ds: int) -> None:
        """Best-effort: (re)build the actor for dataset `ds` of type `kind`.
        Used after a full viewer clear() or when an actor is missing."""
        v = getattr(self, "viewer3d", None)
        if v is None:
            return
        try:
            recs = getattr(v, "_datasets", [])
            if not (isinstance(ds, int) and 0 <= ds < len(recs)):
                return
            rec = recs[ds]
            # If an actor already exists, nothing to do
            actor = rec.get("actor") or rec.get("actor_mesh") or rec.get("actor_points")
            if actor is not None:
                return

            # Try public/safe rebuild paths first
            for name in ("rebuild_dataset", "ensure_dataset_actor", "build_dataset_actor"):
                fn = getattr(v, name, None)
                if callable(fn):
                    try:
                        fn(ds)
                        try:
                            self._apply_cached_visuals(ds)
                        except Exception:
                            pass
                        return
                    except Exception:
                        pass

            # Fall back to common internal helpers (pyvista-based viewers often have these)
            if kind == "points":
                # common internal name
                for name in ("_rebuild_points_actor", "_update_points_actor", "_ensure_points_actor"):
                    fn = getattr(v, name, None)
                    if callable(fn):
                        try:
                            fn(ds)
                            try:
                                self._apply_cached_visuals(ds)
                            except Exception:
                                pass
                            return
                        except Exception:
                            pass
                # very last resort: add from pdata directly
                pdata = rec.get("pdata") or rec.get("full_pdata")
                if pdata is not None:
                    try:
                        actor = v.plotter.add_mesh(
                            pdata, render_points_as_spheres=bool(rec.get("points_as_spheres", True)),
                            point_size=int(rec.get("point_size", 3)), name=f"points_ds{ds}"
                        )
                        rec["actor_points"] = actor
                        try:
                            self._apply_cached_visuals(ds)
                        except Exception:
                            pass
                    except Exception:
                        pass

            elif kind == "mesh":
                for name in ("_rebuild_mesh_actor", "_update_mesh_actor", "_ensure_mesh_actor"):
                    fn = getattr(v, name, None)
                    if callable(fn):
                        try:
                            fn(ds)
                            try:
                                self._apply_cached_visuals(ds)
                            except Exception:
                                pass
                            return
                        except Exception:
                            pass
                mesh = rec.get("mesh") or rec.get("pdata") or rec.get("full_pdata")
                if mesh is not None:
                    try:
                        actor = v.plotter.add_mesh(
                            mesh,
                            opacity=float(rec.get("opacity", 100))/100.0,
                            name=f"mesh_ds{ds}"
                        )
                        rec["actor_mesh"] = actor
                        try:
                            self._apply_cached_visuals(ds)
                        except Exception:
                            pass
                    except Exception:
                        pass
        except Exception:
            pass

    def _current_dataset_index(self) -> Optional[int]:
        """
        Return the dataset index of the currently selected tree item.

        Returns:
            Optional[int]: The dataset index if available, otherwise None.
        """
        item = self.treeMCTS.currentItem()
        info = self._dataset_info_from_item(item)
        if info:
            return info.get("ds")
        return None

    def _persist_dataset_prop(self, ds: int, key: str, value) -> None:
        """Persist a per‑dataset property both in the viewer cache (self.viewer3d._datasets)
        and in the corresponding entry of self.mcts used for session snapshots.

        Args:
            ds: Dataset index in the viewer cache.
            key: Property name (e.g., 'point_size').
            value: Property value to store.
        """
        # Update viewer cache (used by actor rebuilds)
        try:
            recs = getattr(self.viewer3d, "_datasets", [])
            if isinstance(ds, int) and 0 <= ds < len(recs):
                recs[ds][key] = value
        except Exception:
            pass

        # Update mcts registry snapshot (used by UI + sessions)
        try:
            for e in self.mcts.values():
                if e.get("ds_index") == ds:
                    e[key] = value
        except Exception:
            pass

    def _persist_dataset_color(self, ds: int, rgb_tuple: tuple[int, int, int]) -> None:
        """Specialized helper for solid RGB color persistence (kept separate for clarity)."""
        self._persist_dataset_prop(ds, "solid_color", tuple(rgb_tuple))

    def _on_point_size_changed(self, size: int) -> None:
        """
        Update the point size for the currently selected dataset.

        Args:
            size (int): The new point size to set.
        """
        ds = self._current_dataset_index()
        if ds is None:
            return
        self.viewer3d.set_point_size(int(size), ds)
        if self.mct:
            self.mct["point_size"] = int(size)
        # Persist also into the viewer cache so actor rebuilds keep the new size
        self._persist_dataset_prop(ds, "point_size", int(size))
        def _post_psize():
            try:
                self._apply_cached_visuals(ds)
            except Exception:
                pass
        self._defer(0, _post_psize)

    def _on_point_budget_changed(self, percent: int) -> None:
        """
        Update the visible points percentage (point budget) for the selected dataset.

        Args:
            percent (int): The percentage of points to display.
        """
        ds = self._current_dataset_index()
        if ds is None:
            return
        self.viewer3d.set_point_budget(int(percent), ds)
        if self.mct:
            self.mct["point_budget"] = int(percent)
        self._persist_dataset_prop(ds, "point_budget", int(percent))
        try:
            self._viewer_ensure_actor("points", ds)
        except Exception:
            pass
        def _post_budget():
            try:
                self._apply_cached_visuals(ds)
            except Exception:
                pass
        self._defer(0, _post_budget)
        try:
            self.viewer3d.refresh()
        except Exception:
            pass

    def _on_color_mode_changed(self, mode: str) -> None:
        """
        Change the color mode of the selected dataset.

        Args:
            mode (str): The color mode to set (e.g., 'Normal RGB', 'Normal Colormap').
        """
        ds = self._current_dataset_index()
        if ds is None:
            return
        self.viewer3d.set_color_mode(mode, ds)
        if self.mct:
            self.mct["color_mode"] = mode
        self._persist_dataset_prop(ds, "color_mode", str(mode))
        try:
            self.viewer3d.refresh()
        except Exception:
            pass

    def _on_solid_color_changed(self, col: QtGui.QColor) -> None:
        """
        Set the solid color for the selected dataset.

        Args:
            col (QtGui.QColor): The color to set.
        """
        ds = self._current_dataset_index()
        if ds is None or not col.isValid():
            return
        self.viewer3d.set_dataset_color(ds, col.red(), col.green(), col.blue())
        if self.mct:
            self.mct["solid_color"] = (col.red(), col.green(), col.blue())
        self._persist_dataset_color(ds, (col.red(), col.green(), col.blue()))
        try:
            self.viewer3d.refresh()
        except Exception:
            pass

    def _on_colormap_changed(self, name: str) -> None:
        """
        Update the colormap for the selected dataset.

        Args:
            name (str): The name of the colormap to apply.
        """
        ds = self._current_dataset_index()
        if ds is None:
            return
        self.viewer3d.set_colormap(name, ds)
        if self.mct:
            self.mct["colormap"] = name
        self._persist_dataset_prop(ds, "colormap", str(name))
        try:
            self.viewer3d.refresh()
        except Exception:
            pass

    def _on_mesh_rep_changed(self, mode: str) -> None:
        """
        Change the mesh representation mode for the selected mesh dataset.

        Args:
            mode (str): The mesh representation mode (e.g., 'Surface', 'Wireframe').
        """
        ds = self._current_dataset_index()
        if ds is None:
            return
        self.viewer3d.set_mesh_representation(ds, mode)
        if self.mct:
            self.mct["representation"] = mode
        self._persist_dataset_prop(ds, "representation", str(mode))
        # TEMP: rebuild scene once to avoid desync/orphan actors
        self._schedule_scene_rebuild()

    def _on_mesh_opacity_changed(self, val: int) -> None:
        """
        Update the opacity for the selected mesh dataset.

        Args:
            val (int): The opacity value (0-100).
        """
        ds = self._current_dataset_index()
        if ds is None:
            return
        self.viewer3d.set_mesh_opacity(ds, int(val))
        if self.mct:
            self.mct["opacity"] = int(val)
        self._persist_dataset_prop(ds, "opacity", int(val))
        # TEMP: rebuild scene once to avoid desync/orphan actors
        self._schedule_scene_rebuild()

    def _on_toggle_normals_clicked(self, on: bool) -> None:
        """Toggle Normals dal pulsante della toolbar sul dataset selezionato."""
        ds = self._current_dataset_index()
        if ds is None:
            # niente dataset selezionato
            return

        # Se non esiste il nodo "Normals" nel tree, crealo (non lo spunta ancora).
        normals_item = None
        try:
            normals_item = self._ensure_normals_tree_child(ds)
        except Exception:
            normals_item = None
        if normals_item is not None:
            try:
                normals_item.setData(0, QtCore.Qt.ItemDataRole.UserRole, {"kind": "normals", "ds": int(ds)})
            except Exception:
                pass

        # Attiva/disattiva visibilità lato viewer
        try:
            getattr(self.viewer3d, "set_normals_visibility", lambda *_: None)(ds, bool(on))
        except Exception:
            return

        # Persist normals visibility in the dataset record
        try:
            self._persist_dataset_prop(ds, "normals_visible", bool(on))
        except Exception:
            pass

        def _post_normals_toggle():
            try:
                self._apply_cached_visuals(ds)
            except Exception:
                pass
            try:
                self.viewer3d.refresh()
            except Exception:
                pass
        self._defer(1, _post_normals_toggle)
        try:
            self._reapply_overlays_safe()
        except Exception:
            pass

        # Sincronizza lo stato del nodo "Normals" nell'albero (se presente)
        try:
            item = self.treeMCTS.currentItem()
            if item is not None:
                # sali al root (file)
                root = item
                while root.parent() is not None:
                    root = root.parent()
                # trova il figlio "Point cloud" e poi "Normals"
                target = None
                for i in range(root.childCount()):
                    if root.child(i).text(0) == "Point cloud":
                        target = root.child(i)
                        break
                if target is not None:
                    for i in range(target.childCount()):
                        ch = target.child(i)
                        data = ch.data(0, QtCore.Qt.ItemDataRole.UserRole)
                        if ch.text(0) == "Normals" and isinstance(data, dict) and data.get("ds") == ds:
                            ch.setCheckState(0, QtCore.Qt.CheckState.Checked if on else QtCore.Qt.CheckState.Unchecked)
                            break
        except Exception:
            pass
        # TEMP: rebuild scene once to avoid desync/orphan actors
        # self._schedule_scene_rebuild()

    def _build_statusbar(self) -> None:
        sb = QtWidgets.QStatusBar(self)
        self.setStatusBar(sb)

        # --- Widgets -----------------------------------------------------
        self.btnCancel = QtWidgets.QPushButton("CANCEL")
        self.btnCancel.setObjectName("buttonCANCEL")
        self.btnCancel.setEnabled(False)
        self.btnCancel.setSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred)

        self.progress = QtWidgets.QProgressBar()
        self.progress.setObjectName("barPROGRESS")
        self.progress.setRange(0, 100)
        self.progress.setValue(0)
        self.progress.setFormat("Idle")
        self.progress.setTextVisible(True)
        self.progress.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)

        self.disk = QtWidgets.QProgressBar()
        self.disk.setObjectName("diskUsageBar")
        self.disk.setRange(0, 100)
        self.disk.setValue(0)
        self.disk.setTextVisible(True)
        self.disk.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)

        # Container to control layout & stretches (so showMessage won't hide widgets)
        panel = QtWidgets.QWidget()
        lay = QtWidgets.QHBoxLayout(panel)
        lay.setContentsMargins(0, 0, 0, 0)
        lay.setSpacing(6)
        lay.addWidget(self.btnCancel)
        lay.addWidget(self.progress, 3)  # ~60%
        lay.addWidget(self.disk, 2)      # ~40%

        # Add as permanent widget so temporary status messages don't hide it
        sb.addPermanentWidget(panel, 1)

    def _start_disk_timer(self) -> None:
        self._disk_timer = QtCore.QTimer(self)
        self._disk_timer.timeout.connect(self._update_disk)
        self._disk_timer.start(2000)
        self._update_disk()

    def _update_disk(self) -> None:
        used, free, percent = disk_usage_percent()
        self.disk.setValue(int(percent))
        self.disk.setFormat(f"Disk used: {percent:.0f}%")

    # ------------------------------------------------------------------
    # Progress bar helpers + background-worker slots
    # ------------------------------------------------------------------
    # --- Progress helpers (import cloud) ---------------------------------
    def _import_progress_begin(self, title: str = "Importing cloud…") -> None:
        """Begin an import progress section (safe to call multiple times)."""
        try:
            # Reuse the generic progress bar helpers already wired to the status bar
            self._progress_start(title)
        except Exception:
            pass

    def _import_progress_update(self, percent: int | None = None, message: str | None = None) -> None:
        """Update progress bar during import."""
        try:
            if percent is not None:
                v = int(max(0, min(100, percent)))
                try:
                    self.progress.setValue(v)
                except Exception:
                    pass
            if message:
                # Show a short status text while keeping the bar visible
                try:
                    self.progress.setFormat(str(message))
                except Exception:
                    pass
                try:
                    self.statusBar().showMessage(message, 2000)
                except Exception:
                    pass
        except Exception:
            pass

    def _import_progress_end(self) -> None:
        """End the import progress section."""
        try:
            self._progress_finish()
        except Exception:
            pass
    # ---------------------------------------------------------------------
    def _progress_start(self, text: str = "Working…") -> None:
        """Initialize the statusbar progress bar."""
        try:
            self.progress.setRange(0, 100)
            self.progress.setValue(0)
            self.progress.setFormat(text)
            self.progress.setTextVisible(True)
        except Exception:
            pass

    def _progress_set(self, value: int | float, text: str | None = None) -> None:
        """Update progress value (0..100) and optional text."""
        try:
            v = int(max(0, min(100, round(float(value)))))
            self.progress.setValue(v)
            if text is not None:
                self.progress.setFormat(str(text))
        except Exception:
            pass

    def _progress_finish(self, text: str = "Ready") -> None:
        """Finish the progress and reset UI bits."""
        try:
            self.progress.setValue(100)
            self.progress.setFormat(text)
        except Exception:
            pass
        # Disable cancel if it was enabled
        try:
            self.btnCancel.setEnabled(False)
        except Exception:
            pass
        # Clear active job context
        try:
            self._active_job = None
        except Exception:
            pass

    def _ensure_cancel_button(self) -> None:
        """Best-effort: ensure the Cancel button is visible/enabled for jobs."""
        try:
            self.btnCancel.setEnabled(True)
        except Exception:
            pass

    @QtCore.Slot()
    def _on_cancel_job(self) -> None:
        """User pressed CANCEL: ask the active worker to stop."""
        job = getattr(self, "_active_job", None)
        worker = None
        if isinstance(job, dict):
            worker = job.get("worker")
        try:
            if worker is not None and hasattr(worker, "request_cancel"):
                worker.request_cancel()
            self.statusBar().showMessage("Cancelling…", 2000)
        except Exception:
            pass

    # --- Slots used by _NormalsWorker (progress/message/finished) -----------
    @QtCore.Slot(int)
    def _slot_worker_progress(self, p: int) -> None:
        """Update the progress bar percentage."""
        self._progress_set(p)

    @QtCore.Slot(str)
    def _slot_worker_message(self, msg: str) -> None:
        """Reflect worker text into the progress format."""
        self._progress_set(self.progress.value(), msg)

    @QtCore.Slot(object)
    def _slot_worker_finished(self, normals_obj) -> None:
        """
        Worker finished. If `normals_obj` is an Nx3 array, attach/store it to the
        current dataset and (optionally) show normals based on the toolbar toggle.
        Always tear down the worker thread and finalize the progress bar.
        """
        # Tear down the worker thread (best-effort)
        try:
            ctx = getattr(self, "_normals_ctx", {}) or {}
            thread = ctx.get("thread")
            if thread is not None:
                try:
                    thread.quit()
                    thread.wait()
                except Exception:
                    pass
        except Exception:
            pass

        # If we got normals, persist them into the viewer's dataset
        try:
            import numpy as _np  # local import to keep module import-time light
            ds = int(self._normals_ctx.get("ds")) if hasattr(self, "_normals_ctx") else None
            if normals_obj is not None and ds is not None:
                arr = _np.asarray(normals_obj)
                if arr.ndim == 2 and arr.shape[1] == 3:
                    # Try a dedicated API first
                    set_api = getattr(self.viewer3d, "set_normals_array", None)
                    if callable(set_api):
                        try:
                            set_api(ds, arr)
                        except Exception:
                            pass
                    # Also update the cached record and point_data if accessible
                    try:
                        recs = getattr(self.viewer3d, "_datasets", [])
                        if 0 <= ds < len(recs):
                            rec = recs[ds]
                            rec["normals_array"] = arr
                            pdata = rec.get("pdata") or rec.get("full_pdata")
                            if pdata is not None and hasattr(pdata, "point_data"):
                                pdata.point_data["Normals"] = arr
                    except Exception:
                        pass

                    # Apply initial display percentage from context, default 1%
                    try:
                        percent = int(getattr(self, "_normals_ctx", {}).get("percent", 1))
                    except Exception:
                        percent = 1
                    # Persist into the dataset record so builder uses it
                    try:
                        recs = getattr(self.viewer3d, "_datasets", [])
                        if 0 <= ds < len(recs):
                            rec = recs[ds]
                            rec["normals_percent"] = percent
                    except Exception:
                        pass
                    # If the viewer exposes a setter for percent, use it; otherwise trigger a rebuild
                    try:
                        setp = getattr(self.viewer3d, "set_normals_percent", None)
                        if callable(setp):
                            # Some implementations accept (ds, percent, rebuild=True)
                            try:
                                setp(ds, percent, True)
                            except TypeError:
                                setp(ds, percent)
                        else:
                            # Best-effort: rebuild normals actor so the new percent is honored
                            rebuild = getattr(self.viewer3d, "_rebuild_normals_actor", None)
                            if callable(rebuild):
                                rebuild(ds)
                    except Exception:
                        pass

                    # --- Ensure normals are actually shown once computed: force-build actor and toggle ON ---
                    try:
                        # Persist visibility flag in cache
                        recs = getattr(self.viewer3d, "_datasets", [])
                        if 0 <= ds < len(recs):
                            recs[ds]["normals_visible"] = True
                    except Exception:
                        pass
                    try:
                        # Build or rebuild the normals actor explicitly if the viewer exposes it
                        rebuild_normals = getattr(self.viewer3d, "_rebuild_normals_actor", None)
                        if callable(rebuild_normals):
                            rebuild_normals(ds)
                    except Exception:
                        pass
                    try:
                        # Turn on the toolbar toggle (UI) without emitting recursive signals
                        self.act_toggle_normals.blockSignals(True)
                        self.act_toggle_normals.setChecked(True)
                        self.act_toggle_normals.blockSignals(False)
                    except Exception:
                        pass
                    try:
                        # Finally, ensure visibility ON at the viewer level
                        getattr(self.viewer3d, "set_normals_visibility", lambda *_: None)(ds, True)
                    except Exception:
                        pass

                    # Visibility handled above: we explicitly turned normals ON after compute.
                    # (Old code removed here.)
        except Exception:
            pass

        # Finalize UI
        self._progress_finish("Normals done")

    def _on_compute_normals(self) -> None:
        """Compute point‑cloud normals in a background thread (non‑blocking UI).

        Priority: PCA on k-NN neighborhoods with optional FAST mode (subset + propagate).
        On success, stores normals into the current dataset entry and updates the UI.
        """
        import numpy as np

        self._progress_start("Starting normals computation…")
        self._ensure_cancel_button()

        # Grab current dataset points from viewer cache if available via self.mct
        entry = getattr(self, "mct", None)
        if not entry or entry.get("ds_index") is None:
            self._append_message("[Normals] No active dataset selected.")
            self._progress_finish("Normals not computed: no dataset")
            return
        ds = int(entry["ds_index"]) if entry.get("ds_index") is not None else None

        # Try to fetch points back from viewer; fall back to stored structures if available
        P = None
        try:
            datasets = getattr(self.viewer3d, "_datasets", [])
            if isinstance(ds, int) and 0 <= ds < len(datasets):
                fp = datasets[ds].get("full_pdata") or datasets[ds].get("pdata")
                # Expect PyVista PolyData or numpy array alike
                if hasattr(fp, "points"):
                    P = np.asarray(fp.points, dtype=float)
                elif hasattr(fp, "to_numpy"):
                    P = np.asarray(fp.to_numpy(), dtype=float)
                else:
                    P = np.asarray(fp, dtype=float)
        except Exception:
            P = None

        if P is None or P.ndim != 2 or P.shape[1] != 3 or P.shape[0] == 0:
            self._append_message("[Normals] Cannot access points for current dataset.")
            self._progress_finish("Normals not computed: invalid points")
            return

        # Read fast flag
        # Fast-mode flag: prefer DisplayPanel state if present, otherwise fallback
        fast_flag = False
        try:
            if hasattr(self, "displayPanel") and self.displayPanel is not None:
                fast_flag = bool(self.displayPanel.fast_normals_enabled())
            else:
                fast_flag = bool(getattr(self, "normals_fast_enabled", False))
        except Exception:
            pass

        # Parameters (you can expose k via settings later)
        k_nn = int(getattr(self, "normals_k", 16))
        max_fast = int(getattr(self, "normals_fast_max_points", 250_000))

        # Initial display percentage for normals (default 1%)
        try:
            percent_ui = int(self.displayPanel.spinNormalsPercent.value())
        except Exception:
            percent_ui = 1

        # Harden against macOS/Accelerate and OpenMP threading issues inside background threads
        try:
            import os as _os
            _os.environ.setdefault("OMP_NUM_THREADS", "1")
            _os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
            _os.environ.setdefault("MKL_NUM_THREADS", "1")
            _os.environ.setdefault("VECLIB_MAXIMUM_THREADS", "1")
            _os.environ.setdefault("NUMEXPR_NUM_THREADS", "1")
        except Exception:
            pass

        # Prepare worker
        worker = _NormalsWorker(points=P, k=k_nn, subset_size=80_000,
                                fast=fast_flag, fast_max_points=max_fast)
        thread = QtCore.QThread(self)
        worker.moveToThread(thread)

        # salva contesto per lo slot di fine
        self._normals_ctx = {"P": P, "ds": ds, "entry": entry, "thread": thread, "percent": percent_ui}

        # connessioni ai nuovi slot (GUI thread garantito)
        worker.progress.connect(self._slot_worker_progress, QtCore.Qt.ConnectionType.QueuedConnection)
        worker.message.connect(self._slot_worker_message, QtCore.Qt.ConnectionType.QueuedConnection)
        worker.finished.connect(self._slot_worker_finished, QtCore.Qt.ConnectionType.QueuedConnection)

        thread.started.connect(worker.run)
        thread.start()

        # Expose active job for cancellation
        self._active_job = {"worker": worker, "thread": thread}
        self.btnCancel.clicked.connect(self._on_cancel_job, QtCore.Qt.ConnectionType.UniqueConnection)
        self.btnCancel.setEnabled(True)

    # ------------------------------------------------------------------
    # Session I/O: New / Open / Save / Save As
    # ------------------------------------------------------------------
    def _on_new_session(self) -> None:
        """Start a new empty session, clearing tree, viewer and state."""
        try:
            if self.mcts:
                ret = QtWidgets.QMessageBox.question(
                    self, "New Session",
                    "Discard current session and start a new one?",
                    QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
                    QtWidgets.QMessageBox.No,
                )
                if ret != QtWidgets.QMessageBox.Yes:
                    return
        except Exception:
            pass
        # Clear UI state
        try:
            self.treeMCTS.clear()
        except Exception:
            pass
        try:
            if hasattr(self.viewer3d, "clear"):
                self.viewer3d.clear()
        except Exception:
            pass
        self.mcts = {}
        self.mct = {}
        self._session_path = None
        try:
            self.statusBar().showMessage("New session", 3000)
        except Exception:
            pass

    def _on_open_session(self) -> None:
        """Open a saved C2F4DT session (.c2f4dt.json)."""
        dlg = QtWidgets.QFileDialog(self, "Open session")
        dlg.setFileMode(QtWidgets.QFileDialog.ExistingFile)
        dlg.setNameFilters(["C2F4DT Session (*.c2f4dt.json)", "JSON (*.json)", "All files (*)"])
        if not dlg.exec():
            return
        paths = dlg.selectedFiles()
        if not paths:
            return
        self._load_session_from_file(paths[0])

    def _on_save_session(self) -> None:
        """Save the current session to disk; if untitled, fallback to Save As."""
        if not self._session_path:
            self._on_save_session_as()
            return
        data = self._session_snapshot()
        try:
            with open(self._session_path, "w", encoding="utf-8") as f:
                json.dump(data, f, indent=2)
            try:
                self.statusBar().showMessage(f"Saved session to {os.path.basename(self._session_path)}", 3000)
            except Exception:
                pass
        except Exception as ex:
            QtWidgets.QMessageBox.critical(self, "Save error", str(ex))

    def _on_save_session_as(self) -> None:
        """Prompt for a path and save the session JSON there."""
        dlg = QtWidgets.QFileDialog(self, "Save session as")
        dlg.setAcceptMode(QtWidgets.QFileDialog.AcceptSave)
        dlg.setNameFilters(["C2F4DT Session (*.c2f4dt.json)", "JSON (*.json)", "All files (*)"])
        dlg.setDefaultSuffix("c2f4dt.json")
        if not dlg.exec():
            return
        paths = dlg.selectedFiles()
        if not paths:
            return
        self._session_path = paths[0]
        # ensure extension
        if not (self._session_path.endswith(".c2f4dt.json") or self._session_path.endswith(".json")):
            self._session_path += ".c2f4dt.json"
        self._on_save_session()

    def _session_snapshot(self) -> dict:
        """Capture a lightweight, JSON‑serializable snapshot of the current session."""
        snap: dict = {"version": 1, "datasets": [], "viewer": {}, "options": {}}
        # Viewer globals
        try:
            v = self.viewer3d
            snap["viewer"] = {
                "color_mode": getattr(v, "_color_mode", None),
                "colormap": getattr(v, "_cmap", None),
                "point_size": getattr(v, "_point_size", None),
                "view_budget_percent": getattr(v, "_view_budget_percent", None),
                "points_as_spheres": getattr(v, "_points_as_spheres", None),
            }
        except Exception:
            pass
        # App options
        try:
            snap["options"]["downsample_method"] = getattr(self, "downsample_method", None)
            snap["options"]["normals_fast_enabled"] = bool(getattr(self, "normals_fast_enabled", False))
            snap["options"]["normals_k"] = int(getattr(self, "normals_k", 16))
            snap["options"]["normals_fast_max_points"] = int(getattr(self, "normals_fast_max_points", 250_000))
        except Exception:
            pass
        # Datasets (from mcts registry)
        try:
            for name, entry in self.mcts.items():
                ds = {
                    "name": name,
                    "kind": entry.get("kind"),
                    "ds_index": entry.get("ds_index"),
                    "point_size": entry.get("point_size"),
                    "point_budget": entry.get("point_budget"),
                    "color_mode": entry.get("color_mode"),
                    "colormap": entry.get("colormap"),
                    "solid_color": entry.get("solid_color"),
                    "points_as_spheres": entry.get("points_as_spheres"),
                    # Optional: if your importers store the original path
                    "source_path": entry.get("source_path"),
                }
                snap["datasets"].append(ds)
        except Exception:
            pass
        return snap

    def _load_session_from_file(self, path: str) -> None:
        """Load a session JSON and rebuild the scene as much as possible.

        If a dataset has `source_path`, it will be re-imported automatically.
        """
        try:
            with open(path, "r", encoding="utf-8") as f:
                data = json.load(f)
        except Exception as ex:
            QtWidgets.QMessageBox.critical(self, "Open error", f"Cannot read session: {ex}")
            return
        # Reset current state
        self._on_new_session()
        self._session_path = path
        # Restore viewer/app options (best effort)
        try:
            opts = data.get("options", {})
            self.downsample_method = opts.get("downsample_method", self.downsample_method)
            self.normals_fast_enabled = bool(opts.get("normals_fast_enabled", getattr(self, "normals_fast_enabled", False)))
            self.normals_k = int(opts.get("normals_k", getattr(self, "normals_k", 16)))
            self.normals_fast_max_points = int(opts.get("normals_fast_max_points", getattr(self, "normals_fast_max_points", 250_000)))
        except Exception:
            pass
        # Re-import datasets by source_path if available
        restored = 0
        for ds in data.get("datasets", []):
            src = ds.get("source_path")
            if src and os.path.exists(src):
                try:
                    # Use programmatic import if available
                    if hasattr(self, "import_cloud_programmatic"):
                        self.import_cloud_programmatic(src)
                        restored += 1
                except Exception:
                    continue
        try:
            self.statusBar().showMessage(f"Opened session: restored {restored} dataset(s)", 5000)
        except Exception:
            pass

    def _populate_plugins_ui(self) -> None:
        """Riempi la combo e ricostruisci il menù Plugins con le azioni esposte dai plugin."""
        items = self.plugin_manager.ui_combo_items()
        self.comboPlugins.clear()
        if not items:
            self.comboPlugins.addItem("— No plugins installed —")
            self.comboPlugins.setEnabled(False)
        else:
            self.comboPlugins.setEnabled(True)

            color_map = {
                "red": QtGui.QColor("#e53935"),
                "green": QtGui.QColor("#43a047"),
                "gray": QtGui.QColor("#9e9e9e"),
                "black": QtGui.QColor("#000000"),
            }

            for it in items:
                self.comboPlugins.addItem(it["label"], userData=it.get("key"))
                idx = self.comboPlugins.count() - 1
                # tooltip e colore
                self.comboPlugins.setItemData(idx, it.get("tooltip", ""), QtCore.Qt.ItemDataRole.ToolTipRole)
                qcol = color_map.get(it.get("color", "black"), color_map["black"])
                self.comboPlugins.setItemData(idx, qcol, QtCore.Qt.ItemDataRole.TextColorRole)
                # disabilita se non disponibile
                if not it.get("enabled", True):
                    mdl = self.comboPlugins.model()
                    mitem = mdl.item(idx)
                    if mitem is not None:
                        mitem.setEnabled(False)

        # Ricostruisci il menù Plugins
        try:
            self._rebuild_plugins_menu(items)
        except Exception:
            pass

    # --------------------- Plugins wiring ---------------------------------

    def _plugin_context(self) -> dict:
        """Contesto standard passato ai plugin."""
        return {
            "window": self,
            "viewer3d": getattr(self, "viewer3d", None),
            "mcts": getattr(self, "mcts", {}),
            "mct": getattr(self, "mct", {}),
            "current_dataset": self._current_dataset_index(),
            "display": getattr(self, "displayPanel", None),
            "console": getattr(self, "console", None),
            # aggiungi qui oggetti utili che i tuoi plugin si aspettano
        }

    @QtCore.Slot(int)
    def _on_plugin_combo_activated(self, index: int) -> None:
        try:
            key = self.comboPlugins.itemData(index)  # lo impostiamo in _populate_plugins_ui
            if not key:
                return
            self._run_plugin_by_key(str(key))
        except Exception as ex:
            QtWidgets.QMessageBox.warning(self, "Plugin", f"Cannot run plugin: {ex}")

    def _run_plugin_by_key(self, key: str) -> None:
        """Trova il plugin per 'key' e prova ad eseguirlo in modo robusto (senza introspezione fragile)."""
        try:
            # 1) recupera l'oggetto plugin (lazy get)
            plugin = None
            for attr in ("get", "plugin_by_key"):
                fn_get = getattr(self.plugin_manager, attr, None)
                if callable(fn_get):
                    plugin = fn_get(key)
                    break

            # fallback: guarda nella lista items se già istanziato
            if plugin is None:
                try:
                    for it in self.plugin_manager.ui_combo_items():
                        if it.get("key") == key and it.get("plugin_obj") is not None:
                            plugin = it["plugin_obj"]
                            break
                except Exception:
                    pass

            if plugin is None:
                QtWidgets.QMessageBox.warning(self, "Plugin", f"Plugin '{key}' not found.")
                return

            ctx = self._plugin_context()

            # helper per chiamare callables in modo sicuro
            def _call_safe(fn):
                try:
                    fn(ctx)
                    return True
                except TypeError:
                    try:
                        fn()
                        return True
                    except Exception:
                        return False
                except Exception:
                    return False

            # 2) se il plugin espone azioni strutturate, usale
            actions = None
            for attr in ("actions", "get_actions"):
                getter = getattr(plugin, attr, None)
                if callable(getter):
                    try:
                        actions = getter()
                    except Exception:
                        actions = None
                    break

            if isinstance(actions, (list, tuple)) and actions:
                if len(actions) == 1:
                    self._invoke_plugin_action(plugin, actions[0], ctx)
                    return
                menu = QtWidgets.QMenu(self)
                for desc in actions:
                    act = QtGui.QAction(str(desc.get("label", "Action")), self)
                    act.triggered.connect(lambda _=False, d=desc: self._invoke_plugin_action(plugin, d, ctx))
                    menu.addAction(act)
                pt = self.comboPlugins.mapToGlobal(QtCore.QPoint(0, self.comboPlugins.height()))
                menu.exec(pt)
                return

            # 3) entry-point comuni del plugin (metodi d'istanza)
            for attr in ("run", "apply", "open", "open_dialog", "show", "__call__"):
                fn = getattr(plugin, attr, None)
                if callable(fn) and _call_safe(fn):
                    return

            # 4) modulo con funzioni globali
            import types
            if isinstance(plugin, types.ModuleType):
                for attr in ("run", "main"):
                    fn = getattr(plugin, attr, None)
                    if callable(fn) and _call_safe(fn):
                        return

            QtWidgets.QMessageBox.information(self, "Plugin", f"Plugin '{key}' does not expose any known actions.")
        except Exception as ex:
            QtWidgets.QMessageBox.critical(self, "Plugin error", str(ex))

    def _invoke_plugin_action(self, plugin, action_desc, ctx: dict) -> None:
        """Executes a single plugin action described as a dictionary:
           {'label': 'Do X', 'slot': callable} or {'label': ..., 'method': 'run'}.
        """
        try:
            slot = action_desc.get("slot")
            if callable(slot):
                # tenta (ctx) se il callable accetta argomenti
                try:
                    slot(ctx)
                except TypeError:
                    slot()
                return
            method_name = action_desc.get("method") or action_desc.get("name")
            if method_name and hasattr(plugin, method_name):
                fn = getattr(plugin, method_name)
                try:
                    fn(ctx)
                except TypeError:
                    fn()
                return
            # fallback: se c'è 'command' stringa e il plugin ha un dispatcher
            cmd = action_desc.get("command")
            if cmd and hasattr(plugin, "dispatch"):
                plugin.dispatch(cmd, ctx)
                return
            raise RuntimeError("Unsupported action descriptor")
        except Exception as ex:
            QtWidgets.QMessageBox.critical(self, "Plugin action error", str(ex))

    def _rebuild_plugins_menu(self, items: list[dict]) -> None:
        """Rigenera il menù &Plugins con le azioni dei plugin."""
        if not hasattr(self, "m_plugins") or self.m_plugins is None:
            return
        self.m_plugins.clear()
        if not items:
            act = QtGui.QAction("No plugins installed", self)
            act.setEnabled(False)
            self.m_plugins.addAction(act)
            return

        for it in items:
            key = it.get("key")
            label = it.get("label", key or "Plugin")
            tooltip = it.get("tooltip", "")
            enabled = bool(it.get("enabled", True))

            submenu = QtWidgets.QMenu(label, self.m_plugins)
            submenu.setEnabled(enabled)
            if tooltip:
                submenu.setToolTipsVisible(True)
                submenu.setToolTip(tooltip)

            # prova a ottenere il plugin e le sue azioni
            plugin = None
            get_fn = getattr(self.plugin_manager, "get", None)
            if callable(get_fn):
                try:
                    plugin = get_fn(key)
                except Exception:
                    plugin = None
            actions = None
            if plugin is not None:
                for attr in ("actions", "get_actions"):
                    getter = getattr(plugin, attr, None)
                    if callable(getter):
                        try:
                            actions = getter()
                        except Exception:
                            actions = None
                        break

            if isinstance(actions, (list, tuple)) and actions:
                # crea QAction per ciascuna azione
                for a in actions:
                    q = QtGui.QAction(str(a.get("label", "Action")), self)
                    q.setToolTip(str(a.get("tooltip", "")))
                    q.triggered.connect(lambda _=False, plug=plugin, desc=a: self._invoke_plugin_action(plug, desc, self._plugin_context()))
                    submenu.addAction(q)
            else:
                # azione di default: Run <label>
                run_act = QtGui.QAction(f"Run {label}", self)
                run_act.setToolTip("Execute default entry-point")
                run_act.triggered.connect(lambda _=False, k=key: self._run_plugin_by_key(k))
                submenu.addAction(run_act)

            self.m_plugins.addMenu(submenu)


    def _on_undo_changed(self) -> None:
        self.act_undo.setEnabled(self.undo_stack.canUndo())
        self.act_redo.setEnabled(self.undo_stack.canRedo())

    def _console_context(self) -> dict:
        return {"mcts": self.mcts, "mct": self.mct, "window": self, "undo_stack": self.undo_stack}

    def _on_import_cloud(self) -> None:
        """Handle Import Cloud: open dialog, parse file, show summary, then add to scene & tree."""
        dlg = QtWidgets.QFileDialog(self, "Import point cloud / mesh")
        dlg.setFileMode(QtWidgets.QFileDialog.ExistingFile)
        dlg.setNameFilters([
            "All supported (*.ply *.obj *.vtp *.stl *.vtk *.gltf *.glb *.las *.laz *.e57)",
            "Point clouds (*.ply *.las *.laz *.e57)",
            "Meshes (*.ply *.obj *.vtp *.stl *.vtk *.gltf *.glb)",
            "All files (*)",
        ])
        if not dlg.exec():
            return
        paths = dlg.selectedFiles()
        if not paths:
            return
        path = paths[0]
        # --- Start progress bar immediately (UI feedback before heavy I/O) ---
        self._import_progress_begin("Opening file…")
        try:
            # Force the UI to repaint the progress bar before blocking I/O
            QtWidgets.QApplication.processEvents()
        except Exception:
            pass

        # Import
        from .utils.io.importers import import_file
        from .ui.import_summary_dialog import ImportSummaryDialog

        try:
            # Prefer importer with a progress callback (newer versions)
            try:
                objects = import_file(
                    path,
                    progress_cb=lambda p=None, msg=None: self._import_progress_update(
                        p if p is not None else self.progress.value(),
                        msg if msg is not None else "Reading…"
                    )
                )
            except TypeError:
                # Fallback: older importer without progress_cb
                objects = import_file(path)

            # Give a final nudge to the bar/format before showing the summary
            try:
                self._import_progress_update(100, "Parsing complete")
                QtWidgets.QApplication.processEvents()
            except Exception:
                pass

        except Exception as ex:
            # Make sure progress ends even on error
            self._import_progress_end()
            QtWidgets.QMessageBox.critical(self, "Import error", str(ex))
            return

        summary = ImportSummaryDialog(objects, self)
        if summary.exec() != QtWidgets.QDialog.Accepted:
            self._import_progress_end()
            return

        # Dopo aver letto le operazioni scelte dall’utente:
        ops = summary.operations()
        self._import_progress_update(45, "Applying options (axis / normals / budget)…")

        # --- helpers -----------------------------------------------------
        def _apply_axis_map(arr, axis_map):
            """Apply an axis remapping with sign to an (N,3) array.

            Args:
                arr: Points or normals array with shape (N, 3) or None.
                axis_map: Dict like {'X': '+Y', 'Y': '-Z', 'Z': '+X'}.
            Returns:
                New array with same shape, or the original if None/error.
            """
            try:
                import numpy as _np
                if arr is None:
                    return None
                src = _np.asarray(arr, dtype=float)
                if src.ndim != 2 or src.shape[1] != 3:
                    return arr
                out = _np.empty_like(src)
                axes = {"X": 0, "Y": 1, "Z": 2}
                for tgt_key, expr in axis_map.items():
                    sign = -1.0 if expr.startswith("-") else 1.0
                    src_axis = axes[expr[-1]]  # last char is X/Y/Z
                    out[:, axes[tgt_key]] = sign * src[:, src_axis]
                return out
            except Exception:
                return arr

        def _compute_normals_for_points(P, k=16, subset=80000, fast=True):
            """Compute PCA normals for an (N,3) numpy array `P` without touching the viewer.

            This avoids creating temporary datasets that would shift `_datasets` indices.
            """
            import numpy as _np
            from numpy.linalg import eigh as _eigh

            P = _np.asarray(P, dtype=float)
            if P.ndim != 2 or P.shape[1] != 3 or P.shape[0] == 0:
                return None
            n = P.shape[0]
            k = int(max(3, min(k, n)))

            # Try fast subset + nearest propagation when large and SciPy is available
            if fast and n > max(10000, subset):
                try:
                    from scipy.spatial import cKDTree as _KD  # type: ignore
                    rng = _np.random.default_rng(42)
                    idx_sub = rng.choice(n, size=subset, replace=False)
                    Psub = P[idx_sub]

                    tree_sub = _KD(Psub)
                    # compute normals on subset
                    Nsub = _np.empty_like(Psub)
                    # kNN within subset
                    _, knn_idx = tree_sub.query(Psub, k=min(k, Psub.shape[0]))
                    if knn_idx.ndim == 1:
                        knn_idx = knn_idx[:, None]
                    for i in range(Psub.shape[0]):
                        nbrs = Psub[knn_idx[i]]
                        C = _np.cov(nbrs.T)
                        w, v = _eigh(C)
                        nrm = v[:, 0]
                        if _np.dot(nrm, Psub[i] - nbrs.mean(axis=0)) < 0:
                            nrm = -nrm
                        Nsub[i] = nrm
                    # propagate to full set
                    tree_full = _KD(Psub)
                    _, j = tree_full.query(P, k=1)
                    return Nsub[j]
                except Exception:
                    # fall back to full computation
                    pass

            # Full PCA normals (no SciPy dependency)
            try:
                # Brute-force kNN; for large N you may replace with a KD-tree if available
                N = _np.empty_like(P)
                for i in range(n):
                    d2 = _np.sum((P - P[i]) ** 2, axis=1)
                    sel = _np.argpartition(d2, kth=k-1)[:k]
                    nbrs = P[sel]
                    C = _np.cov(nbrs.T)
                    w, v = _eigh(C)
                    nrm = v[:, 0]
                    if _np.dot(nrm, P[i] - nbrs.mean(axis=0)) < 0:
                        nrm = -nrm
                    N[i] = nrm
                return N
            except Exception:
                return None
        # -----------------------------------------------------------------

        # 1) Apply axis mapping / normals ops per object (before downsampling)
        for obj, spec in zip(objects, ops):
            # Points mapping
            obj.points = _apply_axis_map(obj.points, spec['axis_map'])
            # Normals mapping or compute if missing
            if spec.get('map_normals', True):
                if getattr(obj, 'normals', None) is not None:
                    obj.normals = _apply_axis_map(obj.normals, spec['axis_map'])
                elif spec.get('compute_normals_if_missing', False):
                    n = _compute_normals_for_points(obj.points, k=int(getattr(self, "normals_k", 16)))
                    if n is not None:
                        obj.normals = n
                    if n is not None:
                        obj.normals = n
            # Store color preference for later use
            obj.meta['color_preference'] = spec.get('color_preference', 'rgb')

        # SUGGESTED VIEW BUDGET (cap as hint): compute a percent based on total visible points
        try:
            import sys
            # Count current visible points in the viewer
            total_current = 0
            try:
                for _rec in getattr(self.viewer3d, "_datasets", []):
                    if not _rec.get("visible", True):
                        continue
                    fp = _rec.get("full_pdata", _rec.get("pdata"))
                    if hasattr(fp, "n_points"):
                        total_current += int(fp.n_points)
            except Exception:
                total_current = 0

            # Count incoming points (post axis-map but pre downsampling)
            total_incoming = 0
            try:
                for _o in objects:
                    if _o.kind == "points" and _o.points is not None:
                        total_incoming += int(_o.points.shape[0])
            except Exception:
                pass

            total_after = max(1, total_current + total_incoming)

            # Heuristic caps similar to viewer3d (_target_visible_points)
            points_as_spheres = bool(getattr(self.viewer3d, "_points_as_spheres", False))
            if sys.platform == "darwin":
                cap = 600_000 if points_as_spheres else 2_000_000
            else:
                cap = 2_200_000 if points_as_spheres else 8_000_000

            suggested = min(100, max(1, int(cap * 100 / total_after)))

            # Update UI slider and viewer with suggested percent (user can override later)
            try:
                if hasattr(self.displayPanel, "spinBudget") and self.displayPanel.spinBudget is not None:
                    self.displayPanel.spinBudget.blockSignals(True)
                    self.displayPanel.spinBudget.setValue(suggested)
                    self.displayPanel.spinBudget.blockSignals(False)
            except Exception:
                pass
            try:
                getattr(self.viewer3d, "set_point_budget", lambda *_: None)(suggested)
            except Exception:
                pass
        except Exception:
            pass

        # 2) Apply point budget on import (from Display panel)
        try:
            budget = int(getattr(self.displayPanel, "spinBudget", None).value())
        except Exception:
            budget = 100

        if budget < 100:
            from .utils.io.importers import downsample_random, downsample_voxel_auto
            for obj in objects:
                if obj.kind == "points" and obj.points is not None and obj.points.shape[0] > 0:
                    n0 = obj.points.shape[0]
                    if self.downsample_method == "voxel":
                        idx = downsample_voxel_auto(obj.points, budget)
                    else:
                        idx = downsample_random(obj.points, budget)
                    obj.points = obj.points[idx]
                    if obj.colors is not None and obj.colors.shape[0] == n0:
                        obj.colors = obj.colors[idx]
                    if obj.intensity is not None and obj.intensity.shape[0] == n0:
                        obj.intensity = obj.intensity[idx]
                    if getattr(obj, 'normals', None) is not None and obj.normals.shape[0] == n0:
                        obj.normals = obj.normals[idx]
                    obj.meta["downsample"] = {"method": self.downsample_method, "percent": budget, "kept": int(obj.points.shape[0])}

        self._import_progress_update(65, "Adding objects to the scene…")

        # 3) Add transformed objects to the viewer honoring color preference
        for obj in objects:
            # Temporarily adjust viewer color mode according to preference
            try:
                prev_mode = getattr(self.viewer3d, '_color_mode', None)
                pref = obj.meta.get('color_preference', 'rgb')
                if pref == 'colormap':
                    self.viewer3d.set_color_mode('Normal Colormap')
                else:
                    self.viewer3d.set_color_mode('Normal RGB')
            except Exception:
                prev_mode = None

            if obj.kind == "points" and obj.points is not None:
                ds_index = self.viewer3d.add_points(
                    obj.points, obj.colors, getattr(obj, "normals", None)
                )
            elif obj.kind == "mesh" and obj.pv_mesh is not None:
                ds_index = self.viewer3d.add_pyvista_mesh(obj.pv_mesh)

            try:
                self._reapply_overlays_safe()
            except Exception:
                pass

            # Tree: hierarchical, checkable, with metadata.
            self.treeMCTS.blockSignals(True)
            root = QtWidgets.QTreeWidgetItem([obj.name])
            root.setFlags(
                root.flags()
                | QtCore.Qt.ItemFlag.ItemIsUserCheckable
                | QtCore.Qt.ItemFlag.ItemIsAutoTristate
            )
            root.setCheckState(0, QtCore.Qt.CheckState.Checked)
            self.treeMCTS.addTopLevelItem(root)

            if obj.kind == "points":
                # Point cloud child
                it_points = QtWidgets.QTreeWidgetItem(["Point cloud"])
                it_points.setFlags(
                    it_points.flags()
                    | QtCore.Qt.ItemFlag.ItemIsUserCheckable
                    # | QtCore.Qt.ItemFlag.ItemIsAutoTristate
                )
                it_points.setCheckState(0, QtCore.Qt.CheckState.Checked)
                it_points.setData(0, QtCore.Qt.ItemDataRole.UserRole, {"kind": "points", "ds": ds_index})
                root.addChild(it_points)
                # Normals child (if available)
                if getattr(obj, "normals", None) is not None:
                    it_normals = QtWidgets.QTreeWidgetItem(["Normals"])
                    it_normals.setFlags(
                        it_normals.flags() | QtCore.Qt.ItemFlag.ItemIsUserCheckable
                    )
                    it_normals.setCheckState(0, QtCore.Qt.CheckState.Unchecked)
                    it_normals.setData(0, QtCore.Qt.ItemDataRole.UserRole, {"kind": "normals", "ds": ds_index})
                    it_points.addChild(it_normals)
            else:
                # Mesh node
                it_mesh = QtWidgets.QTreeWidgetItem(["Mesh"])
                it_mesh.setFlags(it_mesh.flags() | QtCore.Qt.ItemFlag.ItemIsUserCheckable)
                it_mesh.setCheckState(0, QtCore.Qt.CheckState.Checked)
                it_mesh.setData(0, QtCore.Qt.ItemDataRole.UserRole, {"kind": "mesh", "ds": ds_index})
                root.addChild(it_mesh)

            # Unblock signals after building the subtree
            self.treeMCTS.blockSignals(False)

            # Register into MCTS and set current MCT so it's visible in console
            try:
                entry = {
                    "name": obj.name,
                    "kind": obj.kind,
                    "has_rgb": obj.colors is not None,
                    "has_intensity": getattr(obj, 'intensity', None) is not None,
                    "has_normals": getattr(obj, 'normals', None) is not None,
                    "ds_index": ds_index,
                    "source_path": path,  # keep original file path for session reopen
                }
                if obj.kind == "points":
                    entry.update(
                        {
                            "point_size": getattr(self.viewer3d, "_point_size", 3),
                            "point_budget": getattr(
                                self.viewer3d, "_view_budget_percent", 100
                            ),
                            "color_mode": getattr(self.viewer3d, "_color_mode", "Normal RGB"),
                            "colormap": getattr(self.viewer3d, "_cmap", "viridis"),
                            "solid_color": self.viewer3d._datasets[ds_index].get(
                                "solid_color", (1.0, 1.0, 1.0)
                            ),
                            "points_as_spheres": getattr(
                                self.viewer3d, "_points_as_spheres", False
                            ),
                        }
                    )
                else:
                    entry.update(
                        {
                            "representation": "Surface",
                            "opacity": 100,
                            "solid_color": (1.0, 1.0, 1.0),
                        }
                    )
                self.mcts[obj.name] = entry
                self.mct = entry
                # Always select and check the "Point cloud" node if it exists
                selected = root
                for i in range(root.childCount()):
                    child = root.child(i)
                    data = child.data(0, QtCore.Qt.ItemDataRole.UserRole)
                    if isinstance(data, dict) and data.get("kind") == "points":
                        child.setCheckState(0, QtCore.Qt.CheckState.Checked)
                        selected = child
                        break
                try:
                    self.treeMCTS.setCurrentItem(selected)
                except Exception:
                    pass
            except Exception:
                pass

            self.statusBar().showMessage(f"Imported {len(objects)} object(s) from {path}", 5000)
            # 
            self._refresh_tree_visibility()
            try:
                self._reapply_overlays_safe()
            except Exception:
                pass
            self._import_progress_update(100, "Import finished")
            self._import_progress_end()
            try:
                if self.progress.value() < 100:
                    self._import_progress_end()
            except Exception:
                pass


    def _refresh_tree_visibility(self) -> None:
        """Sync visibility of all datasets from the tree using 'effective checked' (node and all ancestors)."""
        if self.treeMCTS.topLevelItemCount() == 0:
            return

        def recurse(node: QtWidgets.QTreeWidgetItem) -> None:
            data = node.data(0, QtCore.Qt.ItemDataRole.UserRole)
            eff_on = self._is_effectively_checked(node)
            if isinstance(data, dict) and data.get("ds") is not None:
                ds = int(data.get("ds"))
                kind = data.get("kind") or "points"
                # If this is the "Normals" child node, toggle normals only.
                if node.text(0) == "Normals" or data.get("normals_node", False):
                    try:
                        getattr(self.viewer3d, "set_normals_visibility", lambda *_: None)(ds, bool(eff_on))
                    except Exception:
                        pass
                else:
                    self._viewer_set_visibility(kind, ds, bool(eff_on))
                    # Safety: if points are off, ensure normals off too
                    if kind == "points" and not eff_on:
                        try:
                            getattr(self.viewer3d, "set_normals_visibility", lambda *_: None)(ds, False)
                        except Exception:
                            pass

            for i in range(node.childCount()):
                recurse(node.child(i))

        self._tree_updating = True
        try:
            for i in range(self.treeMCTS.topLevelItemCount()):
                recurse(self.treeMCTS.topLevelItem(i))
        finally:
            self._tree_updating = False


    def _on_tree_item_changed(self, item: QtWidgets.QTreeWidgetItem) -> None:
        """
        TEMP: do not propagate check state between parent/children.
        Simply schedule a single full-scene rebuild from current tree state.
        """
        # Evita rientranze/ricorsioni
        if getattr(self, "_tree_updating", False):
            return
        # Assicurati non sia tristate; non toccare parent/children
        try:
            self._tree_updating = True
            item.setFlags((item.flags() | QtCore.Qt.ItemFlag.ItemIsUserCheckable) & ~QtCore.Qt.ItemFlag.ItemIsTristate)
        except Exception:
            pass
        finally:
            self._tree_updating = False
        # Debounced full-scene rebuild
        self._schedule_scene_rebuild()

    def _update_parent_checkstate(self, child: QtWidgets.QTreeWidgetItem) -> None:
        """
        Update ancestors according to these rules:
        - If a parent has a 'points' child, the parent's state follows ONLY the state of 'points'.
        - Otherwise: Checked if all children are Checked; Unchecked if all are Unchecked; otherwise PartiallyChecked.
        - Does NOT modify children (no downward propagation here).
        """
        if child is None:
            return

        self._tree_updating = True
        try:
            parent = child.parent()
            while parent is not None:
                # 1) prova la regola "point-centric"
                points_child = None
                for i in range(parent.childCount()):
                    c = parent.child(i)
                    data = c.data(0, QtCore.Qt.ItemDataRole.UserRole)
                    if isinstance(data, dict) and data.get("kind") == "points":
                        points_child = c
                        break

                if points_child is not None:
                    # Il parent segue SOLO lo stato del figlio "points"
                    parent.setCheckState(0, points_child.checkState(0))
                else:
                    # 2) fallback: tri-stato classico basato su tutti i figli
                    total = parent.childCount()
                    if total == 0:
                        break
                    checked = 0
                    unchecked = 0
                    for i in range(total):
                        st = parent.child(i).checkState(0)
                        if st == QtCore.Qt.CheckState.Checked:
                            checked += 1
                        elif st == QtCore.Qt.CheckState.Unchecked:
                            unchecked += 1
                    if checked == total:
                        parent.setCheckState(0, QtCore.Qt.CheckState.Checked)
                    elif unchecked == total:
                        parent.setCheckState(0, QtCore.Qt.CheckState.Unchecked)
                    else:
                        parent.setCheckState(0, QtCore.Qt.CheckState.PartiallyChecked)

                parent = parent.parent()
        finally:
            self._tree_updating = False

    def _uncheck_descendants(self, item: QtWidgets.QTreeWidgetItem) -> None:
        """Spegni solo i discendenti (non accende nulla)."""
        for i in range(item.childCount()):
            child = item.child(i)
            if child.checkState(0) != QtCore.Qt.CheckState.Unchecked:
                child.setCheckState(0, QtCore.Qt.CheckState.Unchecked)
            self._uncheck_descendants(child)

    def _set_descendant_checkstate(
        self, item: QtWidgets.QTreeWidgetItem, state: QtCore.Qt.CheckState
        ) -> None:
        """Set the check state of all descendants."""
        for i in range(item.childCount()):
            child = item.child(i)
            child.setCheckState(0, state)
            self._set_descendant_checkstate(child, state)

    # def _is_effectively_checked(self, item: QtWidgets.QTreeWidgetItem) -> bool:
    #     """
    #     Visible if *this* item is Checked and no ancestor is Unchecked.

    #     - The current item must be Qt.Checked.
    #     - Ancestors with Qt.PartiallyChecked do NOT block their children.
    #     - An ancestor with Qt.Unchecked disables all its descendants.
    #     """
    #     if item is None or item.checkState(0) != QtCore.Qt.CheckState.Checked:
    #         return False
    #     parent = item.parent()
    #     while parent is not None:
    #         if parent.checkState(0) == QtCore.Qt.CheckState.Unchecked:
    #             return False
    #         parent = parent.parent()
    #     return True
    def _is_effectively_checked(self, item: QtWidgets.QTreeWidgetItem) -> bool:
        """
        Return True if `item` and **all** its ancestors are checked.
        This ensures children cannot remain logically 'on' if a parent is 'off'.
        """
        cur = item
        while cur is not None:
            try:
                if cur.checkState(0) != QtCore.Qt.CheckState.Checked:
                    return False
            except Exception:
                return False
            cur = cur.parent()
        return True

    def _on_tree_context_menu(self, pos: QtCore.QPoint) -> None:
        item = self.treeMCTS.itemAt(pos)
        if item is None:
            return
        data = item.data(0, QtCore.Qt.ItemDataRole.UserRole)
        if not isinstance(data, dict):
            return
        # Consentire la modifica del colore solo per i nodi della nuvola di punti.
        # Only allow color edit for point cloud nodes.
        if data.get("kind") != "points":
            return
        ds = data.get("ds")
        if ds is None:
            return
        menu = QtWidgets.QMenu(self)
        act_color = menu.addAction("Set Color…")
        act_random = menu.addAction("Random Color")
        chosen = menu.exec(self.treeMCTS.viewport().mapToGlobal(pos))
        if chosen is None:
            return
        if chosen is act_color:
            col = QtWidgets.QColorDialog.getColor(parent=self, title="Choose color for point cloud")
            if col.isValid():
                getattr(self.viewer3d, "set_dataset_color", lambda *_: None)(ds, col.red(), col.green(), col.blue())
        elif chosen is act_random:
            import random
            r, g, b = [random.randint(32, 224) for _ in range(3)]
            getattr(self.viewer3d, "set_dataset_color", lambda *_: None)(ds, r, g, b)

    # ------------------------------------------------------------------
    # Test / Esecutore di script
    # Testing / Script runner
    # ------------------------------------------------------------------
    def _on_run_script(self) -> None:
        """Open a .py file and execute it inside the console context.

        The script has access to: mcts, mct, window, undo_stack and a helper
        function `import_cloud(path, **kwargs)` (see `import_cloud_programmatic`).
        """
        dlg = QtWidgets.QFileDialog(self, "Select Python script to run")
        dlg.setFileMode(QtWidgets.QFileDialog.ExistingFile)
        dlg.setNameFilters(["Python scripts (*.py)", "All files (*)"])
        # Default to tests/ directory if it exists
        project_root = os.path.dirname(os.path.dirname(__file__))
        tests_dir = os.path.abspath(os.path.join(project_root, "tests"))
        if os.path.isdir(tests_dir):
            dlg.setDirectory(tests_dir)
        if not dlg.exec():
            return
        sel = dlg.selectedFiles()
        if not sel:
            return
        self._exec_script_file(sel[0])

    def _exec_script_file(self, path: str) -> None:
        """Execute a Python file in the same context used by the console.

        Args:
            path: path to a .py file
        """
        try:
            with open(path, "r", encoding="utf-8") as f:
                code = f.read()
        except Exception as ex:
            QtWidgets.QMessageBox.critical(self, "Script error", f"Cannot read script: {ex}")
            return

        # Build execution context
        ctx = dict(self._console_context())
        ctx.setdefault("window", self)
        ctx.setdefault("import_cloud", self.import_cloud_programmatic)
        try:
            import numpy as _np  # noqa: F401
            ctx.setdefault("np", _np)
        except Exception:
            pass
        try:
            import pyvista as _pv  # noqa: F401
            ctx.setdefault("pv", _pv)
        except Exception:
            pass
        ctx.setdefault("QtWidgets", QtWidgets)
        ctx.setdefault("QtCore", QtCore)
        ctx.setdefault("QtGui", QtGui)

        # Provide dunder variables for compatibility
        ctx["__file__"] = path
        ctx["__name__"] = "__main__"
        ctx["__package__"] = None

        # Allow relative imports and relative paths like in a normal script
        import sys
        script_dir = os.path.dirname(os.path.abspath(path))
        project_root = os.path.dirname(os.path.dirname(__file__))
        tests_dir = os.path.abspath(os.path.join(project_root, "tests"))
        old_cwd = os.getcwd()
        try:
            # Update sys.path
            for pth in (script_dir, tests_dir, project_root):
                if pth and pth not in sys.path:
                    sys.path.insert(0, pth)
            # Run with the script's folder as CWD
            os.chdir(script_dir)

            compiled = compile(code, path, "exec")
            exec(compiled, ctx, ctx)
            self.statusBar().showMessage(f"Executed script: {os.path.basename(path)}", 4000)
        except Exception as ex:
            QtWidgets.QMessageBox.critical(self, "Script execution error", str(ex))
        finally:
            # Restore working directory
            try:
                os.chdir(old_cwd)
            except Exception:
                pass

    def _on_run_tests_triplet(self) -> None:
        """Convenience: import the three example PLYs from tests/ directory."""
        project_root = os.path.dirname(os.path.dirname(__file__))
        tests_dir = os.path.abspath(os.path.join(project_root, "tests"))
        files = [
            "test_1_Corinthian_Column_Capital_RGB_no_normals.ply",
            "test_2_Rocca_North_tower_no_RGB.ply",
            "test_3_Turkish_pillar_RGB_normals.ply",
        ]
        missing = []
        for name in files:
            p = os.path.join(tests_dir, name)
            if os.path.isfile(p):
                try:
                    self.import_cloud_programmatic(p)
                except Exception as ex:
                    QtWidgets.QMessageBox.critical(self, "Import error", f"{name}: {ex}")
                    return
            else:
                missing.append(name)
        if missing:
            QtWidgets.QMessageBox.warning(self, "Missing files", "\n".join(["Not found in tests/:", *missing]))
        else:
            self.statusBar().showMessage("Triplet import completed", 4000)

    # ------------------------------------------------------------------
    # Programmatic import (no dialog)
    # ------------------------------------------------------------------
    def import_cloud_programmatic(
        self,
        path: str,
        *,
        axis_preset: str = "Z-up (identity)",
        color_preference: str = "auto",
        compute_normals_if_missing: bool = True,
        map_normals: bool = True,
    ) -> None:
        """Import a geometry file without showing the summary dialog.

        Mirrors `_on_import_cloud` pipeline with sensible defaults:
        - axis_preset: one of the presets in the summary dialog
        - color_preference: 'auto' | 'rgb' | 'colormap'
        - compute_normals_if_missing: compute rough normals if absent
        - map_normals: if True, apply axis preset also to normals
        """
        from .utils.io.importers import import_file

        # Presets consistent with ImportSummaryDialog
        presets = {
            "Z-up (identity)":  {"X": "+X", "Y": "+Y", "Z": "+Z"},
            "Y-up (swap Y/Z)":  {"X": "+X", "Y": "+Z", "Z": "-Y"},
            "X-up (swap X/Z)":  {"X": "+Z", "Y": "+Y", "Z": "-X"},
            "Flip Z":           {"X": "+X", "Y": "+Y", "Z": "-Z"},
            "Flip Y":           {"X": "+X", "Y": "-Y", "Z": "+Z"},
            "Flip X":           {"X": "-X", "Y": "+Y", "Z": "+Z"},
        }
        axis_map = presets.get(axis_preset, presets["Z-up (identity)"])

        try:
            objects = import_file(path)
        except Exception as ex:
            raise RuntimeError(f"Import error: {ex}")

        # Helpers (reuse lambdas from _on_import_cloud but kept local here)
        def _apply_axis_map(arr, axis_map):
            try:
                import numpy as _np
                if arr is None:
                    return None
                src = _np.asarray(arr, dtype=float)
                if src.ndim != 2 or src.shape[1] != 3:
                    return arr
                out = _np.empty_like(src)
                axes = {"X": 0, "Y": 1, "Z": 2}
                for tgt_key, expr in axis_map.items():
                    sign = -1.0 if expr.startswith("-") else 1.0
                    src_axis = axes[expr[-1]]
                    out[:, axes[tgt_key]] = sign * src[:, src_axis]
                return out
            except Exception:
                return arr

        def _compute_normals(obj):
            try:
                import numpy as _np
                import pyvista as _pv  # type: ignore
                if obj.points is None or obj.points.shape[0] == 0:
                    return None
                pdata = _pv.PolyData(_np.asarray(obj.points))
                pdata = pdata.compute_normals(
                    consistent=False,
                    auto_orient_normals=False,
                    feature_angle=180.0,
                )
                n = getattr(pdata, 'point_normals', None)
                if n is not None:
                    return _np.asarray(n, dtype=_np.float32)
            except Exception:
                return None
            return None

        # 1) Apply axis mapping / normals ops per object
        for obj in objects:
            obj.points = _apply_axis_map(obj.points, axis_map)
            if map_normals and getattr(obj, 'normals', None) is not None:
                obj.normals = _apply_axis_map(obj.normals, axis_map)
            elif compute_normals_if_missing and getattr(obj, 'normals', None) is None:
                n = _compute_normals(obj)
                if n is not None:
                    obj.normals = n
            # Color preference per object (auto: prefer RGB if available)
            if color_preference == "auto":
                obj.meta['color_preference'] = 'rgb' if obj.colors is not None else 'colormap'
            else:
                obj.meta['color_preference'] = color_preference

        # 2) Reuse the final part of the GUI pipeline to add to viewer & tree
        # Temporarily set viewer color-mode per object, as in _on_import_cloud
        for obj in objects:
            prev_mode = getattr(self.viewer3d, '_color_mode', None)
            try:
                pref = obj.meta.get('color_preference', 'rgb')
                if pref == 'colormap':
                    self.viewer3d.set_color_mode('Normal Colormap')
                else:
                    self.viewer3d.set_color_mode('Normal RGB')
            except Exception:
                prev_mode = None

            if obj.kind == "points" and obj.points is not None:
                ds_index = self.viewer3d.add_points(obj.points, obj.colors, getattr(obj, "normals", None))
            elif obj.kind == "mesh" and obj.pv_mesh is not None:
                ds_index = self.viewer3d.add_pyvista_mesh(obj.pv_mesh)
            else:
                ds_index = None

            try:
                self._reapply_overlays_safe()
            except Exception:
                pass
            try:
                if prev_mode is not None:
                    self.viewer3d.set_color_mode(prev_mode)
            except Exception:
                pass

            # 
            # Build the tree entries (same as interactive import)
            self.treeMCTS.blockSignals(True)
            root = QtWidgets.QTreeWidgetItem([obj.name])
            root.setFlags(
                root.flags()
                | QtCore.Qt.ItemFlag.ItemIsUserCheckable
                | QtCore.Qt.ItemFlag.ItemIsAutoTristate
            )
            root.setCheckState(0, QtCore.Qt.CheckState.Checked)
            self.treeMCTS.addTopLevelItem(root)

            if obj.kind == "points":
                it_points = QtWidgets.QTreeWidgetItem(["Point cloud"])
                it_points.setFlags(
                    it_points.flags()
                    | QtCore.Qt.ItemFlag.ItemIsUserCheckable
                    # | QtCore.Qt.ItemFlag.ItemIsAutoTristate
                )
                it_points.setCheckState(0, QtCore.Qt.CheckState.Checked)
                it_points.setData(0, QtCore.Qt.ItemDataRole.UserRole, {"kind": "points", "ds": ds_index})
                root.addChild(it_points)

                if getattr(obj, "normals", None) is not None:
                    it_normals = QtWidgets.QTreeWidgetItem(["Normals"])
                    it_normals.setFlags(
                        it_normals.flags() | QtCore.Qt.ItemFlag.ItemIsUserCheckable
                    )
                    it_normals.setCheckState(0, QtCore.Qt.CheckState.Unchecked)
                    it_normals.setData(0, QtCore.Qt.ItemDataRole.UserRole, {"kind": "normals", "ds": ds_index})
                    it_points.addChild(it_normals)
            else:
                it_mesh = QtWidgets.QTreeWidgetItem(["Mesh"])
                it_mesh.setFlags(it_mesh.flags() | QtCore.Qt.ItemFlag.ItemIsUserCheckable)
                it_mesh.setCheckState(0, QtCore.Qt.CheckState.Checked)
                it_mesh.setData(0, QtCore.Qt.ItemDataRole.UserRole, {"kind": "mesh", "ds": ds_index})
                root.addChild(it_mesh)

            self.treeMCTS.blockSignals(False)
            # 
            # Update visibility after adding.
            self._refresh_tree_visibility()

            # Register into MCTS and set current MCT so it's visible in console
            try:
                entry = {
                    "name": obj.name,
                    "kind": obj.kind,
                    "has_rgb": obj.colors is not None,
                    "has_intensity": getattr(obj, 'intensity', None) is not None,
                    "has_normals": getattr(obj, 'normals', None) is not None,
                    "ds_index": ds_index if (obj.kind == 'points' and ds_index is not None) else None,
                }
                self.mcts[obj.name] = entry
                self.mct = entry
                try:
                    self.treeMCTS.setCurrentItem(root)
                except Exception:
                    pass
            except Exception:
                pass

        self.statusBar().showMessage(f"Imported from {os.path.basename(path)}", 3000)

    # ----------------------- Normals: UI helpers ----------------------------
    def _invoke_set_progress_value(self, v: int) -> None:
        try:
            val = int(v)
            QtCore.QTimer.singleShot(0, lambda: self.progress.setValue(val))
        except Exception:
            pass

    def _invoke_set_progress_format(self, text: str) -> None:
        try:
            msg = str(text)
            QtCore.QTimer.singleShot(0, lambda: self.progress.setFormat(msg))
        except Exception:
            pass

    def _invoke_append_message(self, text: str) -> None:
        try:
            msg = str(text)
            QtCore.QTimer.singleShot(0, lambda: self.txtMessages.appendPlainText(msg))
        except Exception:
            pass

    def _append_message(self, text: str) -> None:
        self._invoke_append_message(text)

    # def _progress_start(self, text: str) -> None:
    #     try:
    #         self.progress.setRange(0, 100)
    #         self._invoke_set_progress_value(0)
    #         self._invoke_set_progress_format(text)
    #     except Exception:
    #         pass

    def _progress_update(self, value: int, text: Optional[str] = None) -> None:
        try:
            v = max(0, min(100, int(value)))
            self._invoke_set_progress_value(v)
            if text is not None:
                self._invoke_set_progress_format(text)
        except Exception:
            pass

    # def _progress_finish(self, text: str) -> None:
    #     try:
    #         self._invoke_set_progress_value(100)
    #         self._invoke_set_progress_format(text)
    #     except Exception:
    #         pass

    # @QtCore.Slot(int)
    # def _slot_worker_progress(self, pct: int) -> None:
    #     try:
    #         txt = getattr(self, "_last_progress_text", "")
    #         v = max(0, min(100, int(pct)))
    #         self._progress_update(v, txt)
    #     except Exception:
    #         pass

    # @QtCore.Slot(str)
    # def _slot_worker_message(self, msg: str) -> None:
    #     try:
    #         self._last_progress_text = str(msg)
    #         self._invoke_set_progress_format(self._last_progress_text)
    #         self._invoke_append_message(self._last_progress_text)
    #     except Exception:
    #         pass

    # def _ensure_cancel_button(self) -> None:
    #     """Enable the CANCEL button for an active job."""
    #     try:
    #         self.btnCancel.setEnabled(True)
    #     except Exception:
    #         pass

    # def _on_cancel_job(self) -> None:
    #     """Request cancellation of the active job, if supported by the worker."""
    #     job = getattr(self, "_active_job", None)
    #     if not job:
    #         return
    #     worker = job.get("worker")
    #     if hasattr(worker, "request_cancel"):
    #         worker.request_cancel()
    #     self._append_message("[Job] Cancel requested by user.")

    def _ensure_normals_tree_child(self, ds_index: int) -> None:
        """Ensure a 'Normals' child exists under the current file node for the active dataset."""
        try:
            item = self.treeMCTS.currentItem()
            if item is None:
                return
            # Ascend to root file node
            root = item
            while root.parent() is not None:
                root = root.parent()
            # Look for a child labeled 'Point cloud' or existing 'Normals'
            target = None
            for i in range(root.childCount()):
                c = root.child(i)
                if c.text(0) == "Point cloud":
                    target = c
                if c.text(0) == "Normals":
                    return  # already present at root level (older structure)
            if target is None:
                # Create the 'Point cloud' node if missing
                target = QtWidgets.QTreeWidgetItem(["Point cloud"])
                target.setFlags(target.flags() | QtCore.Qt.ItemFlag.ItemIsUserCheckable | QtCore.Qt.ItemFlag.ItemIsAutoTristate)
                target.setCheckState(0, QtCore.Qt.CheckState.Checked)
                target.setData(0, QtCore.Qt.ItemDataRole.UserRole, {"kind": "points", "ds": ds_index})
                root.addChild(target)
            # Add Normals child if not present
            for i in range(target.childCount()):
                if target.child(i).text(0) == "Normals":
                    return
            it_normals = QtWidgets.QTreeWidgetItem(["Normals"])
            it_normals.setFlags(it_normals.flags() | QtCore.Qt.ItemFlag.ItemIsUserCheckable)
            it_normals.setCheckState(0, QtCore.Qt.CheckState.Unchecked)
            it_normals.setData(0, QtCore.Qt.ItemDataRole.UserRole, {"kind": "normals", "ds": ds_index})
            target.addChild(it_normals)
        except Exception:
            pass


    # --------- Normals: helpers ---------------------------------------------

    def _current_ds_index(self) -> int | None:
        """Return the current dataset index or None if nothing is selected."""
        try:
            ds = self._current_dataset_index()
            return int(ds) if ds is not None else None
        except Exception:
            return None

    def _ensure_normals_visible(self, ds: int) -> None:
        """Ensure normals actor exists/visible for dataset ds before applying edits."""
        v3d = self.viewer3d
        # Prova API moderna
        set_vis = getattr(v3d, "set_normals_visibility", None)
        if callable(set_vis):
            set_vis(ds, True)
            # Sincronizza anche il toggle della toolbar se esiste
            try:
                self.act_toggle_normals.blockSignals(True)
                self.act_toggle_normals.setChecked(True)
                self.act_toggle_normals.blockSignals(False)
            except Exception:
                pass
            return
        # Fallback: prova a ricostruire direttamente
        rb = getattr(v3d, "_rebuild_normals_actor", None)
        if callable(rb):
            rb(ds)
        try:
            # best effort: attivalo come “visibile” nello stato locale
            rec = v3d._datasets[ds]
            rec["normals_visible"] = True
        except Exception:
            pass

    def _apply_normals_rebuild(self, ds: int) -> None:
        """Chiama il rebuild con i parametri correnti del dataset."""
        v3d = self.viewer3d
        # Se la API granulari esistono, non serve forzare il rebuild manuale
        rb = getattr(v3d, "_rebuild_normals_actor", None)
        if callable(rb):
            # Recupera parametri correnti (con fallback a default)
            try:
                rec = v3d._datasets[ds]
                style = str(rec.get("normals_style", getattr(v3d, "_normals_style", "Uniform")))
                color = tuple(rec.get("normals_color", getattr(v3d, "_normals_color", (1.0, 0.2, 0.2))))
                percent = int(rec.get("normals_percent", getattr(v3d, "_normals_percent", 1)))
                scale = int(rec.get("normals_scale", getattr(v3d, "_normals_scale", 20)))
            except Exception:
                style, color, percent, scale = "Uniform", (1.0, 0.2, 0.2), 50, 20
            rb(ds, style=style, color=color, percent=percent, scale=scale)

    # --------- Normals: handlers from DisplayPanel --------------------------

    # ------------------------------
    # Normals display live updates
    # ------------------------------
    # ----------------------- Normals: handlers ----------------------------
    def _on_normals_style_changed(self, mode: str) -> None:
        """
        Change the visualization style of normals for the currently selected dataset.

        Args:
            mode (str): The style mode to apply. Options include:
                - 'Uniform': Uniform color for all normals.
                - 'Axis RGB': Color normals based on their axis orientation.
                - 'RGB Components': Color normals based on their RGB components.
        """
        ds = self._current_dataset_index()
        if ds is None:
            return
        # Update the internal MCT (Metadata Context Table) state if available
        try:
            if self.mct is not None:
                self.mct["normals_style"] = mode
        except Exception:
            pass
        # Attempt to use the viewer's public API; if unavailable, fallback to rebuilding
        try:
            fn = getattr(self.viewer3d, "set_normals_style", None)
            if callable(fn):
                fn(ds, mode)
            else:
                # Fallback: force a rebuild with the new parameters while maintaining current visibility
                self._apply_normals_update(ds, style=mode)
        except Exception:
            pass

    def _on_normals_color_changed(self, col: QtGui.QColor) -> None:
        """
        Change the uniform color of normals. This is only applicable if the style is set to 'Uniform'.

        Args:
            col (QtGui.QColor): The new color to apply.
        """
        if col is None or not col.isValid():
            return
        ds = self._current_dataset_index()
        if ds is None:
            return
        rgb = (col.red(), col.green(), col.blue())
        # Update the internal MCT state if available
        try:
            if self.mct is not None:
                self.mct["normals_color"] = rgb
        except Exception:
            pass
        # Attempt to use the viewer's public API; if unavailable, fallback to rebuilding
        try:
            fn = getattr(self.viewer3d, "set_normals_color", None)
            if callable(fn):
                fn(ds, *rgb)
            else:
                self._apply_normals_update(ds, color=rgb)
        except Exception:
            pass

    def _on_normals_percent_changed(self, percent: int) -> None:
        """
        Change the percentage of normals displayed for the currently selected dataset.

        Args:
            percent (int): The percentage of normals to display (1 to 100).
        """
        ds = self._current_dataset_index()
        if ds is None:
            return
        p = int(max(1, min(100, percent)))  # Clamp the value between 1 and 100
        # Update the internal MCT state if available
        try:
            if self.mct is not None:
                self.mct["normals_percent"] = p
        except Exception:
            pass
        # Attempt to use the viewer's public API; if unavailable, fallback to rebuilding
        try:
            fn = getattr(self.viewer3d, "set_normals_percent", None)
            if callable(fn):
                fn(ds, p)
            else:
                self._apply_normals_update(ds, percent=p)
        except Exception:
            pass

    def _on_normals_scale_changed(self, scale: int) -> None:
        """
        Change the scale (vector size) of normals for the currently selected dataset.

        Args:
            scale (int): The scale factor for normals. Valid range is 1 to 200.
        """
        ds = self._current_dataset_index()
        if ds is None:
            return
        s = int(max(1, min(200, scale)))  # Clamp the value between 1 and 200
        # Update the internal MCT state if available
        try:
            if self.mct is not None:
                self.mct["normals_scale"] = s
        except Exception:
            pass
        # Attempt to use the viewer's public API; if unavailable, fallback to rebuilding
        try:
            fn = getattr(self.viewer3d, "set_normals_scale", None)
            if callable(fn):
                fn(ds, s)
            else:
                self._apply_normals_update(ds, scale=s)
        except Exception:
            pass

    # Helper: apply changes to normals by rebuilding the glyph actor if necessary
    def _apply_normals_update(self, ds: int, *, style: str | None = None,
                              color: tuple[int, int, int] | None = None,
                              percent: int | None = None,
                              scale: int | None = None) -> None:
        """
        Updates the normals parameters in the viewer's dataset record and forces the
        reconstruction of the glyph actor while maintaining the current visibility state.

        Args:
            ds (int): The dataset index to update.
            style (str | None): The visualization style for normals (e.g., 'Uniform', 'Axis RGB').
            color (tuple[int, int, int] | None): The RGB color for normals, as integers in the range 0-255.
            percent (int | None): The percentage of normals to display (1 to 100).
            scale (int | None): The scale factor for normals (1 to 200).
        """
        try:
            recs = getattr(self.viewer3d, "_datasets", [])
            if not (0 <= ds < len(recs)):
                return
            rec = recs[ds]
            # Update per-dataset state
            if style is not None:
                rec["normals_style"] = style
            if color is not None:
                # Normalize color to float 0..1 if the viewer expects it, otherwise keep 0..255
                try:
                    rec["normals_color"] = tuple(float(c)/255.0 for c in color)
                except Exception:
                    rec["normals_color"] = color
            if percent is not None:
                rec["normals_percent"] = int(max(1, min(100, percent)))
            if scale is not None:
                rec["normals_scale"] = int(max(1, min(200, scale)))

            # If normals are currently visible, rebuild the actor; otherwise, do nothing
            # (the actor will be rebuilt when toggled ON).
            visible = bool(rec.get("normals_visible", False))
            if visible:
                # Prefer public API if it exists
                rb = getattr(self.viewer3d, "_rebuild_normals_actor", None)
                if callable(rb):
                    rb(
                        ds,
                        style=str(rec.get("normals_style", "Axis RGB")),
                        color=tuple(rec.get("normals_color", (0.9, 0.9, 0.2))),
                        percent=int(rec.get("normals_percent", 1)),
                        scale=int(rec.get("normals_scale", 20)),
                    )
                else:
                    # As a fallback, force set_normals_visibility(True), which internally triggers a rebuild
                    getattr(self.viewer3d, "set_normals_visibility", lambda *_: None)(ds, True)
            # Perform a lightweight refresh of the viewer
            try:
                self.viewer3d.refresh()
            except Exception:
                pass
        except Exception:
            pass


    def _on_fast_normals_toggled(self, enabled: bool) -> None:
        """
        Persist the user's preference for 'Fast normals' in the window state.

        Args:
            enabled (bool): Whether the 'Fast normals' mode is enabled or not.
        """
        try:
            self.normals_fast_enabled = bool(enabled)
        except Exception:
            pass
    # ------------------------------------------------------------------
    # ViewSettingsDialog: edit 3D viewer settings (background, grid, colorbar, points style)
    # ------------------------------------------------------------------
    class ViewSettingsDialog(QtWidgets.QDialog):
        """Dialog to customize 3D view preferences (background, grid, colorbar, points style)."""
        def __init__(self, parent=None, state: dict | None = None):
            super().__init__(parent)
            self.setWindowTitle("3D View Settings")
            self.setModal(True)
            self._state = dict(state or {})

            lay = QtWidgets.QVBoxLayout(self)

            # Background color picker
            row_bg = QtWidgets.QHBoxLayout()
            row_bg.addWidget(QtWidgets.QLabel("Background:"))
            self.btnBg = QtWidgets.QPushButton()
            self.btnBg.setFixedWidth(120)
            self.btnBg.clicked.connect(self._pick_bg)
            row_bg.addWidget(self.btnBg)
            row_bg.addStretch(1)
            lay.addLayout(row_bg)

            # Grid + points style
            self.chkGrid = QtWidgets.QCheckBox("Show grid")
            self.chkPtsSpheres = QtWidgets.QCheckBox("Render points as spheres")
            lay.addWidget(self.chkGrid)
            lay.addWidget(self.chkPtsSpheres)

            # Colorbar controls
            gb = QtWidgets.QGroupBox("Colorbar")
            gl = QtWidgets.QFormLayout(gb)
            self.cmbBar = QtWidgets.QComboBox()
            self.cmbBar.addItems(["Hidden", "Horizontal (bottom-right)", "Vertical (top-right)"])
            self.edBarTitle = QtWidgets.QLineEdit()
            gl.addRow("Mode:", self.cmbBar)
            gl.addRow("Title:", self.edBarTitle)
            lay.addWidget(gb)

            # Buttons
            btns = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel | QtWidgets.QDialogButtonBox.Apply)
            btns.accepted.connect(self.accept)
            btns.rejected.connect(self.reject)
            btns.button(QtWidgets.QDialogButtonBox.Apply).clicked.connect(self._apply_only)
            lay.addWidget(btns)

            self._load_state()

        def _load_state(self):
            """Populate widgets from the provided state dict."""
            bg = tuple(self._state.get("bg", (30, 30, 30)))
            self._set_btn_bg(bg)
            self.chkGrid.setChecked(bool(self._state.get("grid", True)))
            self.chkPtsSpheres.setChecked(bool(self._state.get("points_as_spheres", True)))
            mode = str(self._state.get("colorbar_mode", "vertical-tr"))
            idx = {"hidden":0, "horizontal-br":1, "vertical-tr":2}.get(mode, 2)
            self.cmbBar.setCurrentIndex(idx)
            self.edBarTitle.setText(str(self._state.get("colorbar_title", "")))

        def _set_btn_bg(self, rgb: tuple[int, int, int]):
            """Update the background button swatch."""
            try:
                r, g, b = map(int, rgb)
                self.btnBg.setText(f"RGB {r},{g},{b}")
                self.btnBg.setStyleSheet(f"background-color: rgb({r},{g},{b}); color: white;")
            except Exception:
                pass

        def _pick_bg(self):
            """Open a QColorDialog to pick a background color."""
            try:
                c0 = QtGui.QColor(*self._state.get("bg", (30, 30, 30)))
                col = QtWidgets.QColorDialog.getColor(c0, self, "Pick background color")
                if col.isValid():
                    self._state["bg"] = (col.red(), col.green(), col.blue())
                    self._set_btn_bg(self._state["bg"])
            except Exception:
                pass

        def values(self) -> dict:
            """Return current dialog values as a dict."""
            mode_idx = int(self.cmbBar.currentIndex())
            mode = {0:"hidden", 1:"horizontal-br", 2:"vertical-tr"}.get(mode_idx, "vertical-tr")
            return {
                "bg": tuple(self._state.get("bg", (30,30,30))),
                "grid": bool(self.chkGrid.isChecked()),
                "points_as_spheres": bool(self.chkPtsSpheres.isChecked()),
                "colorbar_mode": mode,
                "colorbar_title": self.edBarTitle.text().strip(),
            }

        def _apply_only(self):
            self.done(2)  # custom code for Apply

    def _on_open_view_settings(self) -> None:
        """Open the 3D view settings dialog and apply changes (Apply/OK)."""
        st = dict(getattr(self, "_view_prefs", {}))
        dlg = self.ViewSettingsDialog(self, state=st)
        code = dlg.exec()

        def _apply(vals: dict):
            v3d = getattr(self, "viewer3d", None)
            if v3d is None:
                return
            # Background
            try:
                getattr(v3d, "set_background_color", lambda *_: None)(vals["bg"])  # (r,g,b)
            except Exception:
                pass
            # Grid
            try:
                on = bool(vals.get("grid", True))
                for name in ("set_grid_enabled", "set_grid_visible", "toggle_grid", "show_grid"):
                    fn = getattr(v3d, name, None)
                    if callable(fn):
                        try:
                            fn(on)
                            break
                        except Exception:
                            continue
            except Exception:
                pass
            # Points as spheres
            try:
                getattr(v3d, "set_points_as_spheres", lambda *_: None)(bool(vals.get("points_as_spheres", True)))
            except Exception:
                pass
            # Colorbar placement
            try:
                getattr(v3d, "set_colorbar_mode", lambda *_: None)(str(vals.get("colorbar_mode", "vertical-tr")), str(vals.get("colorbar_title", "")))
            except Exception:
                # Fallback: try vertical/hide helper if available
                mode = str(vals.get("colorbar_mode", "vertical-tr"))
                if mode == "hidden":
                    try:
                        v3d.set_colorbar_vertical(False)
                    except Exception:
                        pass
                elif mode == "vertical-tr":
                    try:
                        v3d.set_colorbar_vertical(True, str(vals.get("colorbar_title", "")))
                    except Exception:
                        pass

            try:
                v3d._apply_background(); v3d._apply_scalarbar()
            except Exception:
                pass
            # Keep a copy for next time
            try:
                self._view_prefs.update(vals)
            except Exception:
                pass
            try:
                v3d.refresh()
            except Exception:
                pass

        # Apply immediately for Apply/OK
        if code == 2 or code == QtWidgets.QDialog.Accepted:
            _apply(dlg.values())

downsample_method = 'random' instance-attribute

mct = {} instance-attribute

mcts = {} instance-attribute

plugin_manager = PluginManager(self, plugins_dir=(self._default_plugins_dir())) instance-attribute

undo_stack = QtGui.QUndoStack(self) instance-attribute

ViewSettingsDialog

Bases: QDialog

Dialog to customize 3D view preferences (background, grid, colorbar, points style).

Source code in src/c2f4dt/main_window.py
class ViewSettingsDialog(QtWidgets.QDialog):
    """Dialog to customize 3D view preferences (background, grid, colorbar, points style)."""
    def __init__(self, parent=None, state: dict | None = None):
        super().__init__(parent)
        self.setWindowTitle("3D View Settings")
        self.setModal(True)
        self._state = dict(state or {})

        lay = QtWidgets.QVBoxLayout(self)

        # Background color picker
        row_bg = QtWidgets.QHBoxLayout()
        row_bg.addWidget(QtWidgets.QLabel("Background:"))
        self.btnBg = QtWidgets.QPushButton()
        self.btnBg.setFixedWidth(120)
        self.btnBg.clicked.connect(self._pick_bg)
        row_bg.addWidget(self.btnBg)
        row_bg.addStretch(1)
        lay.addLayout(row_bg)

        # Grid + points style
        self.chkGrid = QtWidgets.QCheckBox("Show grid")
        self.chkPtsSpheres = QtWidgets.QCheckBox("Render points as spheres")
        lay.addWidget(self.chkGrid)
        lay.addWidget(self.chkPtsSpheres)

        # Colorbar controls
        gb = QtWidgets.QGroupBox("Colorbar")
        gl = QtWidgets.QFormLayout(gb)
        self.cmbBar = QtWidgets.QComboBox()
        self.cmbBar.addItems(["Hidden", "Horizontal (bottom-right)", "Vertical (top-right)"])
        self.edBarTitle = QtWidgets.QLineEdit()
        gl.addRow("Mode:", self.cmbBar)
        gl.addRow("Title:", self.edBarTitle)
        lay.addWidget(gb)

        # Buttons
        btns = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel | QtWidgets.QDialogButtonBox.Apply)
        btns.accepted.connect(self.accept)
        btns.rejected.connect(self.reject)
        btns.button(QtWidgets.QDialogButtonBox.Apply).clicked.connect(self._apply_only)
        lay.addWidget(btns)

        self._load_state()

    def _load_state(self):
        """Populate widgets from the provided state dict."""
        bg = tuple(self._state.get("bg", (30, 30, 30)))
        self._set_btn_bg(bg)
        self.chkGrid.setChecked(bool(self._state.get("grid", True)))
        self.chkPtsSpheres.setChecked(bool(self._state.get("points_as_spheres", True)))
        mode = str(self._state.get("colorbar_mode", "vertical-tr"))
        idx = {"hidden":0, "horizontal-br":1, "vertical-tr":2}.get(mode, 2)
        self.cmbBar.setCurrentIndex(idx)
        self.edBarTitle.setText(str(self._state.get("colorbar_title", "")))

    def _set_btn_bg(self, rgb: tuple[int, int, int]):
        """Update the background button swatch."""
        try:
            r, g, b = map(int, rgb)
            self.btnBg.setText(f"RGB {r},{g},{b}")
            self.btnBg.setStyleSheet(f"background-color: rgb({r},{g},{b}); color: white;")
        except Exception:
            pass

    def _pick_bg(self):
        """Open a QColorDialog to pick a background color."""
        try:
            c0 = QtGui.QColor(*self._state.get("bg", (30, 30, 30)))
            col = QtWidgets.QColorDialog.getColor(c0, self, "Pick background color")
            if col.isValid():
                self._state["bg"] = (col.red(), col.green(), col.blue())
                self._set_btn_bg(self._state["bg"])
        except Exception:
            pass

    def values(self) -> dict:
        """Return current dialog values as a dict."""
        mode_idx = int(self.cmbBar.currentIndex())
        mode = {0:"hidden", 1:"horizontal-br", 2:"vertical-tr"}.get(mode_idx, "vertical-tr")
        return {
            "bg": tuple(self._state.get("bg", (30,30,30))),
            "grid": bool(self.chkGrid.isChecked()),
            "points_as_spheres": bool(self.chkPtsSpheres.isChecked()),
            "colorbar_mode": mode,
            "colorbar_title": self.edBarTitle.text().strip(),
        }

    def _apply_only(self):
        self.done(2)  # custom code for Apply
btnBg = QtWidgets.QPushButton() instance-attribute
chkGrid = QtWidgets.QCheckBox('Show grid') instance-attribute
chkPtsSpheres = QtWidgets.QCheckBox('Render points as spheres') instance-attribute
cmbBar = QtWidgets.QComboBox() instance-attribute
edBarTitle = QtWidgets.QLineEdit() instance-attribute
values()

Return current dialog values as a dict.

Source code in src/c2f4dt/main_window.py
def values(self) -> dict:
    """Return current dialog values as a dict."""
    mode_idx = int(self.cmbBar.currentIndex())
    mode = {0:"hidden", 1:"horizontal-br", 2:"vertical-tr"}.get(mode_idx, "vertical-tr")
    return {
        "bg": tuple(self._state.get("bg", (30,30,30))),
        "grid": bool(self.chkGrid.isChecked()),
        "points_as_spheres": bool(self.chkPtsSpheres.isChecked()),
        "colorbar_mode": mode,
        "colorbar_title": self.edBarTitle.text().strip(),
    }

import_cloud_programmatic(path, *, axis_preset='Z-up (identity)', color_preference='auto', compute_normals_if_missing=True, map_normals=True)

Import a geometry file without showing the summary dialog.

Mirrors _on_import_cloud pipeline with sensible defaults: - axis_preset: one of the presets in the summary dialog - color_preference: 'auto' | 'rgb' | 'colormap' - compute_normals_if_missing: compute rough normals if absent - map_normals: if True, apply axis preset also to normals

Source code in src/c2f4dt/main_window.py
def import_cloud_programmatic(
    self,
    path: str,
    *,
    axis_preset: str = "Z-up (identity)",
    color_preference: str = "auto",
    compute_normals_if_missing: bool = True,
    map_normals: bool = True,
) -> None:
    """Import a geometry file without showing the summary dialog.

    Mirrors `_on_import_cloud` pipeline with sensible defaults:
    - axis_preset: one of the presets in the summary dialog
    - color_preference: 'auto' | 'rgb' | 'colormap'
    - compute_normals_if_missing: compute rough normals if absent
    - map_normals: if True, apply axis preset also to normals
    """
    from .utils.io.importers import import_file

    # Presets consistent with ImportSummaryDialog
    presets = {
        "Z-up (identity)":  {"X": "+X", "Y": "+Y", "Z": "+Z"},
        "Y-up (swap Y/Z)":  {"X": "+X", "Y": "+Z", "Z": "-Y"},
        "X-up (swap X/Z)":  {"X": "+Z", "Y": "+Y", "Z": "-X"},
        "Flip Z":           {"X": "+X", "Y": "+Y", "Z": "-Z"},
        "Flip Y":           {"X": "+X", "Y": "-Y", "Z": "+Z"},
        "Flip X":           {"X": "-X", "Y": "+Y", "Z": "+Z"},
    }
    axis_map = presets.get(axis_preset, presets["Z-up (identity)"])

    try:
        objects = import_file(path)
    except Exception as ex:
        raise RuntimeError(f"Import error: {ex}")

    # Helpers (reuse lambdas from _on_import_cloud but kept local here)
    def _apply_axis_map(arr, axis_map):
        try:
            import numpy as _np
            if arr is None:
                return None
            src = _np.asarray(arr, dtype=float)
            if src.ndim != 2 or src.shape[1] != 3:
                return arr
            out = _np.empty_like(src)
            axes = {"X": 0, "Y": 1, "Z": 2}
            for tgt_key, expr in axis_map.items():
                sign = -1.0 if expr.startswith("-") else 1.0
                src_axis = axes[expr[-1]]
                out[:, axes[tgt_key]] = sign * src[:, src_axis]
            return out
        except Exception:
            return arr

    def _compute_normals(obj):
        try:
            import numpy as _np
            import pyvista as _pv  # type: ignore
            if obj.points is None or obj.points.shape[0] == 0:
                return None
            pdata = _pv.PolyData(_np.asarray(obj.points))
            pdata = pdata.compute_normals(
                consistent=False,
                auto_orient_normals=False,
                feature_angle=180.0,
            )
            n = getattr(pdata, 'point_normals', None)
            if n is not None:
                return _np.asarray(n, dtype=_np.float32)
        except Exception:
            return None
        return None

    # 1) Apply axis mapping / normals ops per object
    for obj in objects:
        obj.points = _apply_axis_map(obj.points, axis_map)
        if map_normals and getattr(obj, 'normals', None) is not None:
            obj.normals = _apply_axis_map(obj.normals, axis_map)
        elif compute_normals_if_missing and getattr(obj, 'normals', None) is None:
            n = _compute_normals(obj)
            if n is not None:
                obj.normals = n
        # Color preference per object (auto: prefer RGB if available)
        if color_preference == "auto":
            obj.meta['color_preference'] = 'rgb' if obj.colors is not None else 'colormap'
        else:
            obj.meta['color_preference'] = color_preference

    # 2) Reuse the final part of the GUI pipeline to add to viewer & tree
    # Temporarily set viewer color-mode per object, as in _on_import_cloud
    for obj in objects:
        prev_mode = getattr(self.viewer3d, '_color_mode', None)
        try:
            pref = obj.meta.get('color_preference', 'rgb')
            if pref == 'colormap':
                self.viewer3d.set_color_mode('Normal Colormap')
            else:
                self.viewer3d.set_color_mode('Normal RGB')
        except Exception:
            prev_mode = None

        if obj.kind == "points" and obj.points is not None:
            ds_index = self.viewer3d.add_points(obj.points, obj.colors, getattr(obj, "normals", None))
        elif obj.kind == "mesh" and obj.pv_mesh is not None:
            ds_index = self.viewer3d.add_pyvista_mesh(obj.pv_mesh)
        else:
            ds_index = None

        try:
            self._reapply_overlays_safe()
        except Exception:
            pass
        try:
            if prev_mode is not None:
                self.viewer3d.set_color_mode(prev_mode)
        except Exception:
            pass

        # 
        # Build the tree entries (same as interactive import)
        self.treeMCTS.blockSignals(True)
        root = QtWidgets.QTreeWidgetItem([obj.name])
        root.setFlags(
            root.flags()
            | QtCore.Qt.ItemFlag.ItemIsUserCheckable
            | QtCore.Qt.ItemFlag.ItemIsAutoTristate
        )
        root.setCheckState(0, QtCore.Qt.CheckState.Checked)
        self.treeMCTS.addTopLevelItem(root)

        if obj.kind == "points":
            it_points = QtWidgets.QTreeWidgetItem(["Point cloud"])
            it_points.setFlags(
                it_points.flags()
                | QtCore.Qt.ItemFlag.ItemIsUserCheckable
                # | QtCore.Qt.ItemFlag.ItemIsAutoTristate
            )
            it_points.setCheckState(0, QtCore.Qt.CheckState.Checked)
            it_points.setData(0, QtCore.Qt.ItemDataRole.UserRole, {"kind": "points", "ds": ds_index})
            root.addChild(it_points)

            if getattr(obj, "normals", None) is not None:
                it_normals = QtWidgets.QTreeWidgetItem(["Normals"])
                it_normals.setFlags(
                    it_normals.flags() | QtCore.Qt.ItemFlag.ItemIsUserCheckable
                )
                it_normals.setCheckState(0, QtCore.Qt.CheckState.Unchecked)
                it_normals.setData(0, QtCore.Qt.ItemDataRole.UserRole, {"kind": "normals", "ds": ds_index})
                it_points.addChild(it_normals)
        else:
            it_mesh = QtWidgets.QTreeWidgetItem(["Mesh"])
            it_mesh.setFlags(it_mesh.flags() | QtCore.Qt.ItemFlag.ItemIsUserCheckable)
            it_mesh.setCheckState(0, QtCore.Qt.CheckState.Checked)
            it_mesh.setData(0, QtCore.Qt.ItemDataRole.UserRole, {"kind": "mesh", "ds": ds_index})
            root.addChild(it_mesh)

        self.treeMCTS.blockSignals(False)
        # 
        # Update visibility after adding.
        self._refresh_tree_visibility()

        # Register into MCTS and set current MCT so it's visible in console
        try:
            entry = {
                "name": obj.name,
                "kind": obj.kind,
                "has_rgb": obj.colors is not None,
                "has_intensity": getattr(obj, 'intensity', None) is not None,
                "has_normals": getattr(obj, 'normals', None) is not None,
                "ds_index": ds_index if (obj.kind == 'points' and ds_index is not None) else None,
            }
            self.mcts[obj.name] = entry
            self.mct = entry
            try:
                self.treeMCTS.setCurrentItem(root)
            except Exception:
                pass
        except Exception:
            pass

    self.statusBar().showMessage(f"Imported from {os.path.basename(path)}", 3000)