Skip to content

Viewers

Qt/PyVista viewers: session-embedded authoring viewers plus the results session window for post-processing.

ModelViewer — g.model.viewer()

apeGmsh.viewers.model_viewer.ModelViewer

ModelViewer(parent: '_SessionBase', model: 'Model', *, physical_group: str | None = None, dims: list[int] | None = None, point_size: float | None = None, line_width: float | None = None, surface_opacity: float | None = None, show_surface_edges: bool | None = None, origin_markers: list[tuple[float, float, float]] | None = None, origin_marker_show_coords: bool | None = None, on_selection_changed: Callable[['SelectionState'], None] | None = None, annotate: bool = False)

Interactive BRep model viewer with physical group management.

Displays BRep geometry, parts, physical groups, and labels. This is a geometry-only viewer — loads, constraints, and masses are mesh-resolved concepts and live on g.mesh.viewer() instead.

Parameters

parent : _SessionBase The apeGmsh session (provides name, _verbose). model : Model The apeGmsh model (provides sync()). physical_group : str, optional Auto-activate this physical group on open. dims : list[int], optional Which entity dimensions to show (default: [0, 1, 2, 3]). point_size, line_width, surface_opacity, show_surface_edges Visual properties forwarded to the scene builder. on_selection_changed : callable, optional callback(SelectionState) fired on every pick change (ADR 0095 studio host). Dispatcher-legal owner mutator. annotate : bool If True, turn on part + entity name labels with overall sizes (cotas) at open. Studio host sets this; the View tab still toggles them.

Source code in src/apeGmsh/viewers/model_viewer.py
def __init__(
    self,
    parent: "_SessionBase",
    model: "Model",
    *,
    physical_group: str | None = None,
    dims: list[int] | None = None,
    point_size: float | None = None,
    line_width: float | None = None,
    surface_opacity: float | None = None,
    show_surface_edges: bool | None = None,
    origin_markers: list[tuple[float, float, float]] | None = None,
    origin_marker_show_coords: bool | None = None,
    on_selection_changed: Callable[["SelectionState"], None] | None = None,
    annotate: bool = False,
) -> None:
    from .ui.preferences_manager import PREFERENCES
    p = PREFERENCES.current

    self._parent = parent
    self._model = model
    self._dims = dims if dims is not None else [0, 1, 2, 3]
    self._physical_group = physical_group

    # Visual props — explicit kwarg wins, otherwise pull user preference.
    self._point_size = point_size if point_size is not None else p.point_size
    self._line_width = line_width if line_width is not None else p.line_width
    self._surface_opacity = (
        surface_opacity if surface_opacity is not None else p.surface_opacity
    )
    self._show_surface_edges = (
        show_surface_edges if show_surface_edges is not None
        else p.show_surface_edges
    )

    # Origin marker overlay. User preference controls whether the
    # default is ``[(0,0,0)]`` or ``[]``; explicit kwarg wins.
    if origin_markers is not None:
        self._origin_markers: list[tuple[float, float, float]] = list(origin_markers)
    elif p.origin_marker_include_world_origin:
        self._origin_markers = [(0.0, 0.0, 0.0)]
    else:
        self._origin_markers = []
    self._origin_marker_show_coords = (
        origin_marker_show_coords if origin_marker_show_coords is not None
        else p.origin_marker_show_coords
    )

    # Populated during show()
    self._selection_state: "SelectionState | None" = None
    self._registry: "EntityRegistry | None" = None
    # ADR 0095 S2: host publishes a SelectionEnvelope on pick.
    # Dispatcher-legal (owner mutator callback); not Outline puppeteering.
    self._on_selection_changed = on_selection_changed
    self._annotate = annotate

    # Plan 04 step 4 — per-viewer ActiveObjects coordinator.
    # Constructed once a QApplication / window exists (in show()).
    # ModelViewer has no pick-mode concept — only the
    # ``selectionChanged`` bridge is wired today. The legacy
    # ``sel.on_changed`` cascade (recolor → tree → browser →
    # parts_tree) stays untouched per the
    # plan doc's one-release compatibility shim policy; the bridge
    # gives future panels a Qt-signal entry point without forcing
    # them through ``SelectionState``'s internal callback list.
    self._active: Any = None

selection property

selection

The current working set as a :class:Selection object.

tags property

tags: list[DimTag]

The current working set as a list of DimTags.

active_group property

active_group: str | None

The name of the physical group currently receiving picks.

show

show(*, title: str | None = None, maximized: bool = True)

Open the viewer window, block until closed.

Source code in src/apeGmsh/viewers/model_viewer.py
 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
def show(self, *, title: str | None = None, maximized: bool = True):
    """Open the viewer window, block until closed."""
    from .core.navigation import install_navigation
    from .core.color_manager import ColorManager
    from .core.filter_controller import FilterController
    from .core.pick_engine import PickEngine
    from .core.visibility import VisibilityManager
    from .core.selection import SelectionState
    from .scene.brep_scene import build_brep_scene
    from .scene.bbox_source import gmsh_bbox, gmsh_model_bbox
    from .ui.viewer_window import ViewerWindow
    from .ui.preferences import PreferencesTab
    from .ui.model_tabs import (
        FilterTab, ViewTab, SelectionTreePanel, PartsTreePanel,
    )

    # Ensure geometry is synced
    gmsh.model.occ.synchronize()

    # ── Window (creates QApplication + plotter) ─────────────────
    default_title = (
        f"ModelViewer — {self._parent.name}"
        + (f" -> {self._physical_group}" if self._physical_group else "")
    )

    # ── Selection state ─────────────────────────────────────────
    sel = SelectionState()
    self._selection_state = sel

    # Seed staging with pre-existing user-facing PGs (skip labels).
    # ADR 0045 S3c: staging is authoritative, so pull existing groups
    # in up front — the browser/outline read staged, gmsh is written
    # back only at flush (window close).
    sel.seed_from_gmsh()

    if self._physical_group is not None:
        sel.set_active_group(self._physical_group)

    # Pre-init the on_close closure vars (mirrors the _cb_parts_tree
    # pre-init below): the close handler references these before they
    # are assigned ~1300 lines down, so bind them to None up front to
    # stay NameError-safe if construction is ever reordered or aborts
    # early. The real assignments / the _on_sel_changed def overwrite
    # these.
    _on_sel_changed = _cb_sel_tree = _cb_outline = _cb_parts_tree = None
    _cb_active = _cb_theme_sel = _cb_theme_tn = None
    _cb_theme_origin = _cb_theme_measure = None
    _studio_sel = None

    def _on_close():
        # Remove sel.on_changed subscribers registered by this viewer.
        for _cb in (
            _on_sel_changed,
            _cb_sel_tree,
            _cb_outline,
            _cb_parts_tree,
            _cb_active,
            _studio_sel,
        ):
            if _cb is not None:
                try:
                    sel.on_changed.remove(_cb)
                except ValueError:
                    pass
        # Remove win._theme_callbacks subscribers registered by this viewer.
        # ViewerWindow has no off_theme_changed(), so we remove directly.
        for _cb in (
            _cb_theme_sel, _cb_theme_tn,
            _cb_theme_origin, _cb_theme_measure,
        ):
            try:
                win._theme_callbacks.remove(_cb)
            except ValueError:
                pass
        try:
            n = sel.flush_to_gmsh()
        except Exception as exc:
            # Log the full traceback so the user can debug, then surface
            # a dialog. Do NOT re-raise — the user is closing the window;
            # crashing their program after-the-fact loses session state.
            import sys
            import traceback
            print(
                f"[viewer] flush_to_gmsh failed on close: {exc}",
                file=sys.stderr,
            )
            traceback.print_exc(file=sys.stderr)
            try:
                from qtpy import QtWidgets
                QtWidgets.QMessageBox.critical(
                    win.window,
                    "Failed to write physical groups",
                    f"{exc}\n\nSee console for full traceback. "
                    "Pending picks were not committed.",
                )
            except Exception:
                pass
            return
        if self._parent._verbose:
            print(f"[viewer] closed — {n} physical group(s) written, "
                  f"{len(sel.picks)} picks in working set")

    # Create window FIRST so QApplication exists for Qt widgets.
    # ``window_key`` opts into layout persistence under
    # ``QSettings("apeGmsh", "ModelViewer")`` (plan 08 follow-up).
    # The left-column nav docks (Outline + Selection) are registered
    # HERE as construction-time placeholder extension docks so they
    # are present at saveState / restoreState time — the same path
    # the built-in docks use, which is why they never get stuck. The
    # real trees (which need scene / selection state built later) are
    # swapped in via ``win.set_extension_dock_widget`` once ready.
    # ``sanitize=True`` opts them into the per-launch heal.
    from qtpy import QtWidgets as _QtW_nav
    from .ui._dock_registry import DockSpec as _NavDockSpec
    from .ui._layout_metrics import LAYOUT as _NAV_LAYOUT
    _nav_floors = dict(
        sanitize=True,
        min_width=_NAV_LAYOUT.outline_min_width,
        initial_width=_NAV_LAYOUT.outline_initial_width,
        min_height=_NAV_LAYOUT.outline_min_height,
        initial_height=_NAV_LAYOUT.outline_initial_height,
    )
    win = ViewerWindow(
        title=title or default_title,
        on_close=_on_close,
        window_key="ModelViewer",
        extension_docks=[
            _NavDockSpec(
                dock_id="dock_model_outline", title="Outline",
                factory=lambda p: _QtW_nav.QWidget(p),
                default_area="left", **_nav_floors,
            ),
            _NavDockSpec(
                dock_id="dock_model_selection", title="Selection",
                factory=lambda p: _QtW_nav.QWidget(p),
                default_area="left", **_nav_floors,
            ),
        ],
    )
    # Stack Selection under the Outline in the left column. Done here
    # (docks already exist from the constructor) so the default
    # arrangement is set; restoreState re-applies the user's saved
    # layout on top, and the per-launch sanitize heals any degenerate
    # restored share.
    from qtpy import QtCore as _QtC_split
    win.window.splitDockWidget(
        win.extension_dock("dock_model_outline"),
        win.extension_dock("dock_model_selection"),
        _QtC_split.Qt.Vertical,
    )

    # ── Plan 04 step 4 — ActiveObjects coordinator ──────────────
    # One per viewer. Provides the ``selectionChanged`` signal that
    # future panels subscribe to; the legacy ``sel.on_changed``
    # cascade installed further below stays as the compatibility
    # path per the plan doc. The bridge into ActiveObjects is
    # registered alongside the cascade in the "Wire callbacks"
    # section so all selection observers are co-located.
    from .core._active_objects import ActiveObjects
    self._active = ActiveObjects(parent=win.window)

    # ── UI tabs (created AFTER QApplication exists) ─────────────
    # NOTE: PreferencesTab is created AFTER scene build (needs registry).
    # See "Preferences" block below build_brep_scene().

    _DIM_NAMES = {0: "points", 1: "curves", 2: "surfaces", 3: "volumes"}

    def _on_new_group():
        from qtpy import QtWidgets
        current_picks = list(sel.targets)
        # A Gmsh physical group is dimension-scoped. A mixed-dim
        # selection would be written as one PG per dimension under
        # the same name (looks duplicated, wrong for FEM export),
        # so reject it up front rather than silently splitting.
        dims = sorted({t.dim for t in current_picks})
        if len(dims) > 1:
            QtWidgets.QMessageBox.warning(
                win.window,
                "Mixed-dimension selection",
                "A physical group must contain entities of a "
                "single dimension.\n\nThe current selection spans: "
                + ", ".join(_DIM_NAMES.get(d, str(d)) for d in dims)
                + ".\n\nRefine it to one dimension and try again.",
            )
            return
        name, ok = QtWidgets.QInputDialog.getText(
            win.window, "New Physical Group",
            "Group name:",
        )
        if ok and name.strip():
            n = name.strip()
            # Stage current picks as the new group (replayable op),
            # then switch to it (loads picks from staging).
            sel.stage_group(n, current_picks)
            sel.set_active_group(n)
            outline.refresh()
            if current_picks:
                win.set_status(
                    f"Group '{n}' created with {len(current_picks)} entities"
                )
            else:
                win.set_status(f"Active group: {n} — pick entities to add")

    def _on_new_label():
        # The multi-dimensional counterpart to _on_new_group. A
        # label IS allowed to span dimensions — it is backed by one
        # ``_label:`` PG per dimension (PGs are dimension-scoped),
        # which the outline merges into one row.
        from qtpy import QtWidgets
        picks = list(sel.picks)
        if not picks:
            QtWidgets.QMessageBox.information(
                win.window, "New Label",
                "Select one or more entities first — a label "
                "groups the current selection (any mix of "
                "dimensions).",
            )
            return
        labels_api = getattr(self._parent, "labels", None)
        if labels_api is None:
            QtWidgets.QMessageBox.warning(
                win.window, "New Label",
                "This session exposes no labels API.",
            )
            return
        name, ok = QtWidgets.QInputDialog.getText(
            win.window, "New Label",
            "Label name (groups the selection across all its "
            "dimensions):",
        )
        if not (ok and name.strip()):
            return
        n = name.strip()
        by_dim: dict[int, list[int]] = {}
        for d, t in picks:
            by_dim.setdefault(int(d), []).append(int(t))
        try:
            # ``labels.add`` warns about cross-dim "ambiguous
            # lookups" when the same name spans dimensions — which
            # is precisely the intent of a multi-dim label, so
            # silence that one warning for this deliberate add.
            import warnings
            with warnings.catch_warnings():
                warnings.filterwarnings(
                    "ignore",
                    message=r".*already exists at dim=.*",
                )
                for d, tags in sorted(by_dim.items()):
                    labels_api.add(d, tags, n)
        except Exception as exc:
            QtWidgets.QMessageBox.warning(
                win.window, "New Label",
                f"Could not create label '{n}':\n{exc}",
            )
            return
        outline.refresh()
        dims_txt = ", ".join(
            _DIM_NAMES.get(d, str(d)) for d in sorted(by_dim)
        )
        win.set_status(
            f"Label '{n}' created from {len(picks)} entities "
            f"({dims_txt})"
        )

    def _on_rename_label(name: str):
        from qtpy import QtWidgets
        labels_api = getattr(self._parent, "labels", None)
        if labels_api is None:
            return
        new_name, ok = QtWidgets.QInputDialog.getText(
            win.window, "Rename Label",
            "New label name:", text=name,
        )
        if not (ok and new_name.strip()):
            return
        nn = new_name.strip()
        if nn == name:
            return
        try:
            # dim=None → rename across every dimension the label
            # spans (a label is multi-dimensional).
            labels_api.rename(name, nn)
        except Exception as exc:
            QtWidgets.QMessageBox.warning(
                win.window, "Rename Label",
                f"Could not rename label '{name}':\n{exc}",
            )
            return
        outline.refresh()
        win.set_status(f"Label '{name}' renamed to '{nn}'")

    def _on_delete_label(name: str):
        from qtpy import QtWidgets
        labels_api = getattr(self._parent, "labels", None)
        if labels_api is None:
            return
        reply = QtWidgets.QMessageBox.question(
            win.window, "Delete Label",
            f"Delete label '{name}' (all dimensions)?",
        )
        if reply != QtWidgets.QMessageBox.StandardButton.Yes:
            return
        try:
            labels_api.remove(name)        # dim=None → all dims
        except Exception as exc:
            QtWidgets.QMessageBox.warning(
                win.window, "Delete Label",
                f"Could not delete label '{name}':\n{exc}",
            )
            return
        outline.refresh()
        win.set_status(f"Deleted label: {name}")

    def _on_rename_group(old_name: str):
        from qtpy import QtWidgets
        new_name, ok = QtWidgets.QInputDialog.getText(
            win.window, "Rename Group",
            "New name:", text=old_name,
        )
        if ok and new_name.strip():
            sel.rename_group(old_name, new_name.strip())
            outline.refresh()

    def _on_delete_group(name: str):
        from qtpy import QtWidgets
        reply = QtWidgets.QMessageBox.question(
            win.window, "Delete Group",
            f"Delete physical group '{name}'?",
        )
        # Qt6 uses QMessageBox.StandardButton.Yes; Qt5 had the
        # top-level alias. Compare via the enum member to stay
        # portable across PyQt5/PySide2/PyQt6/PySide6.
        if reply == QtWidgets.QMessageBox.StandardButton.Yes:
            # ADR 0045 S3c: delete is staged + tombstoned; the gmsh PG
            # is removed at flush. The outline reads staging, so the
            # group disappears from the UI immediately.
            sel.delete_group(name)
            outline.refresh()
            win.set_status(f"Deleted group: {name}")

    def _on_group_activated(name: str):
        sel.set_active_group(name)
        # In-place active-row restyle only. A full refresh()
        # (takeChildren + rebuild) would reset scroll/expansion
        # and make rows visibly jump on every click; the
        # structure is unchanged here, only which group is active.
        outline.update_active()
        n = len(sel.picks)
        win.set_status(f"Active group: {name} ({n} entities)")

    # Filter -> pick engine + visual dim feedback. The closure references
    # plotter / registry / pick_engine which are bound later in this
    # method; safe because the callback only fires after ``win.exec()``.
    # The FilterController (ADR 0045 S2) is the single source of truth
    # for the active dimension set; the 0/1/2/3/4 keys and this panel
    # are two front-ends writing it (INV-4).
    def _apply_filter(active_dims):
        pick_engine.set_pickable_dims(set(active_dims))
        # Ghost inactive dims (still visible) AND make their actors
        # non-pickable so a vtkCellPicker ray passes THROUGH them to
        # the active dim's actor underneath — the volume-click
        # pass-through (ADR 0045 S5): with only volumes active, a
        # click on a volume's (coincident, ghosted) boundary surface
        # resolves to the volume, not the surface.
        from .overlays.pref_helpers import filter_dim_opacity
        for dim in registry.dims:
            in_active = dim in active_dims
            registry.set_dim_pickable(dim, in_active)
            actor = registry.dim_actors.get(dim)
            if actor is None:
                continue
            actor.GetProperty().SetOpacity(
                filter_dim_opacity(
                    registry, dim,
                    active=in_active,
                    fallback=self._surface_opacity,
                )
            )
        plotter.render()
        filter_tab.sync_active(active_dims)  # key→panel two-way sync
        if not active_dims:
            win.set_status("Dim filter: none")
        elif set(active_dims) == set(self._dims):
            win.set_status("Dim filter: all")
        else:
            win.set_status(
                "Dim filter: "
                + ", ".join(str(d) for d in sorted(active_dims))
            )

    self._filter = FilterController(self._dims, on_change=_apply_filter)
    filter_tab = FilterTab(
        self._dims, on_filter_changed=self._filter.set_active
    )

    # ── View tab (entity labels) ────────────────────────────────
    _label_actors: list = []
    _DIM_ABBR = {0: "P", 1: "C", 2: "S", 3: "V"}

    def _on_labels_changed(
        active_dims, font_size, use_names,
        show_parts=False, show_entity_labels=False,
    ):
        from apeGmsh.core.Labels import is_label_pg, strip_prefix
        from .ui._filter_view_tabs import quotation_text

        # Remove existing labels
        for a in _label_actors:
            try:
                plotter.remove_actor(a)
            except Exception:
                pass
        _label_actors.clear()

        for dim, show in active_dims.items():
            if not show:
                continue
            points = []
            labels = []
            for _, tag in gmsh.model.getEntities(dim=dim):
                dt = (dim, tag)
                c = registry.centroid(dt)
                if c is not None:
                    points.append(c)
                else:
                    try:
                        ctr = gmsh_bbox(dim, tag).center - registry.origin_shift
                        points.append(ctr.tolist())
                    except Exception:
                        continue
                if use_names:
                    name = None
                    for pg_dim, pg_tag in gmsh.model.getPhysicalGroups(dim):
                        try:
                            ents = gmsh.model.getEntitiesForPhysicalGroup(
                                pg_dim, pg_tag,
                            )
                            if tag in ents:
                                pg_name = gmsh.model.getPhysicalName(
                                    pg_dim, pg_tag,
                                )
                                # Skip label PGs here — they show
                                # in the dedicated entity-label
                                # overlay below.
                                if not is_label_pg(pg_name):
                                    name = pg_name
                                    break
                        except Exception:
                            pass
                    labels.append(
                        name or f"{_DIM_ABBR[dim]}{tag}"
                    )
                else:
                    labels.append(f"{_DIM_ABBR[dim]}{tag}")

            if not points:
                continue

            from .ui.theme import THEME as _THEME
            try:
                actor = plotter.add_point_labels(
                    np.array(points), labels,
                    font_size=font_size,
                    text_color=_THEME.current.text,
                    shape_color=_THEME.current.mantle,
                    shape_opacity=0.6,
                    show_points=False,
                    always_visible=True,
                    name=f"_labels_dim{dim}",
                )
                _label_actors.append(actor)
            except Exception:
                pass

        # ── Part labels (one per instance, at centroid) ─────────
        parts_reg_local = getattr(self._parent, 'parts', None)
        if show_parts and parts_reg_local is not None:
            part_points = []
            part_labels = []
            for label, inst in parts_reg_local.instances.items():
                # Use highest-dim entity centroid for placement
                placed = False
                quoted = quotation_text(label, inst.bbox)
                for d in (3, 2, 1, 0):
                    for t in inst.entities.get(d, []):
                        c = registry.centroid((d, t))
                        if c is not None:
                            part_points.append(c)
                            part_labels.append(quoted)
                            placed = True
                            break
                    if placed:
                        break
                if not placed and inst.bbox is not None:
                    bb = inst.bbox
                    part_points.append([
                        (bb[0] + bb[3]) * 0.5 - registry.origin_shift[0],
                        (bb[1] + bb[4]) * 0.5 - registry.origin_shift[1],
                        (bb[2] + bb[5]) * 0.5 - registry.origin_shift[2],
                    ])
                    part_labels.append(quoted)

            if part_points:
                try:
                    actor = plotter.add_point_labels(
                        np.array(part_points), part_labels,
                        font_size=font_size + 2,
                        text_color=_THEME.current.success,
                        shape_color=_THEME.current.base,
                        shape_opacity=0.85,
                        show_points=False,
                        always_visible=True,
                        bold=True,
                        name="_labels_parts",
                    )
                    _label_actors.append(actor)
                except Exception:
                    pass

        # ── Entity labels (Tier 1 — from g.labels) ────────────
        if show_entity_labels:
            label_points = []
            label_texts = []
            for pg_dim, pg_tag in gmsh.model.getPhysicalGroups():
                pg_name = gmsh.model.getPhysicalName(pg_dim, pg_tag)
                if not is_label_pg(pg_name):
                    continue
                display_name = strip_prefix(pg_name)
                ent_tags = gmsh.model.getEntitiesForPhysicalGroup(
                    pg_dim, pg_tag,
                )
                for tag in ent_tags:
                    dt = (pg_dim, int(tag))
                    c = registry.centroid(dt)
                    if c is not None:
                        label_points.append(c)
                    else:
                        try:
                            ctr = gmsh_bbox(pg_dim, int(tag)).center - registry.origin_shift
                            label_points.append(ctr.tolist())
                        except Exception:
                            continue
                    try:
                        bb = gmsh.model.getBoundingBox(pg_dim, int(tag))
                    except Exception:
                        bb = None
                    label_texts.append(quotation_text(display_name, bb))

            if label_points:
                try:
                    actor = plotter.add_point_labels(
                        np.array(label_points), label_texts,
                        font_size=font_size,
                        text_color=_THEME.current.warning,
                        shape_color=_THEME.current.base,
                        shape_opacity=0.75,
                        show_points=False,
                        always_visible=True,
                        italic=True,
                        name="_labels_entities",
                    )
                    _label_actors.append(actor)
                except Exception:
                    pass

        plotter.render()

    # ``tn_overlay`` is constructed later in this method (it needs the
    # registry's origin shift, only known after ``build_brep_scene``).
    # The closure resolves it lazily — safe because the callback only
    # fires after ``win.exec()``.
    def _on_geometry_probes_changed(show_tangents: bool, show_normals: bool):
        tn_overlay.set_show_tangents(show_tangents)
        tn_overlay.set_show_normals(show_normals)

    view_tab = ViewTab(
        self._dims,
        on_labels_changed=_on_labels_changed,
        on_geometry_probes_changed=_on_geometry_probes_changed,
    )

    # ── Selection tree panel ────────────────────────────────────
    def _tree_select_only(dts):
        sel.select_batch(dts, replace=True)

    def _tree_add(dts):
        sel.select_batch(dts)

    def _tree_remove(dts):
        sel.box_remove(dts)

    # Visibility callbacks — late-binding on vis_mgr (defined later
    # in this same method). Owner-fired (ADR 0056 V4): the mutators
    # fire MESH_ENTITY_VISIBILITY_CHANGED and the dispatcher
    # rebuilds + renders once — no call-site renders.
    def _tree_hide(dts):
        vis_mgr.hide_dts(dts)

    def _tree_isolate(dts):
        vis_mgr.isolate_dts(dts)

    def _tree_reveal_all():
        vis_mgr.reveal_all()

    sel_tree = SelectionTreePanel(
        on_select_only=_tree_select_only,
        on_add_to_selection=_tree_add,
        on_remove_from_selection=_tree_remove,
        on_hide=_tree_hide,
        on_isolate=_tree_isolate,
        on_reveal_all=_tree_reveal_all,
    )

    # Plan 08 follow-up — every right-side panel is now its own
    # ``QDockWidget`` tabified together by default. Users can drag
    # any panel out, dock it elsewhere, close it from the title
    # bar, and the arrangement persists via ``window_key``.
    # ``_FIRST_DOCK`` anchors the tabify chain so subsequent calls
    # land next to it instead of fanning out across dock areas.
    from .ui._dock_registry import DockSpec
    # Right-side tool group. ``_FIRST_DOCK`` anchors the tabify
    # chain so the rest land as tabs next to it. View is the
    # anchor now that the Browser is retired (Outline + Labels
    # supersede it); Selection is no longer here — it lives in the
    # left column under the Outline (see below).
    _FIRST_DOCK = "dock_model_view"

    def _add_panel(dock_id: str, title: str, widget) -> Any:
        return win.add_extension_dock(DockSpec(
            dock_id=dock_id,
            title=title,
            factory=lambda _p: widget,
            tabify_with=(
                None if dock_id == _FIRST_DOCK else _FIRST_DOCK
            ),
        ))

    _add_panel(_FIRST_DOCK, "View", view_tab.widget)
    _add_panel("dock_model_filter", "Filter", filter_tab.widget)

    plotter = win.plotter

    # ── Build scene ─────────────────────────────────────────────
    _verbose = getattr(self._parent, '_verbose', False)
    registry = build_brep_scene(
        plotter, self._dims,
        point_size=self._point_size,
        line_width=self._line_width,
        surface_opacity=self._surface_opacity,
        show_surface_edges=self._show_surface_edges,
        verbose=_verbose,
    )
    self._registry = registry

    def _compute_model_diagonal() -> float:
        try:
            return gmsh_model_bbox().diagonal or 1.0
        except Exception:
            return 1.0

    from .overlays.origin_markers_overlay import OriginMarkerOverlay
    from .ui.origin_markers_panel import OriginMarkersPanel
    from .ui.preferences_manager import PREFERENCES as _PREF
    _marker_size = _PREF.current.origin_marker_size
    origin_overlay = OriginMarkerOverlay(
        plotter,
        origin_shift=registry.origin_shift,
        model_diagonal=_compute_model_diagonal(),
        points=self._origin_markers,
        show_coords=self._origin_marker_show_coords,
        size=_marker_size,
    )
    origin_panel = OriginMarkersPanel(
        initial_points=self._origin_markers,
        initial_visible=True,
        initial_show_coords=self._origin_marker_show_coords,
        initial_size=_marker_size,
        on_visible_changed=origin_overlay.set_visible,
        on_show_coords_changed=origin_overlay.set_show_coords,
        on_marker_added=origin_overlay.add,
        on_marker_removed=origin_overlay.remove,
        on_size_changed=origin_overlay.set_size,
    )
    _add_panel("dock_model_markers", "Markers", origin_panel.widget)

    # ── Model info panel (read-only diagnostics) ──────────────
    # No longer a dock tab — surfaced via the top-level "Info"
    # menu as a standalone non-modal window (wired further down,
    # once ``win`` + the menu bar are available).
    from .ui._model_info_panel import ModelInfoPanel
    info_panel = ModelInfoPanel(parts_registry=getattr(self._parent, 'parts', None))

    # ── Section / clipping plane ────────────────────────────────
    from .overlays.clip_plane_overlay import ClipPlaneOverlay
    from .ui._clip_plane_panel import ClipPlanePanel
    clip_overlay = ClipPlaneOverlay(
        plotter, registry, origin_shift=registry.origin_shift,
    )

    def _world_bbox() -> tuple[float, float, float, float, float, float]:
        try:
            box = gmsh_model_bbox()
            return (*box.min, *box.max)
        except Exception:
            return (0.0, 0.0, 0.0, 1.0, 1.0, 1.0)

    clip_panel = ClipPlanePanel(clip_overlay, world_bbox=_world_bbox())
    _add_panel("dock_model_section", "Section", clip_panel.widget)

    # ── Measure tool (entity-centroid distance) ─────────────────
    from .overlays.measure_overlay import MeasureOverlay
    from .ui._measure_panel import MeasurePanel
    measure_overlay = MeasureOverlay(plotter, registry)

    def _push_measure_status() -> None:
        measure_panel.update_status(
            num_points=measure_overlay.num_points,
            endpoints=measure_overlay.last_endpoints,
            distance=measure_overlay.last_distance,
            delta=measure_overlay.last_delta,
        )

    def _on_measure_active(active: bool) -> None:
        # Leaving measure mode wipes any in-flight measurement so
        # the next time the user enters they start fresh.
        if not active:
            measure_overlay.reset()
        _push_measure_status()
        win.set_status(
            "Measure mode ON — click two entities" if active
            else "Measure mode off",
            3000,
        )

    def _on_measure_clear() -> None:
        measure_overlay.reset()
        _push_measure_status()

    measure_panel = MeasurePanel(
        on_active_changed=_on_measure_active,
        on_clear=_on_measure_clear,
    )
    _add_panel("dock_model_measure", "Measure", measure_panel.widget)

    # ── Tangent / normal overlay (geometry probes in View tab) ──
    from .overlays.tangent_normal_overlay import TangentNormalOverlay
    tn_overlay = TangentNormalOverlay(
        plotter,
        origin_shift=registry.origin_shift,
        model_diagonal=_compute_model_diagonal(),
        scale=_PREF.current.tangent_normal_scale,
    )

    # ── Preferences (created AFTER scene — needs registry) ─────
    from .overlays.pref_helpers import make_line_width_cb, make_opacity_cb, make_edges_cb
    from .overlays.glyph_helpers import rebuild_brep_point_glyphs

    # ColorManager constructed before the Session tab: the tab's
    # pick-color swatch initializes from this owner (ADR 0056
    # INV-1). VisibilityManager picks it up below.
    color_mgr = ColorManager(registry)

    # ── Physical Group color mode ───────────────────────────────
    import zlib
    from .core.color_mode_controller import (
        _GROUP_PALETTE_RGB, _FALLBACK_RGB as _PG_FALLBACK,
    )
    brep_to_group: dict = {}
    for _pg_dim, _pg_tag in gmsh.model.getPhysicalGroups():
        try:
            _pg_name = gmsh.model.getPhysicalName(_pg_dim, _pg_tag)
            if not _pg_name:
                continue
            for _ent_tag in gmsh.model.getEntitiesForPhysicalGroup(
                _pg_dim, _pg_tag
            ):
                _dt = (_pg_dim, int(_ent_tag))
                if _dt not in brep_to_group:
                    brep_to_group[_dt] = _pg_name
        except Exception:
            pass
    _color_mode = ["default"]

    def _pg_idle_fn(dt):
        name = brep_to_group.get(dt)
        if name is None:
            return _PG_FALLBACK
        return _GROUP_PALETTE_RGB[
            zlib.crc32(name.encode("utf-8")) % len(_GROUP_PALETTE_RGB)
        ]

    def _toggle_pg_color():
        if _color_mode[0] == "default":
            _color_mode[0] = "pg"
            color_mgr.set_idle_fn(_pg_idle_fn)
            win.set_status("Color mode: Physical Group")
        else:
            _color_mode[0] = "default"
            color_mgr.reset_idle_fn()
            win.set_status("Color mode: Default")
        color_mgr.recolor_all(
            picks=set(sel.picks),
            hidden=vis_mgr.hidden,
            hover=pick_engine.hover_entity,
        )
        plotter.render()

    def _pref_point_size(v: float):
        kw = registry._add_mesh_kwargs.get(0, {})
        kw['point_size'] = v
        registry._add_mesh_kwargs[0] = kw
        rebuild_brep_point_glyphs(plotter, registry)
        plotter.render()

    _pref_line_width = make_line_width_cb(registry, plotter)
    _pref_opacity_inner = make_opacity_cb(registry, plotter)

    def _pref_opacity(v: float):
        # Keep the owner field in sync so scene rebuilds don't
        # snap back to the constructor default. Then re-apply the
        # dim filter so ghosted (inactive) dims stay ghosted —
        # the inner callback writes every dim>=2 actor to ``v``.
        self._surface_opacity = float(v)
        _pref_opacity_inner(v)
        _apply_filter(self._filter.active)

    _pref_edges = make_edges_cb(registry, plotter)

    def _pref_pick_color(hex_str: str):
        h = hex_str.lstrip("#")
        try:
            rgb = (
                int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16),
            )
        except ValueError:
            return
        from .ui.theme import THEME as _THEME
        _THEME.update_current(pick_rgb=rgb)

    from .ui.theme import THEME
    prefs = PreferencesTab(
        point_size=self._point_size,
        line_width=self._line_width,
        surface_opacity=self._surface_opacity,
        show_surface_edges=self._show_surface_edges,
        on_point_size=_pref_point_size,
        on_line_width=_pref_line_width,
        on_opacity=_pref_opacity,
        on_edges=_pref_edges,
        # Initial swatch projects the owner's effective pick colour
        # (ADR 0056 INV-1 — the widget rebuilds from the owner).
        pick_color="#{:02x}{:02x}{:02x}".format(
            *(int(c) for c in color_mgr.pick_rgb)
        ),
        on_pick_color=_pref_pick_color,
        on_theme=lambda name: THEME.set_theme(name),
    )
    # Session tab (formerly "Preferences") — runtime tweaks that reset
    # next session. The "Global preferences…" button at the bottom opens
    # the persistent-prefs dialog.
    from qtpy import QtWidgets as _QtW
    from .ui.preferences_dialog import open_preferences_dialog
    from .ui.theme_editor_dialog import open_theme_editor
    _btn_global = _QtW.QPushButton("Global preferences…")
    _btn_global.clicked.connect(
        lambda: open_preferences_dialog(win.window)
    )
    prefs.widget.layout().addWidget(_btn_global)
    _btn_theme = _QtW.QPushButton("Theme editor…")
    _btn_theme.clicked.connect(
        lambda: open_theme_editor(win.window)
    )
    prefs.widget.layout().addWidget(_btn_theme)
    _btn_gfx = _QtW.QPushButton("Graphics colors…")
    _btn_gfx.clicked.connect(win._open_graphics_colors)
    prefs.widget.layout().addWidget(_btn_gfx)
    # Wrap in a scroll area so the (tall) Session panel never
    # forces a minimum size on the shared right-side tab group —
    # it scrolls instead of stretching its neighbours.
    _sess_scroll = _QtW.QScrollArea()
    _sess_scroll.setWidgetResizable(True)
    _sess_scroll.setFrameShape(_QtW.QFrame.NoFrame)
    _sess_scroll.setWidget(prefs.widget)
    # "Display" per ADR 0087 INV-1/INV-5 (display preferences, not
    # session state); objectName stays ``dock_model_session`` so
    # persisted layouts keep round-tripping.
    _add_panel("dock_model_session", "Display", _sess_scroll)

    # Set generous clipping range for shifted coords
    try:
        plotter.reset_camera()
        cam = plotter.renderer.GetActiveCamera()
        cam.SetClippingRange(0.01, 1e6)
    except Exception:
        pass

    # ── Core modules ────────────────────────────────────────────
    vis_mgr = VisibilityManager(registry, color_mgr, sel, plotter, verbose=_verbose)
    # ── Model dispatcher (ADR 0056 V4) ──────────────────────────
    # Same contract as the mesh viewer (V3): VisibilityManager
    # owner-fires MESH_ENTITY_VISIBILITY_CHANGED; its rebuild is
    # the dispatcher's ``entities`` pump; ONE coalesced render per
    # gesture (this also retires the double-render the model
    # viewer used to do — an on_changed render subscriber PLUS a
    # call-site render after every mutator).
    from .diagrams._dispatch import Dispatcher
    dispatcher = Dispatcher(
        self,
        pump_entities=vis_mgr.rebuild_now,
        render=lambda: plotter.render(),
    )
    self._dispatcher = dispatcher
    vis_mgr.dispatcher = dispatcher
    # Mirror the mesh viewer's attribute surface (it stores all
    # three) — verification drivers and tests reach these.
    self._win = win
    self._plotter = plotter
    self._vis_mgr = vis_mgr
    from .ui.preferences_manager import PREFERENCES as _PREF_DT
    pick_engine = PickEngine(
        plotter, registry, drag_threshold=_PREF_DT.current.drag_threshold,
    )

    # ── Left column — primary navigation ───────────────────────
    # The outline (Physical Groups / Labels / Parts, ParaView-
    # style) is the model navigator; the Browser panel it once
    # mirrored has been retired. Selection sits directly below it
    # (vertical split) so picks stay visible while you browse.
    parts_reg = getattr(self._parent, 'parts', None)
    from .ui._model_outline_tree import ModelOutlineTree

    # Outline PG/Label click → declaration target for the
    # Loads / Masses panels (captured by name + kind).
    self._decl_target = None

    def _on_outline_focus(kind, payload) -> None:
        if kind in ("group", "label"):
            self._decl_target = (kind, str(payload))

    outline = ModelOutlineTree(
        selection=sel,
        vis_mgr=vis_mgr,
        parts_registry=parts_reg,
        on_group_activated=_on_group_activated,
        on_entity_toggled=lambda dt: sel.toggle(dt),
        on_new_group=_on_new_group,
        on_new_label=_on_new_label,
        on_rename_label=_on_rename_label,
        on_delete_label=_on_delete_label,
        on_rename_group=_on_rename_group,
        on_delete_group=_on_delete_group,
        on_row_focused=_on_outline_focus,
    )
    # Swap the real trees into the placeholder nav docks registered
    # at construction (see the ViewerWindow call above). The docks +
    # their Outline-over-Selection split + persistence + per-launch
    # heal are already wired; this installs the content.
    win.set_extension_dock_widget("dock_model_outline", outline.widget)
    win.set_extension_dock_widget("dock_model_selection", sel_tree.widget)

    # ── Info menu — model diagnostics as a standalone window ────
    # Replaces the old "Info" dock tab. Lazily builds one
    # non-modal window the first time it's opened; reuses it
    # afterwards. Parented to the main window so it closes with
    # the viewer but never blocks it.
    from qtpy import QtWidgets as _QtW_info, QtCore as _QtC_info
    _model_name = getattr(self._parent, "model_name", None) or "model"
    _info_window: list[Any] = []

    def _open_model_info() -> None:
        w = _info_window[0] if _info_window else None
        if w is None:
            w = _QtW_info.QMainWindow(win.window)
            w.setWindowFlag(_QtC_info.Qt.Window, True)
            w.setWindowTitle(f"Model info — {_model_name}")
            w.setCentralWidget(info_panel.widget)
            w.resize(420, 620)
            _info_window.append(w)
        info_panel.refresh()
        w.show()
        w.raise_()
        w.activateWindow()

    # View → Model info… — the one-item "Info" menu retired into
    # View per ADR 0087 Appendix B (one-item menus are banned).
    win.add_view_menu_action("Model info…", _open_model_info)

    # ── View → Navigation / Camera / Theme submenus (ADR 0087) ──
    win.install_navigation_menu()
    win.install_camera_menu()
    win.install_theme_menu()

    # ── File menu — CAD geometry import / export ────────────────
    # Import is additive: g.model.io.load_step / load_dxf add to
    # the current model, then the scene rebuilds. Export writes
    # the current model to STEP. Errors surface in a dialog (same
    # as the Boolean / Transform panels). Inserted leftmost so it
    # reads as a conventional File menu.
    from qtpy import QtWidgets as _QtW_file

    def _import_step() -> None:
        path, _f = _QtW_file.QFileDialog.getOpenFileName(
            win.window, "Import STEP", "",
            "STEP (*.step *.stp);;All files (*)",
        )
        if not path:
            return
        try:
            imported = self._model.io.load_step(path)
        except Exception as exc:
            _QtW_file.QMessageBox.warning(
                win.window, "Import STEP", str(exc)
            )
            return
        n = sum(len(v) for v in (imported or {}).values())
        _rebuild_scene()
        win.set_status(
            f"Imported STEP — {n} entit"
            f"{'y' if n == 1 else 'ies'}"
        )

    def _import_dxf() -> None:
        path, _f = _QtW_file.QFileDialog.getOpenFileName(
            win.window, "Import DXF", "",
            "DXF (*.dxf);;All files (*)",
        )
        if not path:
            return
        try:
            self._model.io.load_dxf(path)
        except Exception as exc:
            _QtW_file.QMessageBox.warning(
                win.window, "Import DXF", str(exc)
            )
            return
        _rebuild_scene()
        win.set_status("Imported DXF")

    def _export_step() -> None:
        path, _f = _QtW_file.QFileDialog.getSaveFileName(
            win.window, "Export STEP", "",
            "STEP (*.step);;All files (*)",
        )
        if not path:
            return
        try:
            self._model.io.save_step(path)
        except Exception as exc:
            _QtW_file.QMessageBox.warning(
                win.window, "Export STEP", str(exc)
            )
            return
        win.set_status("Exported STEP")

    _file_menu = _QtW_file.QMenu("File", win.window)
    _file_menu.addAction("Import STEP…").triggered.connect(
        _import_step
    )
    _file_menu.addAction("Import DXF…").triggered.connect(
        _import_dxf
    )
    _file_menu.addSeparator()
    _file_menu.addAction("Export STEP…").triggered.connect(
        _export_step
    )
    # Global preferences (bottom of File, after a separator — ADR
    # 0087 Appendix B: no one-item Edit menu just to host it).
    from .ui.preferences_dialog import open_preferences_dialog as _open_prefs
    _file_menu.addSeparator()
    _file_menu.addAction("Preferences…").triggered.connect(
        lambda _checked=False: _open_prefs(win.window)
    )
    _mb = win.window.menuBar()
    _mb_acts = _mb.actions()
    if _mb_acts:
        _mb.insertMenu(_mb_acts[0], _file_menu)   # File leftmost
    else:
        _mb.addMenu(_file_menu)

    # ── Loads / Masses declaration panels (pre-mesh) ────────────
    # Declared against the outline's selected PG / Label. The
    # library call happens here (pattern-wrapped for loads).
    # model.viewer has no mesh, so no arrows — the declarations
    # render later in g.mesh.viewer(fem=fem). Target dim is
    # validated like PG creation. No _rebuild_scene (no geometry
    # change).
    from .ui._loads_panel import LoadsPanel, LOAD_TYPES
    from .ui._masses_panel import MassesPanel, MASS_TYPES
    from qtpy import QtWidgets as _QtW_decl
    _LOAD_DIM = dict(LOAD_TYPES)
    _MASS_DIM = dict(MASS_TYPES)

    def _decl_target():
        return self._decl_target

    def _target_dims(kind, name):
        from apeGmsh.core.Labels import add_prefix
        pgname = add_prefix(name) if kind == "label" else name
        dims = set()
        for d, t in gmsh.model.getPhysicalGroups():
            try:
                if gmsh.model.getPhysicalName(d, t) == pgname:
                    dims.add(int(d))
            except Exception:
                pass
        return dims

    def _kw_for(kind, name, params):
        kw = {"label": name} if kind == "label" else {"pg": name}
        kw.update(params)
        return kw

    _rec_view = lambda r, with_pattern: _decl_record_view(  # noqa: E731
        r, with_pattern=with_pattern
    )

    def _loads_records():
        recs = getattr(self._parent.loads, "load_defs", []) or []
        return [_rec_view(r, True) for r in recs]

    def _loads_remove(key):
        recs = getattr(self._parent.loads, "load_defs", None)
        if recs is not None:
            recs[:] = [r for r in recs if id(r) != key]
        _loads_panel.refresh_list()

    def _loads_apply(load_type, pattern, target, params):
        kind, name = target
        need = _LOAD_DIM.get(load_type)
        dims = _target_dims(kind, name)
        if need is not None and dims and need not in dims:
            _QtW_decl.QMessageBox.warning(
                win.window, f"Loads: {load_type}",
                f"{load_type} needs a "
                f"{_DIM_NAMES.get(need, need)} target; '{name}' is "
                + ", ".join(
                    _DIM_NAMES.get(x, str(x)) for x in sorted(dims)
                ) + ".",
            )
            _loads_panel.set_hint(f"{load_type}: wrong target dim.")
            return
        try:
            with self._parent.loads.case(pattern):
                getattr(self._parent.loads, load_type)(
                    **_kw_for(kind, name, params)
                )
        except Exception as exc:
            _QtW_decl.QMessageBox.warning(
                win.window, f"Loads: {load_type}", str(exc)
            )
            _loads_panel.set_hint(f"{load_type} failed: {exc}")
            return
        _loads_panel.refresh_patterns()
        _loads_panel.refresh_list()
        _loads_panel.set_hint(
            f"Declared {load_type} on {name} "
            f"(pattern '{pattern}')."
        )
        win.set_status(f"Load declared: {load_type}{name}")

    _loads_panel = LoadsPanel(
        get_target=_decl_target,
        get_patterns=lambda: list(
            getattr(self._parent.loads, "patterns", lambda: [])()
        ),
        on_apply=_loads_apply,
        on_remove=_loads_remove,
        list_records=_loads_records,
    )

    def _masses_records():
        recs = getattr(self._parent.masses, "mass_defs", []) or []
        return [_rec_view(r, False) for r in recs]

    def _masses_remove(key):
        recs = getattr(self._parent.masses, "mass_defs", None)
        if recs is not None:
            recs[:] = [r for r in recs if id(r) != key]
        _masses_panel.refresh_list()

    def _masses_apply(mass_type, target, params):
        kind, name = target
        need = _MASS_DIM.get(mass_type)
        dims = _target_dims(kind, name)
        if need is not None and dims and need not in dims:
            _QtW_decl.QMessageBox.warning(
                win.window, f"Masses: {mass_type}",
                f"{mass_type} mass needs a "
                f"{_DIM_NAMES.get(need, need)} target; '{name}' is "
                + ", ".join(
                    _DIM_NAMES.get(x, str(x)) for x in sorted(dims)
                ) + ".",
            )
            _masses_panel.set_hint(f"{mass_type}: wrong target dim.")
            return
        try:
            getattr(self._parent.masses, mass_type)(
                **_kw_for(kind, name, params)
            )
        except Exception as exc:
            _QtW_decl.QMessageBox.warning(
                win.window, f"Masses: {mass_type}", str(exc)
            )
            _masses_panel.set_hint(f"{mass_type} failed: {exc}")
            return
        _masses_panel.refresh_list()
        _masses_panel.set_hint(
            f"Declared {mass_type} mass on {name}."
        )
        win.set_status(f"Mass declared: {mass_type}{name}")

    _masses_panel = MassesPanel(
        get_target=_decl_target,
        on_apply=_masses_apply,
        on_remove=_masses_remove,
        list_records=_masses_records,
    )

    # Wrap in scroll areas so the wide-range vec3 spin boxes never
    # force their (~1000px) minimum width onto the shared right-side
    # tab group — same guard the Session panel uses for its height.
    def _scrollable(w):
        sc = _QtW.QScrollArea()
        sc.setWidgetResizable(True)
        sc.setFrameShape(_QtW.QFrame.NoFrame)
        sc.setWidget(w)
        return sc

    _add_panel(
        "dock_model_loads", "Loads", _scrollable(_loads_panel.widget)
    )
    _add_panel(
        "dock_model_masses", "Masses",
        _scrollable(_masses_panel.widget),
    )

    # Scene rebuild after any geometry mutation (parts fuse,
    # boolean ops, transforms). Hoisted to show() scope so it
    # exists even without a parts registry.
    def _rebuild_scene():
        """Tear down VTK actors and rebuild from current Gmsh state.

        Mutates ``registry`` in-place so all closures over it
        (color_mgr, vis_mgr, pick_engine) keep working.
        """
        # Save camera state
        cam = plotter.renderer.GetActiveCamera()
        cam_pos = cam.GetPosition()
        cam_fp = cam.GetFocalPoint()
        cam_up = cam.GetViewUp()
        cam_clip = cam.GetClippingRange()

        # Remove stale label actors — positions may be wrong after rebuild.
        for a in list(_label_actors):
            try:
                plotter.remove_actor(a)
            except Exception:
                pass
        _label_actors.clear()

        # Remove old actors
        for actor in list(registry.dim_actors.values()):
            try:
                plotter.remove_actor(actor)
            except Exception:
                pass

        # Silhouettes are separate actors that ``remove_actor(fill)``
        # does NOT take down (same pyvista quirk the visibility
        # rebuild handles explicitly). Without this the pre-transform
        # outline lingers as a ghost while the fresh geometry moves.
        for sil in list(registry.dim_silhouette_actors.values()):
            try:
                plotter.remove_actor(sil)
            except Exception:
                pass

        # Build fresh scene
        fresh = build_brep_scene(
            plotter, self._dims,
            point_size=self._point_size,
            line_width=self._line_width,
            surface_opacity=self._surface_opacity,
            show_surface_edges=self._show_surface_edges,
            verbose=_verbose,
        )

        # Mutate existing registry in place — preserves closures
        for slot in registry.__slots__:
            setattr(registry, slot, getattr(fresh, slot))

        # Re-sync origin markers with the fresh registry's shift
        origin_overlay.set_origin_shift(registry.origin_shift)
        tn_overlay.set_model_diagonal(_compute_model_diagonal())
        tn_overlay.set_origin_shift(registry.origin_shift)

        # Clear stale selection / active group
        sel.clear()

        # Refresh UI panels
        if parts_tree is not None:
            parts_tree.refresh()
        outline.refresh()
        sel_tree.update(sel.picks)
        info_panel.refresh()

        # Re-bind the clip plane to the fresh mappers + new bbox
        clip_overlay.set_origin_shift(registry.origin_shift)
        clip_overlay.rebind()
        clip_panel.refresh_bbox(_world_bbox())

        # Stored centroids are stale after a rebuild
        measure_overlay.reset()
        _push_measure_status()

        # Restore camera
        cam.SetPosition(*cam_pos)
        cam.SetFocalPoint(*cam_fp)
        cam.SetViewUp(*cam_up)
        cam.SetClippingRange(*cam_clip)
        # Fresh actors come in at the live slider opacity; re-ghost
        # whatever the pick filter currently has inactive.
        _apply_filter(self._filter.active)
        plotter.render()

    # Exposed for external callers that need to force a rebuild
    # after mutating Gmsh state out-of-band (ADR 0095 S6a: studio
    # host refresh calls this after a successful script replay).
    self._rebuild_scene = _rebuild_scene

    parts_tree = None
    if parts_reg is not None:
        def _parts_select_only(dts):
            sel.select_batch(dts, replace=True)

        def _parts_add(dts):
            sel.select_batch(dts)

        def _parts_remove(dts):
            sel.box_remove(dts)

        def _parts_isolate(dts):
            sel.select_batch(dts, replace=True)
            vis_mgr.isolate()

        def _parts_hide(dts):
            sel.select_batch(dts, replace=True)
            vis_mgr.hide()

        def _parts_new(label, picks):
            from qtpy.QtWidgets import QMessageBox
            try:
                parts_reg.register(label, picks)
            except ValueError as e:
                QMessageBox.warning(win.window, "Ownership conflict", str(e))
                return
            parts_tree.refresh()

        def _parts_rename(old_label, new_label):
            from qtpy.QtWidgets import QMessageBox
            try:
                parts_reg.rename(old_label, new_label)
            except (KeyError, ValueError) as e:
                QMessageBox.warning(win.window, "Rename failed", str(e))
                return
            parts_tree.refresh()

        def _parts_delete(label):
            parts_reg.delete(label)
            parts_tree.refresh()

        def _parts_fuse(labels, new_label):
            from qtpy.QtWidgets import QMessageBox
            try:
                parts_reg.fuse_group(labels, label=new_label)
            except (ValueError, RuntimeError) as e:
                QMessageBox.warning(win.window, "Fuse failed", str(e))
                return
            _rebuild_scene()

        parts_tree = PartsTreePanel(
            parts_reg, registry,
            on_select_only=_parts_select_only,
            on_add_to_selection=_parts_add,
            on_remove_from_selection=_parts_remove,
            on_isolate=_parts_isolate,
            on_hide=_parts_hide,
            on_new_part=_parts_new,
            on_rename_part=_parts_rename,
            on_delete_part=_parts_delete,
            on_fuse_parts=_parts_fuse,
            get_current_picks=lambda: sel.picks,
        )
        # Insert after Browser tab (position 1)
        win._tab_widget.insertTab(1, parts_tree.widget, "Parts")

    # ── Wire callbacks ──────────────────────────────────────────

    # Pick -> selection (or measure overlay when measure mode is on)
    from .core.pick_tiebreak import coincident_stack

    def _on_pick(dt: DimTag, ctrl: bool):
        if measure_panel.is_active():
            # Measure wants the literal entity hit, not the volume.
            measure_overlay.add_entity(dt)
            _push_measure_status()
            return
        # ADR 0045 S5-tiebreak: a boundary click is coincident with its
        # owning volume. Select the highest active dim (the volume) so a
        # click on a solid's face picks the solid, not the face. Degrades
        # to the hit entity when there is no active owning volume.
        stack = coincident_stack(
            dt, self._filter.active, registry.volumes_of_face,
        )
        chosen = stack[0] if stack else dt
        if ctrl:
            sel.unpick(chosen)
        else:
            sel.toggle(chosen)

    pick_engine.on_pick = _on_pick
    pick_engine.set_hidden_check(vis_mgr.is_hidden)

    # Hover -> color
    _prev_hover: list[DimTag | None] = [None]

    def _on_hover(dt: DimTag | None):
        old = _prev_hover[0]
        _prev_hover[0] = dt
        if old is not None and old != dt:
            is_picked = old in sel.picks
            color_mgr.set_entity_state(old, picked=is_picked)
        if dt is not None:
            is_picked = dt in sel.picks
            if not is_picked:
                color_mgr.set_entity_state(dt, hovered=True)
        plotter.render()

    pick_engine.on_hover = _on_hover

    # Selection changed -> batch recolor + refresh UI
    def _on_sel_changed():
        color_mgr.recolor_all(
            picks=set(sel.picks),
            hidden=vis_mgr.hidden,
            hover=pick_engine.hover_entity,
        )
        plotter.render()
        n = len(sel.picks)
        grp = sel.active_group or "none"
        win.set_status(f"{n} picked | group: {grp}")

    sel.on_changed.append(_on_sel_changed)
    if self._on_selection_changed is not None:
        def _studio_sel():
            self._on_selection_changed(sel)
        sel.on_changed.append(_studio_sel)
        _studio_sel()
    # Repaint idle colors when the theme palette changes
    _cb_theme_sel = lambda _p: _on_sel_changed()
    win.on_theme_changed(_cb_theme_sel)
    _cb_theme_tn = lambda _p: tn_overlay.refresh_theme()
    win.on_theme_changed(_cb_theme_tn)
    _cb_theme_origin = lambda _p: origin_overlay.refresh_theme()
    win.on_theme_changed(_cb_theme_origin)
    _cb_theme_measure = lambda _p: measure_overlay.refresh_theme()
    win.on_theme_changed(_cb_theme_measure)
    _cb_sel_tree = lambda: sel_tree.update(sel.picks)
    sel.on_changed.append(_cb_sel_tree)
    _cb_outline = lambda: outline.update_active()
    sel.on_changed.append(_cb_outline)
    if parts_tree is not None:
        _cb_parts_tree = (
            lambda: parts_tree.highlight_part_for_entity(sel.picks[-1])
            if sel.picks else None
        )
        sel.on_changed.append(_cb_parts_tree)
    else:
        _cb_parts_tree = None
    # ADR 0045 S3c-2: the active group's members are auto-materialised
    # into staging by the log reducer, so no per-pick commit is needed
    # (the old on_changed -> commit_active_group hook is gone).
    # Plan 04 step 4 — selection bridge into ActiveObjects.
    # Same pattern as mesh.viewer: emit a fresh tuple of picks on
    # every mutation so ``ActiveObjects``' identity short-circuit
    # doesn't suppress in-place changes. Subscribers reach for
    # ``viewer._active.selection`` (a tuple snapshot) or, for
    # richer state, hold a viewer reference and inspect
    # ``viewer._selection_state``.
    _active_ref = self._active
    _cb_active = lambda: _active_ref.set_selection(tuple(sel.picks))
    sel.on_changed.append(_cb_active)

    # (No render subscriber on vis_mgr.on_changed — the dispatcher
    # renders once per MESH_ENTITY_VISIBILITY_CHANGED fire,
    # ADR 0056 V4.)

    # Box select
    def _on_box(dts: list[DimTag], ctrl: bool):
        if ctrl:
            n = sel.box_remove(dts)
            verb = "removed"
        else:
            n = sel.box_add(dts)
            verb = "added"
        if n:
            noun = "entity" if n == 1 else "entities"
            win.set_status(f"Box select: {verb} {n} {noun}", 2000)
        else:
            win.set_status("Box select: 0 entities", 2000)

    pick_engine.on_box_select = _on_box

    # ── Boolean / Transform panels (live OCC editing) ───────────
    # Pure-UI panels; these callbacks own the library call +
    # _rebuild_scene (mirrors _parts_fuse). The selection feeds
    # operands; OCC renumbers after each op, so captured operands
    # are dropped and the rebuild clears the selection.
    import math as _math
    from .ui._boolean_panel import BooleanPanel
    from .ui._transform_panel import TransformPanel

    def _on_boolean(op, objects, tools, opts):
        from qtpy import QtWidgets
        if not objects:
            _boolean_panel.set_hint(
                "Set the Objects slot from a selection first."
            )
            return
        if op in ("fuse", "cut", "intersect") and not tools:
            _boolean_panel.set_hint(
                f"{op} needs both Objects and Tools."
            )
            return
        bx = self._model.boolean
        try:
            if op == "fragment":
                res = bx.fragment(
                    objects, tools,
                    remove_object=opts["remove_object"],
                    remove_tool=opts["remove_tool"],
                    cleanup_free=opts["cleanup_free"],
                )
            else:
                kw = dict(
                    remove_object=opts["remove_object"],
                    remove_tool=opts["remove_tool"],
                )
                if opts["label"]:
                    kw["label"] = opts["label"]
                res = getattr(bx, op)(objects, tools, **kw)
        except Exception as exc:
            QtWidgets.QMessageBox.warning(
                win.window, f"Boolean: {op}", str(exc)
            )
            _boolean_panel.set_hint(f"{op} failed: {exc}")
            return
        _boolean_panel.clear_operands()
        _rebuild_scene()
        n = len(res) if res else 0
        _boolean_panel.set_hint(f"{op} OK → {n} result(s)")
        win.set_status(f"Boolean {op}: {n} result(s)")

    def _on_transform(op, params, duplicate):
        from qtpy import QtWidgets
        tags = list(sel.picks)
        tx = self._model.transforms
        geo = self._model.geometry
        if op != "thru_sections" and not tags:
            _transform_panel.set_hint("Select entities first.")
            return
        try:
            if op in ("translate", "rotate", "scale", "mirror"):
                if duplicate:
                    dims = {d for d, _ in tags}
                    if len(dims) != 1:
                        _transform_panel.set_hint(
                            "'Keep original' needs a single-"
                            "dimension selection."
                        )
                        return
                    dim0 = dims.pop()
                    target = [(dim0, t) for t in tx.copy(tags)]
                else:
                    target = tags
                if op == "translate":
                    tx.translate(target, params["dx"],
                                 params["dy"], params["dz"])
                elif op == "rotate":
                    tx.rotate(
                        target, _math.radians(params["angle"]),
                        ax=params["ax"], ay=params["ay"],
                        az=params["az"], cx=params["cx"],
                        cy=params["cy"], cz=params["cz"],
                    )
                elif op == "scale":
                    tx.scale(
                        target, params["sx"], params["sy"],
                        params["sz"], cx=params["cx"],
                        cy=params["cy"], cz=params["cz"],
                    )
                else:  # mirror
                    tx.mirror(target, params["a"], params["b"],
                              params["c"], params["d"])
            elif op == "copy":
                tx.copy(tags)
            elif op == "extrude":
                ne = [params["layers"]] if params["layers"] else None
                tx.extrude(tags, params["dx"], params["dy"],
                           params["dz"], num_elements=ne,
                           recombine=params["recombine"])
            elif op == "revolve":
                ne = [params["layers"]] if params["layers"] else None
                tx.revolve(
                    tags, _math.radians(params["angle"]),
                    x=params["x"], y=params["y"], z=params["z"],
                    ax=params["ax"], ay=params["ay"],
                    az=params["az"], num_elements=ne,
                    recombine=params["recombine"],
                )
            elif op == "sweep":
                pc = params.get("path_curves") or []
                if not pc:
                    _transform_panel.set_hint(
                        "Set the sweep path from selected curves."
                    )
                    return
                wire = geo.add_wire(pc)
                tx.sweep(tags, wire, trihedron=params["trihedron"])
            elif op == "thru_sections":
                secs = params.get("sections") or []
                if len(secs) < 2:
                    _transform_panel.set_hint(
                        "Add at least 2 sections."
                    )
                    return
                wires = [geo.add_wire(c) for c in secs]
                tx.thru_sections(
                    wires, make_solid=params["make_solid"],
                    make_ruled=params["make_ruled"],
                )
        except Exception as exc:
            QtWidgets.QMessageBox.warning(
                win.window, f"Transform: {op}", str(exc)
            )
            _transform_panel.set_hint(f"{op} failed: {exc}")
            return
        _transform_panel.reset_captures()
        _rebuild_scene()
        _transform_panel.set_hint(f"{op} OK")
        win.set_status(f"Transform {op} applied")

    _boolean_panel = BooleanPanel(
        get_selection=lambda: list(sel.picks),
        on_apply=_on_boolean,
    )
    _transform_panel = TransformPanel(
        get_selection=lambda: list(sel.picks),
        on_apply=_on_transform,
    )
    _add_panel("dock_model_boolean", "Boolean", _boolean_panel.widget)
    _add_panel(
        "dock_model_transform", "Transform", _transform_panel.widget
    )

    # ── Navigation ──────────────────────────────────────────────
    install_navigation(
        plotter,
        get_orbit_pivot=lambda: sel.centroid(registry),
    )

    # ── Motion LOD ──────────────────────────────────────────────
    # The per-dim silhouette actors are ``vtkPolyDataSilhouette`` —
    # view-dependent, so they re-execute every frame the camera
    # moves (the dominant per-orbit cost on a complex CAD part,
    # on top of what the navigation bounds-cache already removes).
    # Hide them during any camera gesture and restore ~120 ms
    # after it settles — same interactive-LOD trick mesh.viewer
    # uses for its node cloud. The lambda is re-evaluated per
    # gesture so it always targets the live silhouette actors
    # (they're rebuilt by the visibility hide/show path).
    from .core.motion_lod import MotionLOD
    self._motion_lod = MotionLOD(
        plotter,
        lambda: list(registry.dim_silhouette_actors.values()),
    )
    self._motion_lod.install()

    # ── Install pick engine ─────────────────────────────────────
    pick_engine.install()

    # ── Visibility action helpers (shared between toolbar + keys) ──
    # Owner-fired (ADR 0056 V4) — the dispatcher renders.
    def _act_hide() -> None:
        vis_mgr.hide()

    def _act_isolate() -> None:
        vis_mgr.isolate()

    def _act_reveal_all() -> None:
        vis_mgr.reveal_all()

    # ── Toolbar buttons for visibility ──────────────────────────
    win.add_toolbar_separator()
    win.add_toolbar_button(
        "Hide selected (H)", "", _act_hide, icon="eye_off",
    )
    win.add_toolbar_button(
        "Isolate selected (I)", "", _act_isolate, icon="isolate",
    )
    win.add_toolbar_button(
        "Reveal all (R)", "", _act_reveal_all, icon="reveal",
    )
    if brep_to_group:
        win.add_toolbar_separator()
        win.add_toolbar_button(
            "Color by physical group", "", _toggle_pg_color,
            icon="palette",
        )

    # ── Keybindings ─────────────────────────────────────────────
    # VTK-level (only when 3D viewport has focus)
    plotter.add_key_event("h", _act_hide)
    plotter.add_key_event("i", _act_isolate)
    plotter.add_key_event("r", _act_reveal_all)

    # Undo / redo. ADR 0045 S3c-2: group activate/create/rename/delete
    # are replayable, so undo/redo can change the active group + the
    # group tree — rebuild the outline (not just restyle) after each.
    def _undo():
        if sel.undo():
            outline.refresh()

    def _redo():
        if sel.redo():
            outline.refresh()

    plotter.add_key_event("u", _undo)
    plotter.add_key_event("y", _redo)

    # Dim filters: 0=points, 1=curves, 2=surfaces, 3=volumes.
    # Ratified multi-select semantics (ADR 0045): a bare key TOGGLES
    # that dim in/out of the active set; 4 = all.
    # ApplicationShortcut: VTK's QtInteractor swallows plotter
    # add_key_event digit keys (same law as ResultsViewer Esc).
    for key, dim in [("0", 0), ("1", 1), ("2", 2), ("3", 3)]:
        win.add_shortcut(
            key, lambda d=dim: self._filter.toggle(d), application=True,
        )
    win.add_shortcut(
        "4", lambda: self._filter.select_all(), application=True,
    )

    # Window-level (work regardless of focus / mouse position)
    win.add_shortcut("Escape", lambda: sel.clear())
    win.add_shortcut("Q", lambda: win.window.close())

    # ── Help → Shortcuts (top menu) ─────────────────────────────
    from .ui._shortcuts_help import add_help_shortcuts_menu
    add_help_shortcuts_menu(
        win.window,
        entries=[
            ("LMB", "Pick BRep entity"),
            ("0 / 1 / 2 / 3", "Toggle dim filter — point / curve / surface / volume"),
            ("4", "Show all dims"),
            ("H / I / R", "Hide / isolate / reveal all"),
            ("U / Y", "Undo / redo"),
            ("Shift+LMB drag", "Turntable (yaw-only around up axis)"),
            ("Shift+MMB drag", "Orbit (yaw + pitch, no-roll)"),
            ("MMB / RMB drag", "Pan"),
            ("Scroll", "Zoom (focal point fixed)"),
            ("Esc", "Deselect"),
            ("Q", "Close window"),
        ],
    )

    # ── Pre-load group if specified ─────────────────────────────
    if self._physical_group is not None and sel.picks:
        _on_sel_changed()

    if self._annotate:
        view_tab.apply_quotations()

    # ── Run ─────────────────────────────────────────────────────
    win.exec()
    return self

to_physical

to_physical(name: str | None = None) -> int | None

Write the current picks as a Gmsh physical group.

Source code in src/apeGmsh/viewers/model_viewer.py
def to_physical(self, name: str | None = None) -> int | None:
    """Write the current picks as a Gmsh physical group."""
    if self._selection_state is None:
        return None
    sel = self._selection_state
    group_name = name or self._physical_group
    if not group_name:
        return None
    sel.apply_group(group_name)
    return sel.flush_to_gmsh()

MeshViewer — g.mesh.viewer()

apeGmsh.viewers.mesh_viewer.MeshViewer

MeshViewer(parent: '_SessionBase', *, dims: list[int] | None = None, point_size: float | None = None, line_width: float | None = None, surface_opacity: float | None = None, show_surface_edges: bool | None = None, origin_markers: list[tuple[float, float, float]] | None = None, origin_marker_show_coords: bool | None = None, view: 'ViewerData | None' = None, fast: bool = True, on_selection_changed: Callable[['SelectionState'], None] | None = None, **kwargs: Any)

Interactive mesh viewer with element/node picking.

Displays mesh elements and nodes with optional load, constraint, and mass overlays. Overlay data comes from a resolved :class:apeGmsh.viewers.data.ViewerData snapshot — either passed explicitly or auto-resolved from the session at show time.

Parameters

parent : _SessionBase The apeGmsh session. dims : list[int], optional Which mesh dimensions to show (default: [1, 2, 3]). point_size, line_width, surface_opacity, show_surface_edges Visual properties. view : ViewerData, optional Pre-resolved structural snapshot. If not provided, the viewer calls get_fem_data() automatically when the window opens and wraps the resulting FEMData. Phase 8.7 commit 6 renamed this kwarg from fem to view. fast : bool Ignored (always fast). Kept for backward compatibility. on_selection_changed : callable, optional callback(SelectionState) fired on every BREP pick change (ADR 0095 studio host). Dispatcher-legal owner mutator.

Source code in src/apeGmsh/viewers/mesh_viewer.py
def __init__(
    self,
    parent: "_SessionBase",
    *,
    dims: list[int] | None = None,
    point_size: float | None = None,
    line_width: float | None = None,
    surface_opacity: float | None = None,
    show_surface_edges: bool | None = None,
    origin_markers: list[tuple[float, float, float]] | None = None,
    origin_marker_show_coords: bool | None = None,
    view: "ViewerData | None" = None,
    fast: bool = True,
    on_selection_changed: Callable[["SelectionState"], None] | None = None,
    **kwargs: Any,
) -> None:
    from .ui.preferences_manager import PREFERENCES
    p = PREFERENCES.current

    self._parent = parent
    self._dims = dims if dims is not None else [1, 2, 3]

    # Mesh viewer keeps its own pref-sourced visual defaults. Explicit
    # kwarg still wins; falling back to the user's persisted preference
    # otherwise. Historic hard-coded fallbacks (6.0/3.0/1.0/True) match
    # ``Preferences``'s ``node_marker_size``/``line_width`` defaults.
    self._point_size = (
        point_size if point_size is not None else p.node_marker_size
    )
    self._line_width = (
        line_width if line_width is not None else p.mesh_line_width
    )
    self._surface_opacity = (
        surface_opacity if surface_opacity is not None
        else p.mesh_surface_opacity
    )
    self._show_surface_edges = (
        show_surface_edges if show_surface_edges is not None
        else p.mesh_show_surface_edges
    )

    # Origin marker overlay. User preference controls whether the
    # default is ``[(0,0,0)]`` or ``[]``; explicit kwarg wins.
    if origin_markers is not None:
        self._origin_markers: list[tuple[float, float, float]] = list(origin_markers)
    elif p.origin_marker_include_world_origin:
        self._origin_markers = [(0.0, 0.0, 0.0)]
    else:
        self._origin_markers = []
    self._origin_marker_show_coords = (
        origin_marker_show_coords if origin_marker_show_coords is not None
        else p.origin_marker_show_coords
    )
    self._view: "ViewerData | None" = view
    # ADR 0095 S2: host publishes a SelectionEnvelope on pick.
    self._on_selection_changed = on_selection_changed

    # Populated during show()
    self._selection_state: "SelectionState | None" = None
    self._scene_data: "MeshSceneData | None" = None

    # Runtime state (populated in show()) — pre-declared for clarity
    self._plotter: Any = None
    self._win: Any = None
    self._scene: "MeshSceneData | None" = None
    self._registry: "EntityRegistry | None" = None
    self._sel: "SelectionState | None" = None
    self._color_mgr: "ColorManager | None" = None
    self._vis_mgr: "VisibilityManager | None" = None
    self._pick_engine: "PickEngine | None" = None
    self._color_mode_ctrl: "ColorModeController | None" = None
    self._explode_ctrl: Any = None
    # Latest browser hide-set received while exploded (can't apply during
    # explosion — actor ids conflict). Replayed to the VisibilityManager
    # when explosion ends so the browser checkboxes don't silently desync.
    self._pending_browser_hidden: Any = None
    self._info_tab: "MeshInfoTab | None" = None
    self._mesh_tn_overlay: "MeshTangentNormalOverlay | None" = None

    # UI tabs (resolved after construction)
    self._display_tab: Any = None
    self._loads_tab: Any = None
    self._mass_tab: Any = None
    self._constraints_tab: Any = None

    # Mutable per-show state buckets
    self._label_actors: list = []
    self._load_actors: list = []
    self._mass_actors: list = []
    self._constraint_actors: list = []
    self._boundary_node_actors: list = []
    # Overlay glyph scales are OWNED by the OverlayVisibilityModel
    # (ADR 0056 V3) — read via self._overlay_model.scale(key).
    self._moment_template: Any = None
    self._pick_mode: list[str] = ["brep"]   # "brep", "element", "node"
    # ADR 0045 S3b: FE element/node picks live in a dedicated
    # SelectionState as MESH_TOPO targets (nodes dim=0, elements
    # dim=element-topo-dim), giving them undo/redo on the unified
    # target contract. Kept separate from ``_sel`` (BREP DimTags) so
    # the BREP ``.picks`` shim never sees a non-BREP target.
    self._fe_sel: "SelectionState | None" = None
    self._prev_hover: list[DimTag | None] = [None]
    self._hover_label: Any = None

    # Plan 04 step 3 — per-viewer ActiveObjects coordinator.
    # Populated by ``show()`` once a QApplication exists. Same
    # design as ``ResultsViewer._active``: a single source of
    # truth for "what is currently selected / which pick mode" so
    # panels subscribe instead of wiring direct callbacks.
    self._active: Any = None
    # Subscription handle for the SelectionState bridge; cleared
    # in ``_on_close``-equivalent paths.
    self._sel_bridge_unsub: Any = None

show

show(*, title: str | None = None, maximized: bool = True)

Open the viewer window, block until closed.

Source code in src/apeGmsh/viewers/mesh_viewer.py
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
def show(self, *, title: str | None = None, maximized: bool = True):
    """Open the viewer window, block until closed."""
    from .core.navigation import install_navigation
    from .core.color_manager import ColorManager
    from .core.color_mode_controller import ColorModeController
    from .core.filter_controller import FilterController
    from .core.pick_engine import PickEngine
    from .core.visibility import VisibilityManager
    from .core.selection import SelectionState
    from .scene.mesh_scene import build_mesh_scene
    from .ui.viewer_window import ViewerWindow
    from .ui.preferences import PreferencesTab
    from .ui.mesh_tabs import MeshInfoTab, DisplayTab, MeshFilterTab
    from .ui.preferences_manager import PREFERENCES as _PREF
    from .ui.theme import THEME

    gmsh.model.occ.synchronize()

    self._dims = self._auto_filter_dims(self._dims)

    # ── Selection state ─────────────────────────────────────────
    sel = SelectionState()
    self._selection_state = sel
    self._sel = sel
    # FE-topology pick set (elements + nodes), ADR 0045 S3b.
    fe_sel = SelectionState()
    self._fe_sel = fe_sel
    fe_sel.on_changed.append(self._refresh_fe_status)

    # ── Window (creates QApplication) ───────────────────────────
    # ``window_key`` opts into layout persistence under
    # ``QSettings("apeGmsh", "MeshViewer")`` (plan 08 follow-up).
    # The Outline nav dock is registered HERE as a construction-time
    # extension dock with a cheap placeholder widget, so it is
    # present at saveState / restoreState time and participates in
    # layout persistence exactly like the built-in docks (which have
    # never gotten stuck). The real MeshOutlineTree — which needs
    # scene / selection state that doesn't exist yet — is swapped in
    # later via ``win.set_extension_dock_widget``. ``sanitize=True``
    # opts it into the per-launch degenerate-placement heal.
    from qtpy import QtWidgets as _QtW_outline
    from .ui._dock_registry import DockSpec
    from .ui._layout_metrics import LAYOUT
    default_title = f"MeshViewer — {self._parent.name}"
    win = ViewerWindow(
        title=title or default_title, window_key="MeshViewer",
        extension_docks=[DockSpec(
            dock_id="dock_mesh_outline",
            title="Outline",
            factory=lambda p: _QtW_outline.QWidget(p),
            default_area="left",
            sanitize=True,
            min_width=LAYOUT.outline_min_width,
            initial_width=LAYOUT.outline_initial_width,
            min_height=LAYOUT.outline_min_height,
            initial_height=LAYOUT.outline_initial_height,
        )],
    )
    self._win = win

    # ── Plan 04 step 3 — ActiveObjects coordinator ──────────────
    # One per viewer. Pick mode + selection get their canonical
    # signal surface here; existing per-instance state (the
    # ``_pick_mode[0]`` cache, ``sel.on_changed`` callbacks) stays
    # in lockstep via two bridges installed below.
    from .core._active_objects import ActiveObjects
    self._active = ActiveObjects(parent=win.window)
    # Pick mode bridge — subscribers update the legacy cache + the
    # status bar. ``_set_pick_mode`` now flows through
    # ``set_active_pick_mode``, so any future panel that wants to
    # react to pick-mode flips can subscribe to
    # ``activePickModeChanged`` without touching this file.
    self._active.activePickModeChanged.connect(self._on_active_pick_mode)
    # Seed the active pick mode with whatever the constructor /
    # __init__ set on the legacy cache (default "brep"). This keeps
    # ``self._active.active_pick_mode`` aligned with
    # ``_pick_mode[0]`` from the start — code that subscribes to
    # ``activePickModeChanged`` won't see a phantom "" state before
    # the first user key-press.
    try:
        self._active.set_active_pick_mode(self._pick_mode[0])
    except Exception:
        pass

    # ── UI tabs (AFTER QApplication exists) ─────────────────────
    info_tab = MeshInfoTab()
    self._info_tab = info_tab

    display_tab = DisplayTab(
        on_color_mode=self._on_color_mode,
        on_node_labels=self._toggle_node_labels,
        on_elem_labels=self._toggle_elem_labels,
        on_wireframe=self._toggle_wireframe,
        on_show_edges=self._toggle_edges,
        on_show_nodes=self._toggle_nodes,
        on_explode_axis=self._on_explode_axis,
    )
    self._display_tab = display_tab

    # FilterController (ADR 0045 S2) owns the active dimension set;
    # the checkbox panel and the 0/1/2/3/4 keys are two front-ends
    # writing it (INV-4). Built here (before the pick engine exists)
    # so the panel can route through it at construction; the fan-out
    # sink (on_change) is attached once pick_engine is live.
    self._filter = FilterController(self._dims)
    filter_tab = MeshFilterTab(
        self._dims,
        on_filter_changed=self._filter.set_active,
        on_mesh_probes_changed=self._on_mesh_probes_changed,
    )

    win.add_tab("Info", info_tab.widget)
    win.add_tab("Display", display_tab.widget)
    win.add_tab("Filter", filter_tab.widget)

    plotter = win.plotter
    self._plotter = plotter

    # ── Build scene ─────────────────────────────────────────────
    _verbose = getattr(self._parent, '_verbose', False)
    scene = build_mesh_scene(
        plotter, self._dims,
        line_width=self._line_width,
        surface_opacity=self._surface_opacity,
        show_surface_edges=self._show_surface_edges,
        node_marker_size=self._point_size,
        verbose=_verbose,
    )
    self._scene_data = scene
    self._scene = scene
    registry = scene.registry
    self._registry = registry

    # ── Hover tooltip overlay (Qt label on the plotter widget) ──
    from qtpy import QtWidgets as _QtW, QtCore as _QtC
    _interactor = getattr(plotter, "interactor", None)
    if _interactor is not None:
        self._hover_label = _QtW.QLabel(_interactor)
        self._hover_label.setStyleSheet(
            "QLabel { background-color: rgba(40, 40, 40, 220); "
            "color: #eee; padding: 4px 6px; border: 1px solid #555; "
            "border-radius: 3px; }"
        )
        self._hover_label.setAttribute(
            _QtC.Qt.WA_TransparentForMouseEvents
        )
        self._hover_label.hide()

    # ── Origin markers ──────────────────────────────────────────
    from .overlays.origin_markers_overlay import OriginMarkerOverlay
    from .ui.origin_markers_panel import OriginMarkersPanel
    _marker_size = _PREF.current.origin_marker_size
    origin_overlay = OriginMarkerOverlay(
        plotter,
        origin_shift=registry.origin_shift,
        model_diagonal=scene.model_diagonal,
        points=self._origin_markers,
        show_coords=self._origin_marker_show_coords,
        size=_marker_size,
    )
    origin_panel = OriginMarkersPanel(
        initial_points=self._origin_markers,
        initial_visible=True,
        initial_show_coords=self._origin_marker_show_coords,
        initial_size=_marker_size,
        on_visible_changed=origin_overlay.set_visible,
        on_show_coords_changed=origin_overlay.set_show_coords,
        on_marker_added=origin_overlay.add,
        on_marker_removed=origin_overlay.remove,
        on_size_changed=origin_overlay.set_size,
    )
    win.add_tab("Markers", origin_panel.widget)

    # ── Mesh tangent / normal overlay ───────────────────────────
    from .overlays.mesh_tangent_normal_overlay import (
        MeshTangentNormalOverlay,
    )
    self._mesh_tn_overlay = MeshTangentNormalOverlay(
        plotter,
        origin_shift=registry.origin_shift,
        model_diagonal=scene.model_diagonal,
        scale=_PREF.current.tangent_normal_scale,
    )

    # ── Resolve FEM snapshot for overlays ───────────────────────
    view = self._view
    if view is None:
        # ``get_fem_data`` builds the full FEMData broker (~2.7 s on
        # a 600 k-node mesh). Its only consumer is ``self._view``,
        # which feeds the loads / mass / constraints tabs and their
        # rebuild callbacks. Skip it for mesh-only models — see
        # :func:`_needs_fem_for_overlays`.
        _needs_fem = _needs_fem_for_overlays(self._parent)
        if _needs_fem:
            try:
                fem = self._parent.mesh.queries.get_fem_data(
                    dim=max(self._dims))
            except Exception:
                fem = None
            if fem is not None:
                from .data import ViewerData
                view = ViewerData.from_fem(fem)
    self._view = view

    # ── Overlay visibility model — PR5 / D2 closure ─────────────
    # Single source of truth for {load_patterns, constraint_kinds,
    # mass_visible} across the outline-tree eye-icons and the
    # right-side tab checkboxes.  Pre-PR5 each surface held its
    # own snapshot computed off Qt widget state — alternating
    # writes caused the overlay to flip to whichever surface fired
    # last.  Now both surfaces write to the model; the model
    # dedups (idempotent setters) and fans out to the rebuild
    # callbacks below.
    # Must be constructed BEFORE ``_build_overlay_tabs``: the
    # Loads/Mass/Constraints tab panels receive ``overlay_model=``
    # and ``on_*_changed=self._overlay_model.set_*`` at __init__,
    # so the attribute must already exist when the tabs are built.
    from .core.overlay_visibility import OverlayVisibilityModel
    self._overlay_model = OverlayVisibilityModel()

    # ── Mesh dispatcher (ADR 0056 V3) ────────────────────────────
    # One shared Dispatcher class, mesh pumps bound onto the
    # ``entities`` / ``overlays`` slots. Owner models fire their
    # events themselves; UI surfaces only call mutators; one
    # coalesced render per fire. The overlays pump replaces the
    # four per-overlay observer callbacks that used to hang off
    # ``overlay_model.subscribe`` (and each end in its own
    # ``plotter.render()``); ``key=None`` rebuilds all — the
    # gesture_batch replay path. The boundary-node overlay is
    # inert when ``view.nodes.has_boundary_nodes`` is False
    # (single-partition models, pre-2.10.0 archives, live
    # ``from_fem`` viewers) — unchanged from the observer wiring.
    from .diagrams._dispatch import Dispatcher

    def _pump_overlays(key: "str | None" = None) -> None:
        m = self._overlay_model
        if key in (None, "loads"):
            self._rebuild_loads_overlay(m.load_patterns)
        if key in (None, "mass"):
            self._rebuild_mass_overlay(m.mass_visible)
        if key in (None, "constraints"):
            self._rebuild_constraints_overlay(m.constraint_kinds)
        if key in (None, "boundary"):
            self._rebuild_boundary_node_overlay(m.boundary_nodes_visible)
        tn = getattr(self, "_mesh_tn_overlay", None)
        if key in (None, "tangent") and tn is not None:
            from .ui.preferences_manager import PREFERENCES as _P
            tn.set_scale(
                _P.current.tangent_normal_scale
                * m.scale("tangent_normal_arrow")
            )

    dispatcher = Dispatcher(
        self,
        pump_overlays=_pump_overlays,
        render=lambda: plotter.render(),
    )
    self._dispatcher = dispatcher
    self._overlay_model.dispatcher = dispatcher

    # ── Insert overlay tabs (loads/mass/constraints) ────────────
    self._build_overlay_tabs(win)

    # ── Preferences (created AFTER scene — needs registry) ─────
    self._build_preferences_tab(win)

    # ── Core modules ────────────────────────────────────────────
    color_mgr = ColorManager(registry)
    self._color_mgr = color_mgr
    # With the CAD-neutral palette (dim_pt/crv black, dim_srf/vol gray)
    # the default per-dim idle function already gives a uniform look
    # while keeping nodes black — no override needed.
    vis_mgr = VisibilityManager(registry, color_mgr, sel, plotter, verbose=_verbose)
    self._vis_mgr = vis_mgr
    # ADR 0056 V3: the manager owner-fires
    # MESH_ENTITY_VISIBILITY_CHANGED; its rebuild is the
    # dispatcher's ``entities`` pump (one coalesced render —
    # replaces the on_changed render subscriber).
    vis_mgr.dispatcher = dispatcher
    dispatcher.bind(pump_entities=vis_mgr.rebuild_now)
    pick_engine = PickEngine(
        plotter, registry,
        drag_threshold=_PREF.current.drag_threshold,
    )
    self._pick_engine = pick_engine

    # ── Color mode controller ───────────────────────────────────
    self._color_mode_ctrl = ColorModeController(
        color_mgr=color_mgr,
        registry=registry,
        scene=scene,
        sel=sel,
        vis_mgr=vis_mgr,
        plotter=plotter,
        view=self._view,
    )

    from .core.explode_controller import ExplodeController
    self._explode_ctrl = ExplodeController(
        registry=registry, scene=scene, plotter=plotter, view=self._view,
        vis_mgr=vis_mgr, color_mgr=color_mgr,
    )

    # ── Browser tab (groups + element types visibility) ─────────
    from .ui.mesh_browser_tab import MeshBrowserTab
    if scene.group_to_breps or scene.brep_dominant_type:
        def _browser_hidden_changed(hidden_set):
            if self._explode_ctrl is not None and self._explode_ctrl._active:
                # Stash the latest browser state and replay it when
                # explosion ends (see _on_explode_axis) rather than
                # dropping it — otherwise the checkboxes desync from
                # the VisibilityManager.
                self._pending_browser_hidden = set(hidden_set)
                return
            vis_mgr.set_hidden(hidden_set)

        self._browser_tab = MeshBrowserTab(
            scene, on_hidden_changed=_browser_hidden_changed,
        )
        win.add_tab("Browser", self._browser_tab.widget)

    # ── Left-rail outline tree — primary navigation ────────────
    # ParaView-style alternative to the right-side Browser tab.
    # Lists Physical Groups + Element Types + Parts, plus optional
    # Loads / Masses / Constraints sections when the matching
    # composites are set on ``g``. Eye toggles on those rows fire
    # the same rebuild callbacks the right-side tabs already use,
    # so the overlay updates the same way regardless of which
    # surface drove it.
    from .ui._mesh_outline_tree import MeshOutlineTree
    parts_reg = getattr(self._parent, 'parts', None)
    loads_comp = getattr(self._parent, 'loads', None)
    mass_comp = getattr(self._parent, 'masses', None)
    constraints_comp = getattr(self._parent, 'constraints', None)

    # Map outline row kinds to the right-side tab names whose
    # contents serve as the property editor for that row type.
    # mesh.viewer's right side is the legacy ``QTabWidget`` (not
    # tabified extension docks), so we identify tabs by their
    # text label.
    _OUTLINE_TAB_MAP = {
        "group":           "Browser",
        "type":            "Browser",
        "part":            "Browser",
        "load_pattern":    "Loads",
        "mass":            "Mass",
        "constraint_kind": "Constraints",
    }

    def _on_outline_row_focused(kind: str, _payload) -> None:
        tab_name = _OUTLINE_TAB_MAP.get(kind)
        if tab_name is not None:
            win.focus_tab(tab_name)

    self._outline_tree = MeshOutlineTree(
        scene=scene,
        selection=sel,
        vis_mgr=vis_mgr,
        parts_registry=parts_reg,
        loads_composite=loads_comp,
        mass_composite=mass_comp,
        constraints_composite=constraints_comp,
        # PR5 — both writers go through ``self._overlay_model``;
        # the legacy ``on_*_changed`` callbacks route writes into
        # the model rather than calling ``_rebuild_*`` directly.
        # Passing ``overlay_model=`` ALSO subscribes the outline
        # to model changes so tab-checkbox writes refresh the
        # outline's eye-icons (cross-surface UI sync).
        on_load_patterns_changed=self._overlay_model.set_load_patterns,
        on_mass_visibility_changed=self._overlay_model.set_mass_visible,
        on_constraint_kinds_changed=self._overlay_model.set_constraint_kinds,
        on_boundary_nodes_changed=self._overlay_model.set_boundary_nodes_visible,
        on_row_focused=_on_outline_row_focused,
        overlay_model=self._overlay_model,
        # PR2 — partition rows (ADR 0027). The outline reads
        # ``view.elements.partition_for(eid)`` to group entities by
        # dominant OpenSeesMP rank; hidden when the view is absent
        # or carries no partition labelling.
        view=self._view,
    )
    # Swap the real outline tree into the placeholder dock that was
    # registered at construction (see the ViewerWindow call above).
    # The dock already participates in layout persistence + the
    # per-launch sanitize heal; this just installs its content.
    win.set_extension_dock_widget(
        "dock_mesh_outline", self._outline_tree.widget,
    )

    # ── Clipping tab ────────────────────────────────────────────
    from .core.clipping_controller import ClippingController
    from .ui.clipping_tab import ClippingTab
    self._clipping_ctrl = ClippingController(plotter, registry)
    self._clipping_tab = ClippingTab(
        on_toggle=self._clipping_ctrl.toggle,
        on_reset=self._clipping_ctrl.reset,
    )
    win.add_tab("Clipping", self._clipping_tab.widget)

    # ── Wire callbacks ──────────────────────────────────────────
    pick_engine.on_pick = self._handle_pick
    pick_engine.on_hover = self._handle_hover
    pick_engine.on_box_select = self._handle_box_select
    pick_engine.set_hidden_check(vis_mgr.is_hidden)

    # Attach the FilterController's fan-out now that the pick engine
    # exists: drive both actor visibility (the user-visible effect)
    # and the pick-engine pickable-dims mask (so picks ignore hidden
    # dims), then reflect the set back into the panel (key→panel
    # sync). Replaces the old monkeypatch of ``filter_tab._on_filter``
    # — the panel already routes through ``self._filter.set_active``
    # at construction, so both front-ends share one source of truth.
    def _apply_filter(active_dims) -> None:
        self._on_mesh_filter(set(active_dims))
        pick_engine.set_pickable_dims(set(active_dims))
        filter_tab.sync_active(active_dims)
    self._filter.on_change = _apply_filter

    # Selection changed -> recolor
    sel.on_changed.append(self._handle_sel_changed)
    if self._on_selection_changed is not None:
        def _studio_sel() -> None:
            self._on_selection_changed(sel)
        sel.on_changed.append(_studio_sel)
        _studio_sel()
    # Plan 04 step 3 — selection bridge into ActiveObjects.
    # ``SelectionState`` keeps its legacy ``on_changed`` list (the
    # plan doc marks it as a one-release compatibility shim); this
    # bridge fans the same event out via ``selectionChanged``
    # so new subscribers don't need to know about SelectionState's
    # internal callback list. The payload is an immutable tuple of
    # picks — fresh per emit, so ``ActiveObjects``' identity check
    # doesn't suppress repeat fires when picks mutate in place,
    # and downstream subscribers get a stable snapshot they can
    # cache without worrying about later mutation. Subscribers
    # needing more (centroid, parent shapes) reach for
    # ``viewer._sel`` via the viewer reference.
    def _sel_bridge() -> None:
        if self._active is not None and self._sel is not None:
            self._active.set_selection(tuple(self._sel.picks))
    sel.on_changed.append(_sel_bridge)
    self._sel_bridge_unsub = _sel_bridge
    # (No render subscriber on vis_mgr.on_changed — the dispatcher
    # renders once per MESH_ENTITY_VISIBILITY_CHANGED fire,
    # ADR 0056 V3.)
    # Repaint mesh idle colors when the theme palette changes
    win.on_theme_changed(lambda _p: self._handle_sel_changed())
    # Refresh tangent / normal arrows when palette changes
    win.on_theme_changed(
        lambda _p: self._mesh_tn_overlay.refresh_theme()
        if self._mesh_tn_overlay is not None else None
    )
    win.on_theme_changed(lambda _p: origin_overlay.refresh_theme())

    # ── Navigation ──────────────────────────────────────────────
    install_navigation(
        plotter,
        get_orbit_pivot=lambda: sel.centroid(registry),
    )

    # ── Motion LOD ──────────────────────────────────────────────
    # The per-dim node cloud (one sphere-sprite per FE node — 600k+
    # on large meshes) dominates per-frame GPU cost. Hide it while
    # the camera is moving and restore it ~120 ms after the gesture
    # settles, so orbit/zoom stay smooth without losing the node
    # display at rest. Mirrors ParaView's interactive LOD.
    from .core.motion_lod import MotionLOD
    self._motion_lod = MotionLOD(
        plotter,
        lambda: list(registry.dim_node_actors.values()),
    )
    self._motion_lod.install()

    # ── Install pick engine ─────────────────────────────────────
    pick_engine.install()

    # ── Toolbar buttons for visibility ──────────────────────────
    win.add_toolbar_separator()
    win.add_toolbar_button(
        "Hide selected (H)", "", self._act_hide, icon="eye_off",
    )
    win.add_toolbar_button(
        "Isolate selected (I)", "", self._act_isolate, icon="isolate",
    )
    win.add_toolbar_button(
        "Reveal all (R)", "", self._act_reveal_all, icon="reveal",
    )
    win.add_toolbar_separator()
    win.add_toolbar_button(
        "Save image…", "", self._act_screenshot, icon="image",
    )

    # ── Keybindings ─────────────────────────────────────────────
    plotter.add_key_event("h", self._act_hide)
    plotter.add_key_event("i", self._act_isolate)
    plotter.add_key_event("r", self._act_reveal_all)
    # Undo / clear route to the active pick set: FE-topo in
    # element/node mode, BREP entities in brep mode (ADR 0045 S3b).
    plotter.add_key_event("u", self._handle_undo)

    win.add_shortcut("Escape", self._handle_clear)
    win.add_shortcut("Q", lambda: win.window.close())

    plotter.add_key_event("e", lambda: self._set_pick_mode("element"))
    plotter.add_key_event("n", lambda: self._set_pick_mode("node"))
    plotter.add_key_event("b", lambda: self._set_pick_mode("brep"))

    # Dim filters (ADR 0045 S2 — closes the missing-keys gap, HARD
    # REQ 2): a bare key TOGGLES that dim (multi-select); 4 = all.
    # ApplicationShortcut: VTK's QtInteractor swallows plotter
    # add_key_event digit keys (same law as ResultsViewer Esc).
    for _key, _dim in [("0", 0), ("1", 1), ("2", 2), ("3", 3)]:
        win.add_shortcut(
            _key, lambda d=_dim: self._filter.toggle(d), application=True,
        )
    win.add_shortcut(
        "4", lambda: self._filter.select_all(), application=True,
    )

    # ── File menu (ADR 0087 Appendix B) ─────────────────────────
    # Save image… mirrors the toolbar action; Preferences… opens
    # the persistent global-preferences dialog (also reachable via
    # the Display tab's button). Inserted leftmost so the bar reads
    # File / View / Help (INV-5).
    from qtpy import QtWidgets as _QtW_file
    from .ui.preferences_dialog import open_preferences_dialog as _open_prefs
    _file_menu = _QtW_file.QMenu("File", win.window)
    _file_menu.addAction("Save image…").triggered.connect(
        lambda _checked=False: self._act_screenshot()
    )
    _file_menu.addSeparator()
    _file_menu.addAction("Preferences…").triggered.connect(
        lambda _checked=False: _open_prefs(win.window)
    )
    _mb = win.window.menuBar()
    _mb_acts = _mb.actions()
    if _mb_acts:
        _mb.insertMenu(_mb_acts[0], _file_menu)   # File leftmost
    else:
        _mb.addMenu(_file_menu)

    # ── View → Navigation / Camera / Theme submenus (ADR 0087) ──
    win.install_navigation_menu()
    win.install_camera_menu()
    win.install_theme_menu()

    # ── Help → Shortcuts (top menu) ─────────────────────────────
    from .ui._shortcuts_help import add_help_shortcuts_menu
    add_help_shortcuts_menu(
        win.window,
        entries=[
            ("B / E / N", "Pick mode — BRep / element / node"),
            ("0 / 1 / 2 / 3", "Toggle dim filter — point / curve / surface / volume"),
            ("4", "Show all dims"),
            ("H / I / R", "Hide / isolate / reveal all"),
            ("U", "Undo"),
            ("Shift+LMB drag", "Turntable (yaw-only around up axis)"),
            ("Shift+MMB drag", "Orbit (yaw + pitch, no-roll)"),
            ("MMB / RMB drag", "Pan"),
            ("Scroll", "Zoom (focal point fixed)"),
            ("Esc", "Deselect"),
            ("Q", "Close window"),
        ],
    )

    # ── Show summary ────────────────────────────────────────────
    n_nodes = len(scene.node_tags)
    n_elems = sum(len(v) for v in scene.brep_to_elems.values())
    info_tab.show_summary(n_nodes, n_elems)
    win.set_status(
        f"Mesh: {n_nodes:,} nodes, {n_elems:,} elements | "
        f"Mode: BRep (press E=element, N=node, B=brep)"
    )

    # ── Run ─────────────────────────────────────────────────────
    win.exec()
    if self._color_mode_ctrl is not None:
        self._color_mode_ctrl.close()
    return self

Results session window — Results.viewer()

results.viewer() opens the post-solve window. Since ADR 0098 it is sugar for results.session().show(): the document is a ResultsSession — docked mesh and plot panes, each pane carrying result slots — and the window is one client that projects it. A script can build or read the same object with no window at all, and what the window saves is that object.

results.viewer()               # the human one-liner (blocking)

s = results.session()          # the same document, no window
s.render("pane.png")           # a still, no Qt
s.show()                       # the same window, from Python

Explicit blocking=True still crashes the Jupyter kernel

results.viewer() defaults to blocking=None (auto): True (in-process Qt) in scripts / the CLI, False (subprocess) inside a Jupyter kernel. An in-memory Results in a notebook cannot spawn a subprocess and falls back to results.show_web(). An explicit blocking=True still drives the VTK+Qt event loop in-process and kills the ipykernel.

The blocking call returns the ResultsSession once the window closes — still live, so you can query it, render stills off it, or snapshot it. blocking=False returns the subprocess.Popen handle instead, and the notebook in-memory fallback returns the WebViewer: three different things on purpose, because a session in this process is not what a child window is showing.

Saving and restoring

save_session=True (the default) writes the session — panes, slots, pose, time link, selection — to <results>.viewer-session.json when the window closes. restore_session decides what happens to a file already there: True restores it silently, False ignores it, and "prompt" (the default) asks first, listing what the file contains and anything about it that no longer fits these results.

The window always opens. A session file that cannot be read never blocks it and is never destroyed by it: the reason is printed, the default picture boots, and auto-save is switched off for that window so the file is still there afterwards. That last part matters because the save target is the file that was refused.

Sessions written by the retired Geometry / Composition / Diagram viewer are not restorable. The first upgraded open says so in one line and renames the old file to <results>.viewer-session.json.legacy — overwriting neither it nor an aside already sitting there.

apeGmsh.viewers.session._window.SessionWindow

SessionWindow(session: Any, *, title: Optional[str] = None, backend_factory: Optional[Any] = None, defer_fn: Optional[Callable[[Callable[[], None]], None]] = None)

One window projecting one session (§1: the window is a client).

Source code in src/apeGmsh/viewers/session/_window.py
def __init__(
    self,
    session: Any,
    *,
    title: Optional[str] = None,
    backend_factory: Optional[Any] = None,
    defer_fn: Optional[Callable[[Callable[[], None]], None]] = None,
) -> None:
    results = session.results
    if results is None:
        raise RuntimeError(
            "This session has no Results bound — construct it via "
            "results.session() to show a window."
        )
    if results.fem is None:
        raise RuntimeError(
            "session.show requires a bound FEMData (construct "
            "with model= / model_h5= or call results.bind)."
        )
    self._session = session
    self._shell = SessionResultsWindow(
        title=title or "Results session",
        on_close=self._on_close,
        central_interactor=False,
    )
    self._closed = False

    # The host and the outline are two renderings of one state
    # (A1.5), so each calls back into the other. The host is built
    # first — it owns the pane frames the outline's Add gate sizes
    # against — and its constructor already fires the boot
    # activation, so everything a callback touches is initialised
    # here, above it.
    self._pages: dict[str, Any] = {}
    self._current_page: Any = None
    self._nothing_selected = PanePlaceholderPage(
        "No pane selected. Add a mesh view from the outline to "
        "start a picture.",
    )
    self._outline: Optional[SessionOutline] = None
    self._host: Optional[SessionPaneHost] = None

    # The panes are docks of the SHELL's window, seated right of
    # the outline — ADR 0088 D1's partition with the middle column
    # made of dock panels (A3.2), never of a central widget.
    self._host = SessionPaneHost(
        session,
        dock_host=self._shell.window,
        anchor_dock=self._shell.outline_dock,
        backend_factory=backend_factory,
        defer_fn=defer_fn,
        on_active_changed=self._on_active_changed,
        on_panes_changed=self._on_panes_changed,
        on_geometry_changed=self._on_geometry_changed,
    )
    # The toolbar acts on ONE object: whichever pane is active.
    self._shell.set_plotter_provider(self._active_plotter)

    self._outline = SessionOutline(
        session,
        on_pane_selected=self._on_pane_selected,
        on_new_view=self._on_new_view,
        on_new_plot=self._on_new_plot,
        on_new_plot_from_selection=self._on_new_plot_from_selection,
        on_close_pane=self._on_close_pane,
        can_add=self._host.can_add,
    )
    self._shell.set_left_widget(self._outline.widget)

    # ADR 0087 INV-2 (honest empty state). The shell creates the
    # "Display" dock unconditionally and the View menu can summon
    # it; the session window has not built its contents yet, so
    # without this a user who opens it gets a blank panel. One
    # muted hint line that says what to DO, per INV-2 — not a
    # statement of what is absent. Fixed in S6b; the dock's real
    # contents (point size, line width, ID labels) are a port owed
    # by a later slice.
    self._shell.set_session_widget(
        PanePlaceholderPage(
            "Use View → Theme to change the palette, or "
            "apeGmsh.viewers.settings() for label and scale "
            "defaults.",
        ).widget,
    )

    # §7's one control. Bottom dock, under the pane docks, because
    # while the link is on it drives every one of them.
    self._scrubber = SessionScrubber(session, defer_fn=defer_fn)
    self._shell.set_bottom_widget(self._scrubber.widget)

    # Boot selection: the host already made the first pane active;
    # mirror it onto the outline and the inspector.
    if self._host.active_pane_id is not None:
        self._on_active_changed(self._host.active_pane_id)
    else:
        self._mount_page(None)

    # A palette swap changes the substrate colours realize bakes
    # into its layers AND the panes' own backgrounds — one palette,
    # N panes.
    self._shell.on_theme_changed(self._on_theme_changed)
    self._shell.reset_layout_hook = self._on_reset_layout
    # The panes own the interactors, so the navigation menu has to
    # reach them — one palette, one convention, N panes.
    self._shell.navigation_hook = self._host.apply_navigation

    self._restore_pane_arrangement()

    # Surface swallowed reconciler failures on the status bar
    # (ADR 0084 D4 — never silent).
    self._error_handler = self._on_pump_error
    register_error_handler(self._error_handler)

host property

host: SessionPaneHost

The pane docks (Amendment 3). Tests address panes through it — host.frame(pane_id) / host.dock(pane_id) / host.pane_frames — never by digging objectNames out of the window (caution 8).

scrubber property

scrubber: SessionScrubber

The §7 time control (bottom dock).

current_page property

current_page: Any

The mounted inspector page (criterion 9).

inspector_page

inspector_page(pane_id: str) -> Any

The (cached) inspector page for a pane id.

Source code in src/apeGmsh/viewers/session/_window.py
def inspector_page(self, pane_id: str) -> Any:
    """The (cached) inspector page for a pane id."""
    return self._pages[pane_id]

show

show(*, blocking: bool = True) -> Optional[int]

Present the window; run the Qt loop when blocking.

Source code in src/apeGmsh/viewers/session/_window.py
def show(self, *, blocking: bool = True) -> Optional[int]:
    """Present the window; run the Qt loop when ``blocking``."""
    # `resizeDocks` only lands once the layout is live, so the extents
    # requested during construction never applied. Queue them for the
    # first turn of the loop, on both the blocking and non-blocking
    # path (Amendment 3).
    from qtpy.QtCore import QTimer

    QTimer.singleShot(0, self._apply_dock_extents)
    if blocking:
        return self._shell.exec()
    _LIVE_WINDOWS.append(self)
    self._shell.present()
    return None

Colour scales

A scale is caused by a slot, and belongs to the pane. Filling a colour-mapped slot creates its scale; clearing the slot destroys it; two slots showing the same quantity share one scale. Hiding a scale never hides the picture it names, and each pane carries the scales of its own slots — so a quad view of four contours is four panes with one scale each.

Deform is not a slot: a warped mesh with every slot empty draws no scale at all. The scale names the slot's quantity, so warping by displacement while contouring stress gives a scale that says stress.

Number format, orientation and font scale come from the slot's style. The global default size lives in the preferences editor, which this window has no menu entry for — open it from Python with apeGmsh.viewers.settings() (Labels → Colour-scale text size).

Web viewers — results.show_web() / results.serve_web()

Kernel-safe trame/PyVista viewers for notebooks and the browser. These require the [viewer] extra (install with [viewer] — or [all] — in the pip line from Install).

results.show_web(*, stage=None, show=True, controls=True, render_mode="client") renders an inline trame view inside Jupyter, with ipywidgets step-slider and layer toggles when controls=True. It returns a WebViewer.

results.serve_web(*, stage=None, render_mode="client", port=None, open_browser=True, title="apeGmsh") launches a standalone vuetify3 web app (blocks until interrupted) — for use outside a notebook.

render_mode is a friendly alias: "client" (default — WebGL in the browser, fast camera), "server" (kernel-side, image-streamed, for very large models), or "hybrid" (toolbar toggle). Any other value raises ValueError.

from apeGmsh import Results

# Zero-setup sample (real apeSees-emitted model + synthetic pushover)
results = Results.demo()

wv = results.show_web()        # inline trame view + ipywidgets controls
wv.set_step(3)                 # programmatic scrub + re-render

# results.serve_web(port=8080)   # standalone app, outside a notebook

Results.demo(**kwargs) (and the underlying make_demo_results(*, length=10.0, n_elements=8, n_steps=6, tip_drift=2.0, path=None)) build a ready-to-view sample with no .mpco/model.h5 needed — handy for trying the web viewers cold.

apeGmsh.viewers.web_viewer.WebViewer

WebViewer(results: 'Results', *, stage: Optional[str] = None, substrate_color: str = 'lightgray', plotter: Optional[Any] = None)

Minimal view-only web/Jupyter shell around a :class:ResultsDirector.

Parameters

results The :class:~apeGmsh.results.Results to render. stage Stage id or name to activate. Defaults to the first stage. substrate_color Solid colour for the FEM substrate mesh. plotter Inject a pyvista plotter (e.g. pv.Plotter(off_screen=True) in a render-capable test). Defaults to a fresh pv.Plotter() that the trame shell serves.

Source code in src/apeGmsh/viewers/web_viewer.py
def __init__(
    self,
    results: "Results",
    *,
    stage: Optional[str] = None,
    substrate_color: str = "lightgray",
    plotter: Optional[Any] = None,
) -> None:
    import pyvista as pv

    from .backends import TrameBackend
    from .diagrams._director import ResultsDirector
    from .scene.fem_scene import build_fem_scene

    director = ResultsDirector(results)
    view = director.view
    if view is None:
        raise RuntimeError(
            "WebViewer requires a Results with bound FEMData. "
            "Construct Results with fem= or call results.bind(fem)."
        )
    scene = build_fem_scene(view)

    if plotter is None:
        plotter = pv.Plotter()
    plotter.add_mesh(
        scene.grid, color=substrate_color, show_edges=True,
        name="substrate", pickable=False,
    )

    backend = TrameBackend(plotter)
    director.bind_plotter(backend, scene=scene, render_callback=plotter.render)

    # Activate a stage so n_steps / set_step are live, then land on
    # step 0. Mirrors the Qt viewer's boot behaviour.
    stages = director.stages()
    if stages:
        director.set_stage(stage or stages[0].id)
        director.set_step(0)

    self._results = results
    self._director = director
    self._scene = scene
    self._plotter = plotter
    self._backend = backend

set_step

set_step(step_index: int) -> None

Move the active step and re-render (programmatic scrub).

plotter.render() is what propagates the change to the trame view: pyvista registers an on-render callback when the view is created (_BasePyVistaView), so a render pushes the new frame to the browser. The same call drives both the Qt and web paths.

Source code in src/apeGmsh/viewers/web_viewer.py
def set_step(self, step_index: int) -> None:
    """Move the active step and re-render (programmatic scrub).

    ``plotter.render()`` is what propagates the change to the trame
    view: pyvista registers an on-render callback when the view is
    created (``_BasePyVistaView``), so a render pushes the new frame
    to the browser. The same call drives both the Qt and web paths.
    """
    self._director.set_step(int(step_index))
    self._plotter.render()

set_layer_visible

set_layer_visible(diagram: Any, visible: bool) -> None

Show / hide one diagram layer and re-render.

Source code in src/apeGmsh/viewers/web_viewer.py
def set_layer_visible(self, diagram: Any, visible: bool) -> None:
    """Show / hide one diagram layer and re-render."""
    self._director.registry.set_visible(diagram, bool(visible))
    self._plotter.render()

layer_diagrams

layer_diagrams() -> list[Any]

The diagrams currently in the registry (one per toggle).

Source code in src/apeGmsh/viewers/web_viewer.py
def layer_diagrams(self) -> list[Any]:
    """The diagrams currently in the registry (one per toggle)."""
    return list(self._director.registry.diagrams())

controls

controls() -> Any

Build an ipywidgets control panel for this viewer.

A step :class:~ipywidgets.IntSlider (when the active stage has more than one step) plus one :class:~ipywidgets.Checkbox per diagram layer. The slider drives :meth:set_step; each checkbox drives :meth:set_layer_visible. Both re-render, which pushes to the trame view via pyvista's on-render callback.

Returns a :class:~ipywidgets.VBox. Raises if ipywidgets is not installed — call :meth:show (which degrades gracefully to a bare view) if you only need the render.

Source code in src/apeGmsh/viewers/web_viewer.py
def controls(self) -> Any:
    """Build an ``ipywidgets`` control panel for this viewer.

    A step :class:`~ipywidgets.IntSlider` (when the active stage has
    more than one step) plus one :class:`~ipywidgets.Checkbox` per
    diagram layer. The slider drives :meth:`set_step`; each checkbox
    drives :meth:`set_layer_visible`. Both re-render, which pushes to
    the trame view via pyvista's on-render callback.

    Returns a :class:`~ipywidgets.VBox`. Raises if ``ipywidgets`` is
    not installed — call :meth:`show` (which degrades gracefully to a
    bare view) if you only need the render.
    """
    try:
        import ipywidgets as W
    except ImportError as exc:  # pragma: no cover - env-dependent
        raise RuntimeError(
            "WebViewer.controls() needs ipywidgets — install the "
            "[viewer] extra, or call show(controls=False)."
        ) from exc

    children: list[Any] = []
    n = self.n_steps
    if n > 1:
        slider = W.IntSlider(
            value=0, min=0, max=n - 1, step=1, description="Step",
            continuous_update=False,
        )
        slider.observe(
            lambda change: self.set_step(int(change["new"])),
            names="value",
        )
        children.append(slider)

    for diagram in self.layer_diagrams():
        checkbox = W.Checkbox(
            value=bool(getattr(diagram, "is_visible", True)),
            description=self._layer_label(diagram),
        )

        def _handler(diag: Any):
            return lambda change: self.set_layer_visible(
                diag, bool(change["new"])
            )

        checkbox.observe(_handler(diagram), names="value")
        children.append(checkbox)

    return W.VBox(children)

build_app

build_app(*, render_mode: str = 'client', title: str = 'apeGmsh', server_name: Optional[str] = None) -> Any

Build a standalone trame web app (vuetify3) around this viewer.

Constructs a :class:trame.app.Server with a :class:~trame.ui.vuetify3.SinglePageLayout: the pyvista view (via :func:pyvista.trame.ui.plotter_ui) fills the content, and the toolbar carries a step slider (when the active stage has more than one step) plus one switch per diagram layer. The slider and switches bind to trame state; server-side state.change handlers drive :meth:set_step / :meth:set_layer_visible, which re-render and push to the browser through pyvista's on-render callback (the same mechanism as the Jupyter path).

The server is returned unstarted so construction is fully headless and unit-testable; :meth:serve starts it. render_mode ("client" / "server" / "hybrid") maps to the plotter_ui render mode.

Source code in src/apeGmsh/viewers/web_viewer.py
def build_app(
    self,
    *,
    render_mode: str = "client",
    title: str = "apeGmsh",
    server_name: Optional[str] = None,
) -> Any:
    """Build a standalone trame web app (vuetify3) around this viewer.

    Constructs a :class:`trame.app.Server` with a
    :class:`~trame.ui.vuetify3.SinglePageLayout`: the pyvista view
    (via :func:`pyvista.trame.ui.plotter_ui`) fills the content, and
    the toolbar carries a step slider (when the active stage has more
    than one step) plus one switch per diagram layer. The slider and
    switches bind to trame state; server-side ``state.change`` handlers
    drive :meth:`set_step` / :meth:`set_layer_visible`, which re-render
    and push to the browser through pyvista's on-render callback (the
    same mechanism as the Jupyter path).

    The server is returned **unstarted** so construction is fully
    headless and unit-testable; :meth:`serve` starts it. ``render_mode``
    (``"client"`` / ``"server"`` / ``"hybrid"``) maps to the
    ``plotter_ui`` render mode.
    """
    from trame.app import get_server
    from trame.ui.vuetify3 import SinglePageLayout
    from trame.widgets import vuetify3 as v3
    from pyvista.trame.ui import plotter_ui

    ui_mode = _resolve_ui_mode(render_mode)

    server = get_server(name=server_name, client_type="vue3")
    state = server.state

    layer_keys = [
        (f"layer_{i}_visible", diagram)
        for i, diagram in enumerate(self.layer_diagrams())
    ]

    state.step = 0
    for key, diagram in layer_keys:
        state[key] = bool(getattr(diagram, "is_visible", True))

    @state.change("step")
    def _on_step(step=0, **_kwargs):
        self.set_step(int(step))

    if layer_keys:
        @state.change(*[key for key, _ in layer_keys])
        def _on_visibility(**_kwargs):
            for key, diagram in layer_keys:
                self.set_layer_visible(diagram, bool(state[key]))

    with SinglePageLayout(server) as layout:
        layout.title.set_text(title)
        with layout.toolbar:
            v3.VSpacer()
            if self.n_steps > 1:
                v3.VSlider(
                    v_model=("step", 0),
                    min=0, max=self.n_steps - 1, step=1,
                    label="Step", hide_details=True, density="compact",
                    style="max-width: 320px;",
                )
            for key, diagram in layer_keys:
                v3.VSwitch(
                    v_model=(key,),
                    label=self._layer_label(diagram),
                    hide_details=True, density="compact",
                    classes="ml-2",
                )
        with layout.content:
            with v3.VContainer(
                fluid=True, classes="pa-0 fill-height",
            ):
                plotter_ui(self._plotter, mode=ui_mode)

    return server

serve

serve(*, render_mode: str = 'client', port: Optional[int] = None, open_browser: bool = True, title: str = 'apeGmsh', **start_kwargs: Any) -> Any

Build the standalone trame app and start serving it.

Opens a browser tab at the served URL (open_browser). In a plain script this blocks until the server is stopped (Ctrl-C); inside a notebook / already-running asyncio loop it schedules the server as a background task and returns immediately (so the cell doesn't hang and you keep an interactive kernel). Honours APEGMSH_SKIP_VIEWER (returns the unstarted server without serving) so CI / headless runs don't block. Extra keyword arguments pass through to server.start; pass exec_mode= explicitly to override the auto-detected mode.

Source code in src/apeGmsh/viewers/web_viewer.py
def serve(
    self,
    *,
    render_mode: str = "client",
    port: Optional[int] = None,
    open_browser: bool = True,
    title: str = "apeGmsh",
    **start_kwargs: Any,
) -> Any:
    """Build the standalone trame app and start serving it.

    Opens a browser tab at the served URL (``open_browser``). In a plain
    script this blocks until the server is stopped (Ctrl-C); inside a
    notebook / already-running asyncio loop it schedules the server as a
    background task and returns immediately (so the cell doesn't hang and
    you keep an interactive kernel). Honours ``APEGMSH_SKIP_VIEWER``
    (returns the unstarted server without serving) so CI / headless runs
    don't block. Extra keyword arguments pass through to ``server.start``;
    pass ``exec_mode=`` explicitly to override the auto-detected mode.
    """
    server = self.build_app(render_mode=render_mode, title=title)
    if os.environ.get("APEGMSH_SKIP_VIEWER"):
        print("[skip web viewer] APEGMSH_SKIP_VIEWER set")
        return server
    if port is not None:
        start_kwargs["port"] = port
    start_kwargs["open_browser"] = open_browser
    # Default exec_mode="main" calls loop.run_until_complete, which raises
    # "This event loop is already running" under Jupyter/ipykernel. When a
    # loop is already running, schedule the server as a task on it instead
    # (non-blocking); a plain script keeps the blocking "main" mode.
    start_kwargs.setdefault(
        "exec_mode", "task" if _event_loop_running() else "main"
    )
    server.start(**start_kwargs)
    return server

show

show(*, controls: bool = True, render_mode: str = 'client', jupyter_backend: Optional[str] = None, **kwargs: Any) -> Any

Display the scene inline (Jupyter) via pyvista's trame backend.

render_mode picks how the scene is rendered (resolved Q2):

  • "client" (default) — VTK.js / WebGL in the browser; camera interaction is local and instant. Fast for typical models.
  • "server" — render on the kernel and stream images back; most VTK-feature-complete but laggy. Use for very large models.
  • "hybrid" — pyvista's trame backend (both, with a local/remote toggle in the toolbar).

Pass jupyter_backend to override with a raw pyvista backend name (e.g. "html", "static"); it takes precedence over render_mode.

Returns the trame view widget — or, when controls is True and ipywidgets is available, a :class:~ipywidgets.VBox of the control panel stacked above the view. Honours APEGMSH_SKIP_VIEWER (returns None) so the same cell runs under nbconvert --execute / CI without a browser.

Source code in src/apeGmsh/viewers/web_viewer.py
def show(
    self,
    *,
    controls: bool = True,
    render_mode: str = "client",
    jupyter_backend: Optional[str] = None,
    **kwargs: Any,
) -> Any:
    """Display the scene inline (Jupyter) via pyvista's trame backend.

    ``render_mode`` picks how the scene is rendered (resolved Q2):

    * ``"client"`` (default) — VTK.js / WebGL in the browser; camera
      interaction is local and instant. Fast for typical models.
    * ``"server"`` — render on the kernel and stream images back; most
      VTK-feature-complete but laggy. Use for very large models.
    * ``"hybrid"`` — pyvista's ``trame`` backend (both, with a
      local/remote toggle in the toolbar).

    Pass ``jupyter_backend`` to override with a raw pyvista backend name
    (e.g. ``"html"``, ``"static"``); it takes precedence over
    ``render_mode``.

    Returns the trame view widget — or, when ``controls`` is ``True``
    and ``ipywidgets`` is available, a :class:`~ipywidgets.VBox` of the
    control panel stacked above the view. Honours
    ``APEGMSH_SKIP_VIEWER`` (returns ``None``) so the same cell runs
    under ``nbconvert --execute`` / CI without a browser.
    """
    if os.environ.get("APEGMSH_SKIP_VIEWER"):
        print("[skip web viewer] APEGMSH_SKIP_VIEWER set")
        return None
    backend = jupyter_backend or _resolve_jupyter_backend(render_mode)
    view = self._plotter.show(
        jupyter_backend=backend, return_viewer=True, **kwargs
    )
    if not controls:
        return view
    try:
        import ipywidgets as W
    except ImportError:  # pragma: no cover - env-dependent
        return view  # degrade: no controls, just the rendered view
    # The control panel can only be stacked when the trame view is an
    # ipywidget. pyvista returns a *non*-widget when the trame server
    # couldn't launch (a static-image fallback — usually a missing
    # ``nest_asyncio2``, which pyvista needs to start the server without
    # ``await``) or in some IFrame modes; wrapping that in a VBox raises
    # a TraitError. Degrade to the bare view with a clear pointer.
    if not isinstance(view, W.Widget):
        import warnings

        warnings.warn(
            "show_web fell back to a static image without the control "
            "panel — the trame server could not launch in-notebook. "
            "Install nest_asyncio2 (`pip install nest_asyncio2`) for the "
            "live interactive view plus the step / visibility controls.",
            RuntimeWarning,
            stacklevel=2,
        )
        return view
    return W.VBox([self.controls(), view])

Geometric transform viewer

apeGmsh.viewers.geom_transf_viewer.GeomTransfViewer

GeomTransfViewer(title: str = 'OpenSees geomTransf viewer')

Browser-based 3D viewer for OpenSees geomTransf visualisation.

Spins up a lightweight local HTTP server, opens the viewer in the default browser, and blocks until the browser tab is closed. The server shuts itself down automatically — no input() prompt, no leftover temp files.

Parameters

title : str Window / browser-tab title (default: "OpenSees geomTransf viewer").

Source code in src/apeGmsh/viewers/geom_transf_viewer.py
def __init__(self, title: str = "OpenSees geomTransf viewer") -> None:
    self._title = title

show

show(node_i: Sequence[float] | None = None, node_j: Sequence[float] | None = None, vecxz: Sequence[float] | None = None, beams: list[dict] | None = None) -> None

Open the interactive geomTransf viewer in the default browser.

Blocks until the browser tab is closed.

Parameters

node_i : [x, y, z] Start node (single-beam convenience). node_j : [x, y, z] End node (single-beam convenience). vecxz : [vx, vy, vz] Vector in local x-z plane (default [1, 0, 0]). beams : list[dict] List of dicts with keys 'node_i', 'node_j', 'vecxz' (optional). Pass this for multi-beam mode.

Source code in src/apeGmsh/viewers/geom_transf_viewer.py
def show(
    self,
    node_i: Sequence[float] | None = None,
    node_j: Sequence[float] | None = None,
    vecxz: Sequence[float] | None = None,
    beams: list[dict] | None = None,
) -> None:
    """
    Open the interactive geomTransf viewer in the default browser.

    Blocks until the browser tab is closed.

    Parameters
    ----------
    node_i : [x, y, z]
        Start node (single-beam convenience).
    node_j : [x, y, z]
        End node (single-beam convenience).
    vecxz : [vx, vy, vz]
        Vector in local x-z plane (default ``[1, 0, 0]``).
    beams : list[dict]
        List of dicts with keys ``'node_i'``, ``'node_j'``,
        ``'vecxz'`` (optional).  Pass this for multi-beam mode.
    """
    beam_list = self._build_beam_list(node_i, node_j, vecxz, beams)
    html = _build_html(beam_list, self._title)

    # ── local HTTP server ─────────────────────────────────────────
    shutdown_event = threading.Event()

    handler_cls = partial(_ViewerHandler, html=html,
                          shutdown_event=shutdown_event)
    server = HTTPServer(("127.0.0.1", 0), handler_cls)
    port = server.server_address[1]

    server_thread = threading.Thread(target=server.serve_forever,
                                     daemon=True)
    server_thread.start()

    webbrowser.open(f"http://127.0.0.1:{port}")

    # Block until the browser tab fires the /shutdown beacon
    shutdown_event.wait()
    server.shutdown()
    server_thread.join(timeout=2)

Preferences

settings()

apeGmsh.viewers.settings

settings() -> int

Open the global preferences editor (modal dialog).

Persists changes to the JSON file at PreferencesManager.path (platform-appropriate config dir). Spins up a QApplication if none exists.

Returns the dialog result code (QDialog.Accepted / Rejected).

Source code in src/apeGmsh/viewers/__init__.py
def settings() -> int:
    """Open the global preferences editor (modal dialog).

    Persists changes to the JSON file at
    ``PreferencesManager.path`` (platform-appropriate config dir).
    Spins up a ``QApplication`` if none exists.

    Returns the dialog result code (``QDialog.Accepted`` / ``Rejected``).
    """
    from .ui.preferences_dialog import open_preferences_dialog
    return open_preferences_dialog()

theme_editor()

apeGmsh.viewers.theme_editor

theme_editor() -> int

Open the theme editor (modal dialog with live preview).

Custom themes are persisted under ThemeManager.themes_dir() (platform-appropriate config dir). Spins up a QApplication if none exists.

Returns the dialog result code (QDialog.Accepted / Rejected).

Source code in src/apeGmsh/viewers/__init__.py
def theme_editor() -> int:
    """Open the theme editor (modal dialog with live preview).

    Custom themes are persisted under ``ThemeManager.themes_dir()``
    (platform-appropriate config dir). Spins up a ``QApplication`` if
    none exists.

    Returns the dialog result code (``QDialog.Accepted`` / ``Rejected``).
    """
    from .ui.theme_editor_dialog import open_theme_editor
    return open_theme_editor()