Skip to content

aimbat._tui

AIMBAT Terminal User Interface.

Modules:

Name Description
app

AIMBAT Terminal User Interface application.

modals

Modal screens for the AIMBAT TUI.

app

AIMBAT Terminal User Interface application.

Classes:

Name Description
AimbatTUI

AIMBAT Terminal User Interface.

Functions:

Name Description
main

Entry point for the AIMBAT TUI.

AimbatTUI

Bases: App[None]

AIMBAT Terminal User Interface.

Source code in src/aimbat/_tui/app.py
 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
class AimbatTUI(App[None]):
    """AIMBAT Terminal User Interface."""

    TITLE = "AIMBAT"
    CSS_PATH = "aimbat.tcss"

    BINDINGS = [
        Binding("e", "switch_event", "Events", show=True),
        Binding("d", "add_data", "Add Data", show=True),
        Binding("p", "open_parameters", "Parameters", show=True),
        Binding("t", "open_interactive_tools", "Tools", show=True),
        Binding("a", "open_align", "Align", show=True),
        Binding("n", "new_snapshot", "New Snapshot", show=True),
        Binding("r", "refresh", "Refresh", show=True),
        Binding("c", "toggle_theme", "Theme", show=True),
        Binding("?", "show_help", "Help", show=True),
        Binding("H", "vim_left", "Vim left", show=False),
        Binding("L", "vim_right", "Vim right", show=False),
        Binding("q", "quit", "Quit", show=True),
    ]

    def compose(self) -> ComposeResult:
        yield Header()
        yield Static(id="event-bar")
        with TabbedContent(initial="tab-project"):
            with TabPane("Project", id="tab-project"):
                with Horizontal(id="project-layout"):
                    with Vertical(id="project-tables"):
                        yield VimDataTable(id="project-event-table")
                        yield VimDataTable(id="project-station-table")
                    with Vertical(id="project-right-panel"):
                        yield Static(
                            id="project-quality-panel", classes="quality-panel"
                        )
                        yield NoteWidget(id="project-note")
            with TabPane("Live data", id="tab-seismograms"):
                with Horizontal(id="seismogram-layout"):
                    yield VimDataTable(id="seismogram-table")
                    with Vertical(id="seismogram-right-panel"):
                        yield SeismogramPlotWidget(id="seismogram-plot")
                        yield NoteWidget(id="seismogram-note")
            with TabPane("Snapshots", id="tab-snapshots"):
                with Horizontal(id="snapshot-layout"):
                    yield VimDataTable(id="snapshot-table")
                    with Vertical(id="snapshot-right-panel"):
                        yield Static(
                            id="snapshot-quality-panel", classes="quality-panel"
                        )
                        yield NoteWidget(id="snapshot-note")
        yield Footer()

    def on_mount(self) -> None:
        self._bound_iccs: BoundICCS | None = None
        self._iccs_creating: bool = False
        self._iccs_last_modified_seen: Timestamp | None = None
        self._current_event_id: uuid.UUID | None = None
        self._active_tab: str = "tab-project"
        self._highlighted_event_id: str | None = None
        self._highlighted_station_id: str | None = None
        self._highlighted_seismogram_id: str | None = None
        self._highlighted_snapshot_id: str | None = None
        self._quality_source: Literal["event", "station"] = "event"
        self._project_refreshing: bool = False
        self._seismogram_refreshing: bool = False

        self.theme = _DEFAULT_THEME

        self._setup_project_tables()
        self._setup_seismogram_table()
        self._setup_snapshot_table()

        self.set_interval(5, self._check_iccs_staleness)

        logger.info("TUI started.")
        if not _project_exists(engine):
            self.push_screen(NoProjectModal(), self._on_no_project_modal)
        else:
            self._create_iccs()
            self.refresh_all()

    def _on_no_project_modal(self, create: bool | None) -> None:
        if create:
            logger.info("User chose to create a new project.")
            create_project(engine)
            self._create_iccs()
            self.refresh_all()
        else:
            logger.info("User declined to create a project. Exiting.")
            self.exit()

    @on(TabbedContent.TabActivated)
    def on_tab_activated(self, event: TabbedContent.TabActivated) -> None:
        if event.pane.id not in _MAIN_TABS:
            return
        self._active_tab = event.pane.id
        self.refresh_bindings()
        if not isinstance(self.focused, Tabs):
            with suppress(NoMatches):
                event.pane.query_one(DataTable).focus()
        if event.pane.id == "tab-seismograms":
            if self.query_one("#seismogram-table", DataTable).row_count == 0:
                self._update_seismogram_note(None)
                self._update_seismogram_plot(None)
        elif event.pane.id == "tab-snapshots":
            if self.query_one("#snapshot-table", DataTable).row_count == 0:
                self._update_snapshot_quality(None)

    def check_action(self, action: str, parameters: tuple[object, ...]) -> bool | None:
        if action in {
            "open_parameters",
            "open_interactive_tools",
            "open_align",
            "new_snapshot",
        }:
            return self._current_event_id is not None
        return True

    # ------------------------------------------------------------------
    # Event selection
    # ------------------------------------------------------------------

    def _get_current_event(self, session: Session) -> AimbatEvent:
        """Return the event currently selected for processing in the TUI.

        Raises `NoResultFound` when no event has been selected yet.
        Clears a stale `_current_event_id` if the referenced event no longer exists.
        """
        if self._current_event_id is not None:
            event = session.get(AimbatEvent, self._current_event_id)
            if event is not None:
                return event
            self._current_event_id = None
        raise NoResultFound("No event selected")

    # ------------------------------------------------------------------
    # Suspend helper
    # ------------------------------------------------------------------

    @contextmanager
    def _suspend(self, label: str | None = None) -> Generator[None, None, None]:
        """Suspend Textual and handle errors gracefully.

        If `label` is given, a panel is shown with a "close matplotlib to
        return" hint.  Any exception raised inside the block is shown in the
        terminal while still suspended, then re-raised after Textual has fully
        resumed so callers can still react to it.
        """
        console = Console()
        caught: BaseException | None = None
        with self.suspend():
            console.clear()
            if label is not None:
                console.print(
                    Panel(
                        f"[bold]{label}[/bold]\n\n"
                        "Close the matplotlib window to return to AIMBAT.",
                        title="Interactive Tool Running",
                        border_style="bright_blue",
                        padding=(1, 4),
                    )
                )
            try:
                yield
            except Exception as exc:
                caught = exc
                console.print(f"\n[bold red]Error:[/bold red] {exc}")
                console.input("\n[dim]Press Enter to return to AIMBAT...[/dim]")
            finally:
                console.clear()
        if caught is not None:
            raise caught

    # ------------------------------------------------------------------
    # ICCS lifecycle
    # ------------------------------------------------------------------

    def _create_iccs(self) -> None:
        """Discard the existing ICCS instance and create a new one in a background worker.

        ICCS construction reads waveform data, so it must not block the asyncio event loop.
        Concurrent calls are ignored — only one worker runs at a time.
        """
        if self._iccs_creating:
            logger.debug(
                "ICCS creation already in progress; skipping duplicate request."
            )
            return
        self._iccs_creating = True
        self._bound_iccs = None
        self._worker_create_iccs()

    @work(thread=True)
    def _worker_create_iccs(self) -> None:
        """Background worker: create ICCS instance without blocking the UI."""
        try:
            with Session(engine) as session:
                event = self._get_current_event(session)
                bound_iccs = create_iccs_instance(session, event)
        except (NoResultFound, RuntimeError):
            logger.debug("ICCS worker: no event selected or no data; aborting.")
            self.call_from_thread(setattr, self, "_iccs_creating", False)
            return
        except Exception as exc:
            logger.exception(f"ICCS worker: unexpected error during creation: {exc}")
            self.call_from_thread(
                self.notify, f"ICCS init failed: {exc}", severity="error"
            )
            self.call_from_thread(setattr, self, "_iccs_creating", False)
            return
        logger.debug("ICCS worker: instance created successfully.")
        self.call_from_thread(self._assign_iccs, bound_iccs)

    def _assign_iccs(self, bound_iccs: BoundICCS) -> None:
        """Main-thread callback: store the new BoundICCS instance and refresh status."""
        self._iccs_creating = False
        self._bound_iccs = bound_iccs
        logger.info("ICCS instance ready and assigned.")
        self._refresh_event_bar()
        self._refresh_seismograms()

    # ------------------------------------------------------------------
    # Table setup
    # ------------------------------------------------------------------

    def _setup_project_tables(self) -> None:
        et_headers = [
            tui_display_title(AimbatEventRead, f)
            for f in AimbatEventRead.model_fields
            if f not in _EVENT_TABLE_EXCLUDE | {"id"}
        ]
        et = self.query_one("#project-event-table", DataTable)
        et.border_title = "Events"
        et.cursor_type = "row"
        et.add_columns(" ", *et_headers)
        station_headers = [
            tui_display_title(AimbatStationRead, f)
            for f in AimbatStationRead.model_fields
            if f not in _STATION_TABLE_EXCLUDE | {"id"}
        ]
        st = self.query_one("#project-station-table", DataTable)
        st.border_title = "Stations"
        st.cursor_type = "row"
        st.add_columns(*station_headers)

    def _setup_seismogram_table(self) -> None:
        seis_headers = [
            tui_display_title(AimbatSeismogramRead, f)
            for f in AimbatSeismogramRead.model_fields
            if f not in _SEISMOGRAM_TABLE_EXCLUDE | {"id"}
        ]
        t = self.query_one("#seismogram-table", DataTable)
        t.border_title = "Seismograms"
        t.cursor_type = "row"
        t.add_columns(*seis_headers)

    def _setup_snapshot_table(self) -> None:
        snap_headers = [
            tui_display_title(AimbatSnapshotRead, f)
            for f in AimbatSnapshotRead.model_fields
            if f not in _SNAPSHOT_TABLE_EXCLUDE | {"id"}
        ]
        t = self.query_one("#snapshot-table", DataTable)
        t.border_title = "Snapshots"
        t.cursor_type = "row"
        t.add_columns(*snap_headers)

    # ------------------------------------------------------------------
    # Data refresh
    # ------------------------------------------------------------------

    def refresh_all(self) -> None:
        self.refresh_bindings()
        self._refresh_event_bar()
        self._refresh_project()
        self._refresh_seismograms()
        self._refresh_snapshots()

    def _refresh_project(self) -> None:
        et = self.query_one("#project-event-table", DataTable)
        st = self.query_one("#project-station-table", DataTable)
        et_saved, st_saved = et.cursor_row, st.cursor_row
        et.clear()
        st.clear()
        with suppress(NoResultFound, RuntimeError):
            with Session(engine) as session:
                event_rows = dump_event_table(
                    session,
                    from_read_model=True,
                    by_title=True,
                    exclude=_EVENT_TABLE_EXCLUDE,
                )
                station_rows = dump_station_table(
                    session,
                    from_read_model=True,
                    by_title=True,
                    exclude=_STATION_TABLE_EXCLUDE,
                )

            total = len(event_rows)
            completed = sum(1 for r in event_rows if r.get("Completed"))
            et.border_title = (
                f"Events  [dim]{total} total · {completed} completed[/dim]"
            )

            if self._current_event_id is not None:
                active = next(
                    (
                        r
                        for r in event_rows
                        if r.get("ID") == str(self._current_event_id)
                    ),
                    None,
                )
                if active is not None:
                    _sc_key = tui_display_title(AimbatEventRead, "station_count")
                    st.border_title = f"Stations  [dim]{active.get(_sc_key, '?')} in active event[/dim]"

            for row in event_rows:
                row_id = str(row.pop("ID"))
                marker = "▶" if row_id == str(self._current_event_id) else " "
                cells = [tui_cell(AimbatEventRead, k, v) for k, v in row.items()]
                et.add_row(marker, *cells, key=row_id)

            for row in station_rows:
                row_id = str(row.pop("ID"))
                cells = [tui_cell(AimbatStationRead, k, v) for k, v in row.items()]
                st.add_row(*cells, key=row_id)

        self._project_refreshing = True
        if et.row_count > 0:
            et.move_cursor(row=min(et_saved, et.row_count - 1))
        if st.row_count > 0:
            st.move_cursor(row=min(st_saved, st.row_count - 1))
        self.call_after_refresh(self._end_project_refresh)

    def _end_project_refresh(self) -> None:
        """Runs after pending RowHighlighted events from move_cursor have been processed."""
        self._project_refreshing = False
        if self._quality_source == "station":
            self._update_station_quality(self._highlighted_station_id)
        else:
            self._update_event_quality(self._highlighted_event_id)

    def _end_seismogram_refresh(self) -> None:
        """Runs after pending RowHighlighted events from move_cursor have been processed."""
        self._seismogram_refreshing = False
        self._update_seismogram_note(self._highlighted_seismogram_id)
        self._update_seismogram_plot(self._highlighted_seismogram_id)

    def _check_iccs_staleness(self) -> None:
        """Trigger ICCS recreation if the current event has been modified externally.

        When ICCS creation previously failed (e.g. due to an invalid parameter set via
        the CLI), retries whenever `event.last_modified` changes. On any detected
        change the full UI is refreshed so panels reflect the new DB state immediately.
        """
        try:
            with Session(engine) as session:
                event = self._get_current_event(session)
                last_modified = event.last_modified
                stale = (
                    self._bound_iccs.is_stale(event)
                    if self._bound_iccs is not None
                    else last_modified != self._iccs_last_modified_seen
                )
        except (NoResultFound, RuntimeError):
            return
        if stale:
            logger.debug(
                "ICCS staleness detected; recreating instance and refreshing UI."
            )
            self._iccs_last_modified_seen = last_modified
            self._create_iccs()
            self.refresh_all()

    def _refresh_event_bar(self) -> None:
        bar = self.query_one("#event-bar", Static)
        try:
            with Session(engine) as session:
                event = self._get_current_event(session)
                iccs_status = (
                    " ● ICCS ready" if self._bound_iccs is not None else " ○ no ICCS"
                )
                time_str = str(event.time)[:19] if event.time else "unknown"
                lat = f"{event.latitude:.3f}°" if event.latitude is not None else "?"
                lon = f"{event.longitude:.3f}°" if event.longitude is not None else "?"
                modified = (
                    f"  modified: {str(event.last_modified)[:19]}"
                    if event.last_modified is not None
                    else ""
                )
                bar.update(
                    f"▶ {time_str}  |  {lat}, {lon}{modified}"
                    f"  [dim]{iccs_status}  e = switch event[/dim]"
                )
        except NoResultFound:
            with Session(engine) as session:
                has_events = session.exec(select(AimbatEvent)).first() is not None
            if has_events:
                bar.update("[red]No event selected — press e to select one[/red]")
            else:
                bar.update("[red]No data in project — press d to add data[/red]")
        except RuntimeError as exc:
            bar.update(f"[red]{exc}[/red]")

    def _refresh_seismograms(self) -> None:
        table = self.query_one("#seismogram-table", DataTable)
        saved_row = table.cursor_row
        table.clear()

        live_cc_map: dict[str, float] = {}
        if self._bound_iccs is not None:
            with suppress(AttributeError, ValueError):
                for iccs_seis, cc in zip(
                    self._bound_iccs.iccs.seismograms, self._bound_iccs.iccs.ccs
                ):
                    live_cc_map[str(iccs_seis.extra["id"])] = float(cc)

        all_ccs: list[float] = []
        selected_ccs: list[float] = []

        with suppress(NoResultFound, RuntimeError):
            with Session(engine) as session:
                event = self._get_current_event(session)
                rows = dump_seismogram_table(
                    session,
                    from_read_model=True,
                    by_title=True,
                    exclude=_SEISMOGRAM_TABLE_EXCLUDE,
                    event_id=event.id,
                )

            for row in rows:
                seis_id = str(row["ID"])
                if seis_id in live_cc_map:
                    row["Stack CC"] = live_cc_map[seis_id]

            rows.sort(
                key=lambda r: r["Stack CC"] if r.get("Stack CC") is not None else -2.0,
                reverse=True,
            )

            for row in rows:
                cc_val = row.get("Stack CC")
                if cc_val is not None:
                    all_ccs.append(float(cc_val))
                    if row.get("Select"):
                        selected_ccs.append(float(cc_val))
                row_id = str(row.pop("ID"))
                cells = [tui_cell(AimbatSeismogramRead, k, v) for k, v in row.items()]
                table.add_row(*cells, key=row_id)

        if all_ccs:
            n_all = len(all_ccs)
            mean_all = statistics.mean(all_ccs)
            sem_all = statistics.stdev(all_ccs) / n_all**0.5 if n_all >= 2 else None
            n_sel = len(selected_ccs)
            mean_sel = statistics.mean(selected_ccs) if selected_ccs else None
            sem_sel = (
                statistics.stdev(selected_ccs) / n_sel**0.5 if n_sel >= 2 else None
            )
            table.border_title = (
                f"Seismograms  [dim]CC: selected {fmt_float_sem(mean_sel, sem_sel)}"
                f" · all {fmt_float_sem(mean_all, sem_all)}[/dim]"
            )
        else:
            table.border_title = "Seismograms"

        self._seismogram_refreshing = True
        if table.row_count > 0:
            table.move_cursor(row=min(saved_row, table.row_count - 1))
            self.call_after_refresh(self._end_seismogram_refresh)
        else:
            self._highlighted_seismogram_id = None
            self._seismogram_refreshing = False
            self._update_seismogram_note(None)
            self._update_seismogram_plot(None)

    def _refresh_snapshots(self) -> None:
        table = self.query_one("#snapshot-table", DataTable)
        saved_row = table.cursor_row
        table.clear()
        with suppress(NoResultFound, RuntimeError):
            with Session(engine) as session:
                event = self._get_current_event(session)
                snapshots = dump_snapshot_table(
                    session,
                    from_read_model=True,
                    by_title=True,
                    exclude=_SNAPSHOT_TABLE_EXCLUDE,
                    event_id=event.id,
                )
            for row in snapshots:
                row_id = str(row.pop("ID"))
                cells = [tui_cell(AimbatSnapshotRead, k, v) for k, v in row.items()]
                table.add_row(*cells, key=row_id)
        if table.row_count > 0:
            table.move_cursor(row=min(saved_row, table.row_count - 1))
        else:
            self._highlighted_snapshot_id = None
        self.call_after_refresh(
            lambda: self._update_snapshot_quality(self._highlighted_snapshot_id)
        )

    # ------------------------------------------------------------------
    # Row event handlers
    # ------------------------------------------------------------------

    @on(DataTable.RowSelected, "#project-event-table")
    def project_event_row_selected(self, event: DataTable.RowSelected) -> None:
        if event.row_key.value:
            self._open_row_action_menu(
                "project-events",
                event.row_key.value,
                f"Event  {event.row_key.value[:8]}",
            )

    @on(DataTable.RowSelected, "#project-station-table")
    def project_station_row_selected(self, event: DataTable.RowSelected) -> None:
        if event.row_key.value:
            self._open_row_action_menu(
                "project-stations",
                event.row_key.value,
                f"Station  {event.row_key.value[:8]}",
            )

    @on(DataTable.RowSelected, "#seismogram-table")
    def seismogram_row_selected(self, event: DataTable.RowSelected) -> None:
        if event.row_key.value:
            self._open_row_action_menu(
                "tab-seismograms",
                event.row_key.value,
                f"Seismogram  {event.row_key.value[:8]}",
            )

    @on(DataTable.RowSelected, "#snapshot-table")
    def snapshot_row_selected(self, event: DataTable.RowSelected) -> None:
        snap_id = event.row_key.value
        if not snap_id:
            return

        def on_action(result: tuple[str, bool, bool] | None) -> None:
            if result is None:
                return
            action, context, all_seis = result
            if action == "preview_stack":
                self._preview_snapshot_plot(snap_id, "stack", context, all_seis)
            elif action == "preview_image":
                self._preview_snapshot_plot(snap_id, "image", context, all_seis)
            elif action == "save_results":
                self._save_snapshot_results(snap_id)
            else:
                self._handle_row_action("tab-snapshots", snap_id, action)

        self.push_screen(SnapshotActionMenuModal(f"Snapshot  {snap_id[:8]}"), on_action)

    @on(DataTable.RowHighlighted, "#project-event-table")
    def project_event_row_highlighted(self, event: DataTable.RowHighlighted) -> None:
        self._highlighted_event_id = event.row_key.value if event.row_key else None
        if not self._project_refreshing:
            self._quality_source = "event"
            self._update_event_quality(self._highlighted_event_id)

    @on(DataTable.RowHighlighted, "#project-station-table")
    def project_station_row_highlighted(self, event: DataTable.RowHighlighted) -> None:
        self._highlighted_station_id = event.row_key.value if event.row_key else None
        if not self._project_refreshing:
            self._quality_source = "station"
            self._update_station_quality(self._highlighted_station_id)

    @on(VimDataTable.Focused, "#project-event-table")
    def _project_event_table_focused(self) -> None:
        if not self._project_refreshing:
            self._quality_source = "event"
            self._update_event_quality(self._highlighted_event_id)

    @on(VimDataTable.Focused, "#project-station-table")
    def _project_station_table_focused(self) -> None:
        if not self._project_refreshing:
            self._quality_source = "station"
            self._update_station_quality(self._highlighted_station_id)

    @on(DataTable.RowHighlighted, "#seismogram-table")
    def seismogram_row_highlighted(self, event: DataTable.RowHighlighted) -> None:
        self._highlighted_seismogram_id = event.row_key.value if event.row_key else None
        if not self._seismogram_refreshing:
            self._update_seismogram_note(self._highlighted_seismogram_id)
            self._update_seismogram_plot(self._highlighted_seismogram_id)

    @on(DataTable.RowHighlighted, "#snapshot-table")
    def snapshot_row_highlighted(self, event: DataTable.RowHighlighted) -> None:
        self._highlighted_snapshot_id = event.row_key.value if event.row_key else None
        self._update_snapshot_quality(self._highlighted_snapshot_id)

    # ------------------------------------------------------------------
    # Quality panel updates
    # ------------------------------------------------------------------

    def _update_event_quality(self, item_id: str | None) -> None:
        panel = self.query_one("#project-quality-panel", Static)
        panel.border_title = "Live event statistics"
        stats = None
        if item_id is not None:
            try:
                with Session(engine) as session:
                    stats = get_event_quality(session, uuid.UUID(item_id))
            except (ValueError, SQLAlchemyError):
                pass
        body, subtitle = format_quality_panel(stats)
        panel.update(body)
        panel.border_subtitle = subtitle
        note_widget = self.query_one("#project-note", NoteWidget)
        if item_id is None:
            note_widget.clear()
        else:
            with suppress(ValueError):
                note_widget.set_entity("event", uuid.UUID(item_id))

    def _update_station_quality(self, item_id: str | None) -> None:
        panel = self.query_one("#project-quality-panel", Static)
        panel.border_title = "Live station statistics"
        stats = None
        if item_id is not None:
            try:
                with Session(engine) as session:
                    stats = get_station_quality(session, uuid.UUID(item_id))
            except (ValueError, SQLAlchemyError):
                pass
        body, subtitle = format_quality_panel(stats)
        panel.update(body)
        panel.border_subtitle = subtitle
        note_widget = self.query_one("#project-note", NoteWidget)
        if item_id is None:
            note_widget.clear()
        else:
            with suppress(ValueError):
                note_widget.set_entity("station", uuid.UUID(item_id))

    def _update_seismogram_note(self, item_id: str | None) -> None:
        note_widget = self.query_one("#seismogram-note", NoteWidget)
        if item_id is None:
            note_widget.clear()
        else:
            with suppress(ValueError):
                note_widget.set_entity("seismogram", uuid.UUID(item_id))

    def _update_seismogram_plot(self, item_id: str | None) -> None:
        try:
            plot_widget = self.query_one("#seismogram-plot", SeismogramPlotWidget)
        except NoMatches:
            return
        if item_id is None or self._bound_iccs is None:
            plot_widget.clear()
            return
        seis_uuid = uuid.UUID(item_id)
        iccs = self._bound_iccs.iccs
        idx = next(
            (
                i
                for i, s in enumerate(iccs.seismograms)
                if s.extra.get("id") == seis_uuid
            ),
            None,
        )
        if idx is None:
            plot_widget.clear()
            return
        parent = iccs.seismograms[idx]
        pick = parent.t1 if parent.t1 is not None else parent.t0
        try:
            cc_seis = iccs.cc_seismograms[idx]
            ctx_seis = iccs.context_seismograms[idx]
        except Exception:
            plot_widget.clear()
            return
        pick_ns: int = pick.value
        cc_n = len(cc_seis.data)
        cc_times = (
            (
                cc_seis.begin_time.value
                + np.arange(cc_n, dtype=np.int64) * cc_seis.delta.value
                - pick_ns
            )
            / 1e9
        ).tolist()
        ctx_n = len(ctx_seis.data)
        ctx_times = (
            (
                ctx_seis.begin_time.value
                + np.arange(ctx_n, dtype=np.int64) * ctx_seis.delta.value
                - pick_ns
            )
            / 1e9
        ).tolist()
        plot_widget.update_plots(
            cc_times,
            cc_seis.data.tolist(),
            ctx_times,
            ctx_seis.data.tolist(),
        )

    def _update_snapshot_quality(self, item_id: str | None) -> None:
        panel = self.query_one("#snapshot-quality-panel", Static)
        panel.border_title = "Snapshot statistics"
        stats = None
        if item_id is not None:
            try:
                with Session(engine) as session:
                    stats = get_snapshot_quality(session, uuid.UUID(item_id))
            except (ValueError, SQLAlchemyError):
                pass
        body, subtitle = format_quality_panel(stats)
        panel.update(body)
        panel.border_subtitle = subtitle
        note_widget = self.query_one("#snapshot-note", NoteWidget)
        if item_id is None:
            note_widget.clear()
        else:
            with suppress(ValueError):
                note_widget.set_entity("snapshot", uuid.UUID(item_id))

    # ------------------------------------------------------------------
    # Row-action menu helpers
    # ------------------------------------------------------------------

    def _open_row_action_menu(self, tab: str, item_id: str, title: str) -> None:
        actions = _TAB_ROW_ACTIONS.get(tab, [])
        if not actions:
            return

        def on_action(action: str | None) -> None:
            self._handle_row_action(tab, item_id, action)

        self.push_screen(ActionMenuModal(title, actions), on_action)

    def _handle_row_action(self, tab: str, item_id: str, action: str | None) -> None:
        if action == "delete":
            self._confirm_delete(tab, item_id)
        elif action == "select":
            self._select_event(item_id)
        elif action == "toggle_completed":
            self._toggle_event_completed(item_id)
        elif action == "view_seismograms":
            self._view_seismograms(tab, item_id)
        elif action == "rollback":
            self._confirm_rollback(item_id)
        elif action == "show_details":
            self._show_snapshot_details(item_id)
        elif action == "toggle_select":
            self._toggle_seismogram_bool(item_id, SeismogramParameter.SELECT)
        elif action == "toggle_flip":
            self._toggle_seismogram_bool(item_id, SeismogramParameter.FLIP)
        elif action == "reset":
            self._reset_seismogram_parameters(item_id)

    def _select_event(self, item_id: str) -> None:
        logger.debug(f"User selected event {item_id[:8]}.")
        self._current_event_id = uuid.UUID(item_id)
        self._create_iccs()
        self.refresh_all()
        self.notify("Event selected", timeout=2)

    def _toggle_event_completed(self, item_id: str) -> None:
        logger.debug(f"User toggled completed flag for event {item_id[:8]}.")
        try:
            with Session(engine) as session:
                event = session.get(AimbatEvent, uuid.UUID(item_id))
                if event is None:
                    return
                event.parameters.completed = not event.parameters.completed
                session.add(event)
                session.commit()
            self._refresh_project()
            self.notify("Completed flag toggled", timeout=2)
        except Exception as exc:
            self.notify(str(exc), severity="error")

    def _view_seismograms(self, tab: str, item_id: str) -> None:
        item_uuid = uuid.UUID(item_id)
        try:
            with self._suspend("View seismograms"):
                with Session(engine) as session:
                    if tab == "project-events":
                        event = session.get(AimbatEvent, item_uuid)
                        if event is None:
                            return
                        plot_seismograms(session, event, return_fig=False)
                    else:
                        station = session.get(AimbatStation, item_uuid)
                        if station is None:
                            return
                        plot_seismograms(session, station, return_fig=False)
        except Exception as exc:
            self.notify(str(exc), severity="error")

    def _toggle_seismogram_bool(self, item_id: str, param: SeismogramParameter) -> None:
        logger.debug(f"User toggled {param} for seismogram {item_id[:8]}.")
        try:
            seis_uuid = uuid.UUID(item_id)
            with Session(engine) as session:
                seis = session.get(AimbatSeismogram, seis_uuid)
                if seis is None:
                    raise ValueError(f"Seismogram {item_id} not found")
                new_value = not getattr(seis.parameters, param)
                setattr(seis.parameters, param, new_value)
                session.add(seis)
                session.commit()
            if self._bound_iccs is not None:
                for iccs_seis in self._bound_iccs.iccs.seismograms:
                    if iccs_seis.extra.get("id") == seis_uuid:
                        setattr(iccs_seis, param, new_value)
                        self._bound_iccs.iccs.clear_cache()
                        self._bound_iccs.created_at = Timestamp.now("UTC")
                        break
            self._refresh_seismograms()
            self.notify(f"{param} toggled", timeout=2)
        except Exception as exc:
            self.notify(str(exc), severity="error")

    def _reset_seismogram_parameters(self, item_id: str) -> None:
        logger.debug(f"User reset parameters for seismogram {item_id[:8]}.")
        try:
            with Session(engine) as session:
                reset_seismogram_parameters(session, uuid.UUID(item_id))
            self.refresh_all()
            self.notify("Seismogram parameters reset", timeout=2)
        except Exception as exc:
            self.notify(str(exc), severity="error")

    def _confirm_delete(self, tab: str, item_id: str) -> None:
        messages = {
            "project-events": "Delete this event and all its data?",
            "project-stations": "Delete this station and all its seismograms?",
            "tab-seismograms": "Delete this seismogram?",
            "tab-snapshots": "Delete this snapshot?",
        }
        msg = messages.get(tab)
        if not msg:
            return

        def on_confirm(confirmed: bool | None) -> None:
            if not confirmed:
                return
            try:
                if tab == "project-events":
                    logger.info(f"User confirmed deletion of event {item_id[:8]}.")
                    with Session(engine) as session:
                        delete_event(session, uuid.UUID(item_id))
                    if self._current_event_id == uuid.UUID(item_id):
                        self._current_event_id = None
                        self._bound_iccs = None
                    self.refresh_all()
                    self.notify("Event deleted", timeout=2)
                elif tab == "project-stations":
                    logger.info(f"User confirmed deletion of station {item_id[:8]}.")
                    with Session(engine) as session:
                        delete_station(session, uuid.UUID(item_id))
                    self._create_iccs()
                    self.refresh_all()
                    self.notify("Station deleted", timeout=2)
                elif tab == "tab-seismograms":
                    logger.info(f"User confirmed deletion of seismogram {item_id[:8]}.")
                    with Session(engine) as session:
                        delete_seismogram(session, uuid.UUID(item_id))
                    self._create_iccs()
                    self.refresh_all()
                    self.notify("Seismogram deleted", timeout=2)
                elif tab == "tab-snapshots":
                    logger.info(f"User confirmed deletion of snapshot {item_id[:8]}.")
                    with Session(engine) as session:
                        delete_snapshot(session, uuid.UUID(item_id))
                    self._refresh_snapshots()
                    self.notify("Snapshot deleted", timeout=2)
            except Exception as exc:
                logger.exception(f"Deletion failed: {exc}")
                self.notify(str(exc), severity="error")

        self.push_screen(ConfirmModal(msg), on_confirm)

    def _show_snapshot_details(self, snap_id: str) -> None:
        try:
            with Session(engine) as session:
                snap = session.get(AimbatSnapshot, uuid.UUID(snap_id))
                if snap is None:
                    return
                p = snap.event_parameters_snapshot
                rows: list[tuple[str, str]] = []
                for attr, field_info in AimbatEventParametersBase.model_fields.items():
                    value = getattr(p, attr)
                    if isinstance(value, bool):
                        display = "✓" if value else "✗"
                    elif isinstance(value, Timedelta):
                        display = f"{value.total_seconds():.2f}"
                    else:
                        display = f"{value}"
                    label = field_info.title or attr
                    rows.append((label, display))
            self.push_screen(SnapshotDetailsModal(f"Snapshot  {snap_id[:8]}", rows))
        except Exception as exc:
            self.notify(str(exc), severity="error")

    def _save_snapshot_results(self, snap_id: str) -> None:
        default_name = f"results_{snap_id[:8]}.json"

        def on_path(path: Path | None) -> None:
            if path is None:
                return
            import json

            try:
                with Session(engine) as session:
                    data = dump_snapshot_results(session, uuid.UUID(snap_id))
                path.write_text(json.dumps(data, indent=2), encoding="utf-8")
                logger.info(f"Snapshot results saved to {path}.")
                self.notify(f"Results saved to {path.name}", timeout=3)
            except Exception as exc:
                logger.exception(f"Failed to save snapshot results: {exc}")
                self.notify(str(exc), severity="error")

        self.push_screen(
            FileSave(".", title="Save results", default_file=default_name), on_path
        )

    def _preview_snapshot_plot(
        self, snap_id: str, plot_type: str, context: bool, all_seis: bool
    ) -> None:
        logger.debug(f"User previewing {plot_type} plot for snapshot {snap_id[:8]}.")
        try:
            with self._suspend("Previewing snapshot"):
                with Session(engine) as session:
                    bound = build_iccs_from_snapshot(session, uuid.UUID(snap_id))
                if plot_type == "stack":
                    plot_stack(bound.iccs, context, all_seis, return_fig=False)
                else:
                    plot_matrix_image(bound.iccs, context, all_seis, return_fig=False)
        except Exception as exc:
            logger.exception(f"Snapshot preview failed: {exc}")
            self.notify(str(exc), severity="error")

    def _confirm_rollback(self, snap_id: str) -> None:
        def on_confirm(confirmed: bool | None) -> None:
            if not confirmed:
                return
            try:
                logger.info(f"User confirmed rollback to snapshot {snap_id[:8]}.")
                with Session(engine) as session:
                    rollback_to_snapshot(session, uuid.UUID(snap_id))
                self._create_iccs()
                self.refresh_all()
                if self._active_tab == "tab-snapshots":
                    self.query_one(TabbedContent).active = "tab-seismograms"
                self.notify("Rolled back to snapshot", timeout=3)
            except Exception as exc:
                logger.exception(f"Rollback failed: {exc}")
                self.notify(str(exc), severity="error")

        self.push_screen(ConfirmModal("Roll back to this snapshot?"), on_confirm)

    # ------------------------------------------------------------------
    # Actions
    # ------------------------------------------------------------------

    def action_open_parameters(self) -> None:
        logger.debug("User opened parameters modal.")
        try:
            with Session(engine) as session:
                event = self._get_current_event(session)
                event_id = event.id
        except NoResultFound:
            self.notify("No event selected — press e to select one", severity="warning")
            return

        def on_close(changed: bool | None) -> None:
            if changed:
                logger.info("Parameters changed; recreating ICCS.")
                self._create_iccs()
                self.refresh_all()

        self.push_screen(ParametersModal(event_id), on_close)

    def action_switch_event(self) -> None:
        def on_result(result: uuid.UUID | None) -> None:
            if result is not None:
                logger.debug(f"User switched to event {str(result)[:8]}.")
                self._current_event_id = result
                self._create_iccs()
            self.refresh_all()

        self.push_screen(EventSwitcherModal(self._current_event_id), on_result)

    def action_add_data(self) -> None:
        actions = [(dt.value, dt.name.replace("_", " ")) for dt in DataType]

        def on_type(selected: str | None) -> None:
            if selected is None:
                return
            data_type = DataType(selected)
            suffixes = DATATYPE_SUFFIXES[data_type]
            label = data_type.name.replace("_", " ")

            def on_file(path: Path | None) -> None:
                if path is None:
                    return
                try:
                    with Session(engine) as session:
                        add_data_to_project(
                            session, [path], data_type, disable_progress_bar=True
                        )
                        session.commit()
                    logger.info(f"User added data file: {path}.")
                    self.notify(f"Added: {path.name}", severity="information")
                    self.refresh_all()
                except Exception as exc:
                    logger.exception(f"Failed to add data file {path}: {exc}")
                    self.notify(str(exc), severity="error")

            self.push_screen(
                FileOpen(
                    ".",
                    title=f"Add {label}",
                    filters=Filters(
                        (f"{label} files", lambda p: p.suffix.lower() in suffixes),
                        ("All files", lambda _: True),
                    ),
                ),
                on_file,
            )

        self.push_screen(ActionMenuModal("Add Data", actions), on_type)

    def _require_iccs(self) -> bool:
        """Return True if ICCS is ready; show a contextual warning and return False otherwise."""
        if self._bound_iccs is not None:
            return True
        if self._current_event_id is not None:
            self.notify(
                "ICCS not ready — check event parameters (Parameters tab)",
                severity="warning",
            )
        else:
            self.notify("No event selected — press e to select one", severity="warning")
        return False

    def action_open_interactive_tools(self) -> None:
        if not self._require_iccs():
            return

        def on_result(result: tuple[str, bool, bool] | None) -> None:
            if result is not None:
                self._run_tool(*result)

        self.push_screen(InteractiveToolsModal(), on_result)

    def _run_tool(self, tool: str, context: bool, all_seis: bool) -> None:
        """Run an interactive tool, suspending Textual while matplotlib is active.

        Uses the long-lived ICCS instance (waveform data already loaded) and runs
        matplotlib on the main thread via App.suspend(), which is the correct
        Textual pattern for blocking terminal-adjacent processes.
        """
        logger.debug(
            f"User launched interactive tool '{tool}' (context={context}, all_seis={all_seis})."
        )
        if self._bound_iccs is None:
            self.notify("ICCS not ready — please wait", severity="warning")
            return
        label, fn = _TOOL_REGISTRY[tool]
        iccs = self._bound_iccs.iccs

        try:
            with self._suspend(label):
                with Session(engine) as session:
                    event = self._get_current_event(session)
                    fn(session, event, iccs, context, all_seis)
        except Exception as exc:
            logger.exception(f"Interactive tool '{tool}' raised: {exc}")
            self.notify(str(exc), severity="error")
            return

        self._bound_iccs.created_at = Timestamp.now("UTC")
        self._refresh_seismograms()
        self._refresh_event_bar()
        self.notify("Done", timeout=2)

    def action_open_align(self) -> None:
        if not self._require_iccs():
            return

        def on_result(result: tuple[str, bool, bool, bool] | None) -> None:
            if result is not None:
                self._run_align_tool(self._bound_iccs, *result)

        self.push_screen(AlignModal(), on_result)

    @work(thread=True)
    def _run_align_tool(
        self,
        bound: BoundICCS,
        algorithm: str,
        autoflip: bool,
        autoselect: bool,
        all_seis: bool,
    ) -> None:
        """Run ICCS or MCCC in a background thread."""
        logger.debug(
            f"Alignment worker starting: {algorithm=}, {autoflip=}, {autoselect=}, {all_seis=}."
        )
        notify_msg = "Alignment complete"
        notify_severity: Literal["information", "warning", "error"] = "information"
        try:
            with Session(engine) as session:
                event = self._get_current_event(session)
                if algorithm == "iccs":
                    result = run_iccs(session, event, bound.iccs, autoflip, autoselect)
                    n = len(result.convergence)
                    status = "converged" if result.converged else "did not converge"
                    noun = "iteration" if n == 1 else "iterations"
                    notify_msg = f"ICCS {status} after {n} {noun}"
                    notify_severity = "information" if result.converged else "warning"
                elif algorithm == "mccc":
                    run_mccc(session, event, bound.iccs, all_seis)
                    notify_msg = "MCCC complete"
        except Exception as exc:
            logger.exception(f"Alignment worker error ({algorithm}): {exc}")
            self.call_from_thread(self.notify, str(exc), severity="error")
            return
        self.call_from_thread(self._post_align_complete, notify_msg, notify_severity)

    def _post_align_complete(
        self, msg: str, severity: Literal["information", "warning", "error"]
    ) -> None:
        # Acknowledge our own writes (t1/flip/select written back by ICCS/MCCC)
        # so the staleness check doesn't recreate an ICCS we just ran.
        if self._bound_iccs is not None:
            self._bound_iccs.created_at = Timestamp.now("UTC")
        self.refresh_all()
        self.notify(msg, severity=severity, timeout=4)

    def action_new_snapshot(self) -> None:
        def on_comment(comment: str | None) -> None:
            if comment is None:
                return
            try:
                logger.info(f"User creating snapshot with comment={comment!r}.")
                with Session(engine) as session:
                    event = self._get_current_event(session)
                    create_snapshot(session, event, comment or None)
                self._refresh_snapshots()
                self.notify("Snapshot created", timeout=2)
            except Exception as exc:
                logger.exception(f"Snapshot creation failed: {exc}")
                self.notify(str(exc), severity="error")

        self.push_screen(SnapshotCommentModal(), on_comment)

    def action_vim_left(self) -> None:
        if not isinstance(self.screen, ModalScreen):
            self.query_one(TabbedContent).query_one(Tabs).action_previous_tab()

    def action_vim_right(self) -> None:
        if not isinstance(self.screen, ModalScreen):
            self.query_one(TabbedContent).query_one(Tabs).action_next_tab()

    def action_toggle_theme(self) -> None:
        self.theme = _LIGHT_THEME if self.theme == _DEFAULT_THEME else _DEFAULT_THEME

    def action_show_help(self) -> None:
        self.push_screen(HelpModal(self._active_tab))

    def action_refresh(self) -> None:
        logger.debug("User triggered manual refresh.")
        self.refresh_all()
        self.notify("Refreshed", timeout=1)

main

main() -> None

Entry point for the AIMBAT TUI.

Source code in src/aimbat/_tui/app.py
def main() -> None:
    """Entry point for the AIMBAT TUI."""
    AimbatTUI().run()

modals

Modal screens for the AIMBAT TUI.

Classes:

Name Description
ActionMenuModal

Generic context-action menu for a selected table row.

AlignModal

Menu for running ICCS or MCCC alignment.

ConfirmModal

Generic yes/no confirmation dialog.

EventSwitcherModal

Modal screen for selecting a seismic event to process.

HelpModal

Modal screen showing keyboard help for the current TUI tab.

InteractiveToolsModal

Menu for launching interactive matplotlib tools.

NoProjectModal

Shown on startup when no project exists.

ParameterInputModal

Modal for entering a new numeric/timedelta parameter value.

ParametersModal

View and edit all event processing parameters inline.

SnapshotActionMenuModal

Action menu for a snapshot row.

SnapshotCommentModal

Prompt for an optional snapshot comment.

SnapshotDetailsModal

Read-only view of the event parameters captured in a snapshot.

ActionMenuModal

Bases: ModalScreen[str | None]

Generic context-action menu for a selected table row.

Dismisses with the chosen action key, or None on cancel.

Methods:

Name Description
__init__

Initialise the modal.

Source code in src/aimbat/_tui/modals.py
class ActionMenuModal(ModalScreen[str | None]):
    """Generic context-action menu for a selected table row.

    Dismisses with the chosen action key, or None on cancel.
    """

    BINDINGS = [
        Binding("escape", "cancel", show=False),
    ]

    def __init__(self, title: str, actions: list[tuple[str, str]]) -> None:
        """Initialise the modal.

        Args:
            title: Heading displayed at the top of the menu.
            actions: List of `(action_key, display_label)` pairs shown as rows.
        """
        super().__init__()
        self._title = title
        self._actions = actions  # [(action_key, display_label), ...]

    def compose(self) -> ComposeResult:
        with Container(id="action-menu-dialog"):
            yield Label(self._title, classes=_CSS.TITLE)
            yield VimDataTable(id="action-table", show_header=False)
            yield Label(
                _Hint.NAVIGATE_SELECT_CANCEL,
                classes=_CSS.HINT,
            )

    def on_mount(self) -> None:
        table = self.query_one(DataTable)
        table.cursor_type = "row"
        table.add_column("action")
        for key, label in self._actions:
            table.add_row(label, key=key)
        table.styles.height = len(self._actions)
        table.focus()

    @on(DataTable.RowSelected)
    def row_selected(self, event: DataTable.RowSelected) -> None:
        self.dismiss(event.row_key.value)

    def action_select(self) -> None:
        self.query_one(DataTable).action_select_cursor()

    def action_cancel(self) -> None:
        self.dismiss(None)

__init__

__init__(
    title: str, actions: list[tuple[str, str]]
) -> None

Initialise the modal.

Parameters:

Name Type Description Default
title str

Heading displayed at the top of the menu.

required
actions list[tuple[str, str]]

List of (action_key, display_label) pairs shown as rows.

required
Source code in src/aimbat/_tui/modals.py
def __init__(self, title: str, actions: list[tuple[str, str]]) -> None:
    """Initialise the modal.

    Args:
        title: Heading displayed at the top of the menu.
        actions: List of `(action_key, display_label)` pairs shown as rows.
    """
    super().__init__()
    self._title = title
    self._actions = actions  # [(action_key, display_label), ...]

AlignModal

Bases: ModalScreen[tuple[str, bool, bool, bool] | None]

Menu for running ICCS or MCCC alignment.

Dismisses with (algorithm, autoflip, autoselect, all_seismograms) or None. ICCS options: autoflip (f), autoselect (s). MCCC options: all seismograms (a).

Source code in src/aimbat/_tui/modals.py
class AlignModal(ModalScreen[tuple[str, bool, bool, bool] | None]):
    """Menu for running ICCS or MCCC alignment.

    Dismisses with (algorithm, autoflip, autoselect, all_seismograms) or None.
    ICCS options: autoflip (f), autoselect (s).
    MCCC options: all seismograms (a).
    """

    BINDINGS = [
        Binding("escape", "cancel", "Cancel", show=False),
        Binding("f", "toggle_autoflip", "Autoflip", show=False),
        Binding("s", "toggle_autoselect", "Autoselect", show=False),
        Binding("a", "toggle_all", "All", show=False),
    ]

    def __init__(self) -> None:
        super().__init__()
        self._autoflip = False
        self._autoselect = False
        self._all_seis = False
        self._highlighted_algorithm: str = "iccs"

    def compose(self) -> ComposeResult:
        with Container(id="align-dialog"):
            yield Label("Align Seismograms", classes=_CSS.TITLE)
            yield VimDataTable(id="align-table", show_header=False)
            yield Static(id="align-options")
            yield Label(
                _Hint.NAVIGATE_RUN_CANCEL,
                classes=_CSS.HINT,
            )

    def on_mount(self) -> None:
        table = self.query_one("#align-table", DataTable)
        table.cursor_type = "row"
        table.add_column("algorithm")
        for key, label in _ALIGN_ALGORITHMS:
            table.add_row(label, key=key)
        self._update_options()
        table.focus()

    def _update_options(self) -> None:
        """Refresh the algorithm-specific option toggles."""
        opts = self.query_one("#align-options", Static)
        if self._highlighted_algorithm == "iccs":
            fl = "✓" if self._autoflip else "✗"
            sl = "✓" if self._autoselect else "✗"
            opts.update(
                f"  [@click='screen.toggle_autoflip'][dim]f[/dim] Autoflip: {fl}[/]"
                f"   [@click='screen.toggle_autoselect'][dim]s[/dim] Autoselect: {sl}[/]"
            )
        else:
            al = "✓" if self._all_seis else "✗"
            opts.update(
                f"  [@click='screen.toggle_all'][dim]a[/dim] All seismograms: {al}[/]"
            )

    @on(DataTable.RowHighlighted, "#align-table")
    def row_highlighted(self, event: DataTable.RowHighlighted) -> None:
        self._highlighted_algorithm = event.row_key.value or "iccs"
        self._update_options()

    @on(DataTable.RowSelected, "#align-table")
    def row_selected(self, event: DataTable.RowSelected) -> None:
        key = event.row_key.value
        if key:
            self.dismiss((key, self._autoflip, self._autoselect, self._all_seis))

    def action_toggle_autoflip(self) -> None:
        if self._highlighted_algorithm == "iccs":
            self._autoflip = not self._autoflip
            self._update_options()

    def action_toggle_autoselect(self) -> None:
        if self._highlighted_algorithm == "iccs":
            self._autoselect = not self._autoselect
            self._update_options()

    def action_toggle_all(self) -> None:
        if self._highlighted_algorithm == "mccc":
            self._all_seis = not self._all_seis
            self._update_options()

    def action_select(self) -> None:
        self.query_one(DataTable).action_select_cursor()

    def action_cancel(self) -> None:
        self.dismiss(None)

ConfirmModal

Bases: ModalScreen[bool | None]

Generic yes/no confirmation dialog.

Dismisses True on confirm, False on cancel.

Methods:

Name Description
__init__

Initialise the modal.

Source code in src/aimbat/_tui/modals.py
class ConfirmModal(ModalScreen[bool | None]):
    """Generic yes/no confirmation dialog.

    Dismisses True on confirm, False on cancel.
    """

    BINDINGS = [
        Binding("y", "confirm", show=False),
        Binding("enter", "confirm", show=False),
        Binding("n", "cancel", show=False),
        Binding("escape", "cancel", show=False),
    ]

    def __init__(self, message: str) -> None:
        """Initialise the modal.

        Args:
            message: Confirmation prompt displayed to the user.
        """
        super().__init__()
        self._message = message

    def compose(self) -> ComposeResult:
        with Container(id="confirm-dialog"):
            yield Label(self._message, classes=_CSS.TITLE)
            yield Label(
                _Hint.CONFIRM_CANCEL,
                classes=_CSS.HINT,
            )

    def action_confirm(self) -> None:
        self.dismiss(True)

    def action_cancel(self) -> None:
        self.dismiss(False)

__init__

__init__(message: str) -> None

Initialise the modal.

Parameters:

Name Type Description Default
message str

Confirmation prompt displayed to the user.

required
Source code in src/aimbat/_tui/modals.py
def __init__(self, message: str) -> None:
    """Initialise the modal.

    Args:
        message: Confirmation prompt displayed to the user.
    """
    super().__init__()
    self._message = message

EventSwitcherModal

Bases: ModalScreen[UUID | None]

Modal screen for selecting a seismic event to process.

Methods:

Name Description
__init__

Initialise the modal.

check_action

Disable destructive actions when no row is highlighted.

Source code in src/aimbat/_tui/modals.py
class EventSwitcherModal(ModalScreen[uuid.UUID | None]):
    """Modal screen for selecting a seismic event to process."""

    BINDINGS = [
        Binding("escape", "cancel", "Cancel", show=False),
        Binding("c", "toggle_completed", "Complete", show=True),
        Binding("backspace", "delete_event", "Delete", show=True),
    ]

    def __init__(self, current_event_id: uuid.UUID | None = None) -> None:
        """Initialise the modal.

        Args:
            current_event_id: ID of the currently active event, used to mark
                the active row with a `▶` indicator.
        """
        super().__init__()
        self._current_event_id = current_event_id
        self._selected_event_id: str | None = None

    def check_action(self, action: str, parameters: tuple[object, ...]) -> bool | None:
        """Disable destructive actions when no row is highlighted."""
        if action in {"delete_event", "toggle_completed"}:
            return True if self._selected_event_id else False
        return True

    def compose(self) -> ComposeResult:
        with Container(id="switcher-dialog"):
            yield Label("Switch Event", classes=_CSS.TITLE)
            yield VimDataTable(id="event-table")
            yield Label(_Hint.NAVIGATE_EVENT_SWITCHER, classes=_CSS.HINT)

    def on_mount(self) -> None:
        table = self.query_one(DataTable)
        table.cursor_type = "row"
        headers = [
            tui_display_title(AimbatEventRead, f)
            for f in AimbatEventRead.model_fields
            if f not in _SWITCHER_EVENT_EXCLUDE | {"id"}
        ]
        table.add_columns(" ", *headers)
        self._populate(table)

    def _populate(self, table: DataTable) -> None:
        """Fetch events from the database and populate `table` with rows."""
        try:
            with Session(engine) as session:
                rows = dump_event_table(
                    session,
                    from_read_model=True,
                    by_title=True,
                    exclude=_SWITCHER_EVENT_EXCLUDE,
                )
            for row in rows:
                row_id = str(row.pop("ID"))
                marker = "▶" if row_id == str(self._current_event_id) else " "
                cells = [tui_cell(AimbatEventRead, k, v) for k, v in row.items()]
                table.add_row(marker, *cells, key=row_id)
        except RuntimeError as exc:
            self.notify(str(exc), severity="error")
            self.dismiss(None)

    def _refresh_table(self) -> None:
        """Clear and repopulate the event table, preserving cursor position."""
        table = self.query_one("#event-table", DataTable)
        saved_row = table.cursor_row
        table.clear()
        self._populate(table)
        if table.row_count > 0:
            table.move_cursor(row=min(saved_row, table.row_count - 1))

    @on(DataTable.RowHighlighted, "#event-table")
    def row_highlighted(self, event: DataTable.RowHighlighted) -> None:
        self._selected_event_id = event.row_key.value if event.row_key else None
        self.refresh_bindings()

    @on(DataTable.RowSelected, "#event-table")
    def row_selected(self, event: DataTable.RowSelected) -> None:
        row_key = event.row_key.value
        if not row_key:
            return
        self.dismiss(uuid.UUID(row_key))

    def action_toggle_completed(self) -> None:
        event_id = self._selected_event_id
        if not event_id:
            return
        try:
            with Session(engine) as session:
                event = session.get(AimbatEvent, uuid.UUID(event_id))
                if event is None:
                    return
                event.parameters.completed = not event.parameters.completed
                session.add(event)
                session.commit()
            self._refresh_table()
        except Exception as exc:
            self.notify(str(exc), severity="error")

    def action_delete_event(self) -> None:
        event_id = self._selected_event_id
        if not event_id:
            return

        def on_confirm(confirmed: bool | None) -> None:
            if not confirmed:
                return
            try:
                with Session(engine) as session:
                    delete_event(session, uuid.UUID(event_id))
                self._selected_event_id = None
                self._refresh_table()
                self.notify("Event deleted", timeout=2)
            except Exception as exc:
                self.notify(str(exc), severity="error")

        self.app.push_screen(
            ConfirmModal("Delete this event and all its data?"), on_confirm
        )

    def action_select(self) -> None:
        self.query_one(DataTable).action_select_cursor()

    def action_cancel(self) -> None:
        self.dismiss(None)

__init__

__init__(current_event_id: UUID | None = None) -> None

Initialise the modal.

Parameters:

Name Type Description Default
current_event_id UUID | None

ID of the currently active event, used to mark the active row with a indicator.

None
Source code in src/aimbat/_tui/modals.py
def __init__(self, current_event_id: uuid.UUID | None = None) -> None:
    """Initialise the modal.

    Args:
        current_event_id: ID of the currently active event, used to mark
            the active row with a `▶` indicator.
    """
    super().__init__()
    self._current_event_id = current_event_id
    self._selected_event_id: str | None = None

check_action

check_action(
    action: str, parameters: tuple[object, ...]
) -> bool | None

Disable destructive actions when no row is highlighted.

Source code in src/aimbat/_tui/modals.py
def check_action(self, action: str, parameters: tuple[object, ...]) -> bool | None:
    """Disable destructive actions when no row is highlighted."""
    if action in {"delete_event", "toggle_completed"}:
        return True if self._selected_event_id else False
    return True

HelpModal

Bases: ModalScreen[None]

Modal screen showing keyboard help for the current TUI tab.

Methods:

Name Description
__init__

Initialise the modal for the given tab.

Source code in src/aimbat/_tui/modals.py
class HelpModal(ModalScreen[None]):
    """Modal screen showing keyboard help for the current TUI tab."""

    BINDINGS = [
        Binding("escape", "cancel", "Close", show=False),
        Binding("question_mark", "cancel", "Close", show=False),
    ]

    def __init__(self, tab_id: str) -> None:
        """Initialise the modal for the given tab.

        Args:
            tab_id: The ID of the active `TabPane` whose help to display.
        """
        super().__init__()
        self._tab_id = tab_id

    def compose(self) -> ComposeResult:
        with Container(id="help-dialog"):
            yield Label("Help", classes=_CSS.TITLE)
            yield Markdown(_load_help(self._tab_id), id="help-content")
            yield Label(_Hint.CLOSE, classes=_CSS.HINT)

    def action_cancel(self) -> None:
        self.dismiss(None)

__init__

__init__(tab_id: str) -> None

Initialise the modal for the given tab.

Parameters:

Name Type Description Default
tab_id str

The ID of the active TabPane whose help to display.

required
Source code in src/aimbat/_tui/modals.py
def __init__(self, tab_id: str) -> None:
    """Initialise the modal for the given tab.

    Args:
        tab_id: The ID of the active `TabPane` whose help to display.
    """
    super().__init__()
    self._tab_id = tab_id

InteractiveToolsModal

Bases: ModalScreen[tuple[str, bool, bool] | None]

Menu for launching interactive matplotlib tools.

Options are toggled with key bindings so no Checkbox widgets are needed. Dismisses with (tool_key, context, all_seismograms) or None on cancel.

Source code in src/aimbat/_tui/modals.py
class InteractiveToolsModal(ModalScreen[tuple[str, bool, bool] | None]):
    """Menu for launching interactive matplotlib tools.

    Options are toggled with key bindings so no Checkbox widgets are needed.
    Dismisses with (tool_key, context, all_seismograms) or None on cancel.
    """

    BINDINGS = [
        Binding("escape", "cancel", "Cancel", show=False),
        Binding("c", "toggle_context", "Context", show=False),
        Binding("a", "toggle_all", "All", show=False),
    ]

    def __init__(self) -> None:
        super().__init__()
        self._use_context = True
        self._all_seis = False

    def compose(self) -> ComposeResult:
        with Container(id="tools-dialog"):
            yield Label("Tools", classes=_CSS.TITLE)
            yield VimDataTable(id="tools-table", show_header=False)
            yield Static(id="tools-options")
            yield Label(
                _Hint.NAVIGATE_RUN_CANCEL,
                classes=_CSS.HINT,
            )

    def on_mount(self) -> None:
        table = self.query_one("#tools-table", DataTable)
        table.cursor_type = "row"
        table.add_column("tool")
        for key, label in _TOOLS:
            table.add_row(label, key=key)
        self._update_options()
        table.focus()

    def _update_options(self) -> None:
        """Refresh the context/all-seismograms toggle display."""
        ctx = "✓" if self._use_context else "✗"
        al = "✓" if self._all_seis else "✗"
        self.query_one("#tools-options", Static).update(
            f"  [@click='screen.toggle_context'][dim]c[/dim] context: {ctx}[/]"
            f"   [@click='screen.toggle_all'][dim]a[/dim] all seismograms: {al}[/]"
        )

    @on(DataTable.RowSelected, "#tools-table")
    def row_selected(self, event: DataTable.RowSelected) -> None:
        key = event.row_key.value
        if key:
            self.dismiss((key, self._use_context, self._all_seis))

    def action_toggle_context(self) -> None:
        self._use_context = not self._use_context
        self._update_options()

    def action_toggle_all(self) -> None:
        self._all_seis = not self._all_seis
        self._update_options()

    def action_select(self) -> None:
        self.query_one(DataTable).action_select_cursor()

    def action_cancel(self) -> None:
        self.dismiss(None)

NoProjectModal

Bases: ModalScreen[bool]

Shown on startup when no project exists.

Dismisses True if the user chose to create a project, False to quit.

Source code in src/aimbat/_tui/modals.py
class NoProjectModal(ModalScreen[bool]):
    """Shown on startup when no project exists.

    Dismisses True if the user chose to create a project, False to quit.
    """

    BINDINGS = [
        Binding("c", "create", show=False),
        Binding("enter", "create", show=False),
        Binding("q", "quit_app", show=False),
        Binding("escape", "quit_app", show=False),
    ]

    def compose(self) -> ComposeResult:
        with Container(id="confirm-dialog"):
            yield Label(
                "No project found in the current directory.", classes=_CSS.TITLE
            )
            yield Label(
                "[@click='screen.create'][bold]c[/bold] / ⏎ create project[/]"
                "   "
                "[@click='screen.quit_app'][bold]q[/bold] / ⎋ quit[/]",
                classes=_CSS.HINT,
            )

    def action_create(self) -> None:
        self.dismiss(True)

    def action_quit_app(self) -> None:
        self.dismiss(False)

ParameterInputModal

Bases: ModalScreen[str | None]

Modal for entering a new numeric/timedelta parameter value.

Methods:

Name Description
__init__

Initialise the modal.

Source code in src/aimbat/_tui/modals.py
class ParameterInputModal(ModalScreen[str | None]):
    """Modal for entering a new numeric/timedelta parameter value."""

    BINDINGS = [Binding("escape", "cancel", "Cancel", show=False)]

    def __init__(self, param_name: str, current: str, unit: str) -> None:
        """Initialise the modal.

        Args:
            param_name: Display name of the parameter being edited.
            current: Current value shown as the default input text.
            unit: Unit label appended to the hint (e.g. `"s"` for seconds).
        """
        super().__init__()
        self._param_name = param_name
        self._current = current
        self._unit = unit

    def compose(self) -> ComposeResult:
        hint = f"Current: {self._current} {self._unit}".strip()
        with Container(id="param-edit-dialog"):
            yield Label(f"Edit: {self._param_name}", classes=_CSS.TITLE)
            yield Label(hint, classes=_CSS.HINT)
            yield Input(value=self._current, id="param-input")
            yield Label(
                _Hint.SAVE_CANCEL,
                classes=_CSS.HINT,
            )

    def on_mount(self) -> None:
        self.query_one(Input).focus()

    @on(Input.Submitted)
    def submitted(self, event: Input.Submitted) -> None:
        self.dismiss(event.value.strip())

    def action_save(self) -> None:
        self.dismiss(self.query_one("#param-input", Input).value.strip())

    def action_cancel(self) -> None:
        self.dismiss(None)

__init__

__init__(param_name: str, current: str, unit: str) -> None

Initialise the modal.

Parameters:

Name Type Description Default
param_name str

Display name of the parameter being edited.

required
current str

Current value shown as the default input text.

required
unit str

Unit label appended to the hint (e.g. "s" for seconds).

required
Source code in src/aimbat/_tui/modals.py
def __init__(self, param_name: str, current: str, unit: str) -> None:
    """Initialise the modal.

    Args:
        param_name: Display name of the parameter being edited.
        current: Current value shown as the default input text.
        unit: Unit label appended to the hint (e.g. `"s"` for seconds).
    """
    super().__init__()
    self._param_name = param_name
    self._current = current
    self._unit = unit

ParametersModal

Bases: ModalScreen[bool]

View and edit all event processing parameters inline.

Dismisses with True if any parameter was changed, False otherwise.

Methods:

Name Description
__init__

Initialise the modal.

Source code in src/aimbat/_tui/modals.py
class ParametersModal(ModalScreen[bool]):
    """View and edit all event processing parameters inline.

    Dismisses with True if any parameter was changed, False otherwise.
    """

    BINDINGS = [Binding("escape", "cancel", show=False)]

    def __init__(self, event_id: uuid.UUID) -> None:
        """Initialise the modal.

        Args:
            event_id: ID of the event whose parameters are displayed.
        """
        super().__init__()
        self._event_id = event_id
        self._changed = False

    def compose(self) -> ComposeResult:
        with Container(id="param-table-dialog"):
            yield Label("Parameters", classes=_CSS.TITLE)
            yield VimDataTable(id="param-modal-table", show_header=True)
            yield Label(_Hint.NAVIGATE_EDIT_CLOSE, classes=_CSS.HINT)

    def on_mount(self) -> None:
        table = self.query_one(DataTable)
        table.cursor_type = "row"
        table.add_columns("Parameter", "Value", "Description")
        self._populate()
        table.focus()

    def _populate(self) -> None:
        """Reload the parameter table from the database, preserving cursor position."""
        table = self.query_one("#param-modal-table", DataTable)
        saved_row = table.cursor_row
        table.clear()
        with Session(engine) as session:
            event = session.get(AimbatEvent, self._event_id)
            if event is None:
                return
            fields = list(AimbatEventParametersBase.model_fields.items())
            p = event.parameters
            for attr, field_info in fields:
                value = getattr(p, attr)
                if isinstance(value, bool):
                    display = "✓" if value else "✗"
                elif isinstance(value, Timedelta):
                    display = f"{value.total_seconds():.2f}"
                else:
                    display = f"{value}"
                label = field_info.title or attr
                desc = field_info.description or ""
                table.add_row(label, display, desc, key=attr)
            table.styles.height = len(fields) + 2
        if table.row_count > 0:
            table.move_cursor(row=min(saved_row, table.row_count - 1))

    @on(DataTable.RowSelected)
    def row_selected(self, event: DataTable.RowSelected) -> None:
        attr = event.row_key.value
        if not attr:
            return
        self._edit_parameter(attr)

    def _edit_parameter(self, attr: str) -> None:
        """Open an edit dialog for `attr`, toggling booleans inline."""
        with Session(engine) as session:
            ev = session.get(AimbatEvent, self._event_id)
            if ev is None:
                return
            current = getattr(ev.parameters, attr)

        if isinstance(current, bool):
            self._apply_parameter(attr, not current)
            return

        if isinstance(current, Timedelta):
            current_str = f"{current.total_seconds():.2f}"
            unit = "s"
        else:
            current_str = f"{current}"
            unit = ""

        def on_input(raw: str | None) -> None:
            if raw is None:
                return
            try:
                if isinstance(current, Timedelta):
                    new_val: object = Timedelta(seconds=float(raw))
                else:
                    new_val = float(raw)
                self._apply_parameter(attr, new_val)
            except ValueError as exc:
                self.notify(str(exc), severity="error")

        label = AimbatEventParametersBase.model_fields[attr].title or attr
        self.app.push_screen(ParameterInputModal(label, current_str, unit), on_input)

    def _apply_parameter(self, attr: str, value: object) -> None:
        """Persist a validated parameter change to the database."""
        try:
            with Session(engine) as session:
                event = session.get(AimbatEvent, self._event_id)
                if event is None:
                    return
                set_event_parameter(
                    session,
                    event.id,
                    EventParameter(attr),
                    value,
                    validate_iccs=True,
                )  # type: ignore[call-overload]
        except ValidationError as exc:
            msgs = "; ".join(
                e["msg"].removeprefix("Value error, ") for e in exc.errors()
            )
            self.notify(msgs, severity="error")
            return
        except Exception as exc:
            self.notify(str(exc), severity="error")
            return
        self._changed = True
        self.notify(f"{attr} updated", timeout=2)
        self._populate()

    def action_select(self) -> None:
        self.query_one(DataTable).action_select_cursor()

    def action_cancel(self) -> None:
        self.dismiss(self._changed)

__init__

__init__(event_id: UUID) -> None

Initialise the modal.

Parameters:

Name Type Description Default
event_id UUID

ID of the event whose parameters are displayed.

required
Source code in src/aimbat/_tui/modals.py
def __init__(self, event_id: uuid.UUID) -> None:
    """Initialise the modal.

    Args:
        event_id: ID of the event whose parameters are displayed.
    """
    super().__init__()
    self._event_id = event_id
    self._changed = False

SnapshotActionMenuModal

Bases: ModalScreen[tuple[str, bool, bool] | None]

Action menu for a snapshot row.

Shows context/all-seismograms toggles dynamically when a preview action is highlighted. Dismisses with (action, context, all_seismograms) or None.

Methods:

Name Description
__init__

Initialise the modal.

Source code in src/aimbat/_tui/modals.py
class SnapshotActionMenuModal(ModalScreen[tuple[str, bool, bool] | None]):
    """Action menu for a snapshot row.

    Shows context/all-seismograms toggles dynamically when a preview action
    is highlighted.  Dismisses with (action, context, all_seismograms) or None.
    """

    BINDINGS = [
        Binding("escape", "cancel", show=False),
        Binding("c", "toggle_context", show=False),
        Binding("a", "toggle_all", show=False),
    ]

    def __init__(self, title: str) -> None:
        """Initialise the modal.

        Args:
            title: Heading displayed above the action list.
        """
        super().__init__()
        self._title = title
        self._use_context = True
        self._all_seis = False
        self._highlighted: str = ""

    def compose(self) -> ComposeResult:
        with Container(id="snapshot-action-dialog"):
            yield Label(self._title, classes=_CSS.TITLE)
            yield VimDataTable(id="snapshot-action-table", show_header=False)
            yield Static(id="snapshot-action-options")
            yield Label(_Hint.NAVIGATE_SELECT_CANCEL, classes=_CSS.HINT)

    def on_mount(self) -> None:
        table = self.query_one(DataTable)
        table.cursor_type = "row"
        table.add_column("action")
        for key, label in _SNAPSHOT_ACTIONS:
            table.add_row(label, key=key)
        table.styles.height = len(_SNAPSHOT_ACTIONS)
        table.focus()

    def _update_options(self) -> None:
        """Refresh the context/all-seismograms toggle display."""
        opts = self.query_one("#snapshot-action-options", Static)
        if self._highlighted in _PREVIEW_ACTIONS:
            ctx = "✓" if self._use_context else "✗"
            al = "✓" if self._all_seis else "✗"
            opts.update(
                f"  [@click='screen.toggle_context'][dim]c[/dim] context: {ctx}[/]"
                f"   [@click='screen.toggle_all'][dim]a[/dim] all seismograms: {al}[/]"
            )
        else:
            opts.update("")

    @on(DataTable.RowHighlighted, "#snapshot-action-table")
    def row_highlighted(self, event: DataTable.RowHighlighted) -> None:
        self._highlighted = event.row_key.value or ""
        self._update_options()

    @on(DataTable.RowSelected, "#snapshot-action-table")
    def row_selected(self, event: DataTable.RowSelected) -> None:
        key = event.row_key.value
        if key:
            self.dismiss((key, self._use_context, self._all_seis))

    def action_toggle_context(self) -> None:
        if self._highlighted in _PREVIEW_ACTIONS:
            self._use_context = not self._use_context
            self._update_options()

    def action_toggle_all(self) -> None:
        if self._highlighted in _PREVIEW_ACTIONS:
            self._all_seis = not self._all_seis
            self._update_options()

    def action_select(self) -> None:
        self.query_one(DataTable).action_select_cursor()

    def action_cancel(self) -> None:
        self.dismiss(None)

__init__

__init__(title: str) -> None

Initialise the modal.

Parameters:

Name Type Description Default
title str

Heading displayed above the action list.

required
Source code in src/aimbat/_tui/modals.py
def __init__(self, title: str) -> None:
    """Initialise the modal.

    Args:
        title: Heading displayed above the action list.
    """
    super().__init__()
    self._title = title
    self._use_context = True
    self._all_seis = False
    self._highlighted: str = ""

SnapshotCommentModal

Bases: ModalScreen[str | None]

Prompt for an optional snapshot comment.

Dismisses with the comment string (empty string = no comment) or None if the user cancels.

Source code in src/aimbat/_tui/modals.py
class SnapshotCommentModal(ModalScreen[str | None]):
    """Prompt for an optional snapshot comment.

    Dismisses with the comment string (empty string = no comment) or None if
    the user cancels.
    """

    BINDINGS = [Binding("escape", "cancel", "Cancel", show=False)]

    def compose(self) -> ComposeResult:
        with Container(id="param-edit-dialog"):
            yield Label("New Snapshot", classes=_CSS.TITLE)
            yield Input(placeholder="Comment (optional)", id="param-input")
            yield Label(
                _Hint.SAVE_CANCEL,
                classes=_CSS.HINT,
            )

    def on_mount(self) -> None:
        self.query_one(Input).focus()

    @on(Input.Submitted)
    def submitted(self, event: Input.Submitted) -> None:
        self.dismiss(event.value.strip())

    def action_save(self) -> None:
        self.dismiss(self.query_one("#param-input", Input).value.strip())

    def action_cancel(self) -> None:
        self.dismiss(None)

SnapshotDetailsModal

Bases: ModalScreen[None]

Read-only view of the event parameters captured in a snapshot.

Methods:

Name Description
__init__

Initialise the modal.

Source code in src/aimbat/_tui/modals.py
class SnapshotDetailsModal(ModalScreen[None]):
    """Read-only view of the event parameters captured in a snapshot."""

    BINDINGS = [
        Binding("escape", "cancel", show=False),
    ]

    def __init__(self, title: str, rows: list[tuple[str, str]]) -> None:
        """Initialise the modal.

        Args:
            title: Heading displayed above the parameter table.
            rows: List of `(label, value)` pairs to display as read-only rows.
        """
        super().__init__()
        self._title = title
        self._rows = rows  # [(label, value), ...]

    def compose(self) -> ComposeResult:
        with Container(id="snapshot-details-dialog"):
            yield Label(self._title, classes=_CSS.TITLE)
            yield VimDataTable(id="snapshot-details-table", show_header=True)
            yield Label(_Hint.CLOSE, classes=_CSS.HINT)

    def on_mount(self) -> None:
        table = self.query_one(DataTable)
        table.cursor_type = "none"
        table.add_columns("Parameter", "Value")
        for row in self._rows:
            table.add_row(*row)
        table.styles.height = len(self._rows) + 2

    def action_cancel(self) -> None:
        self.dismiss(None)

__init__

__init__(title: str, rows: list[tuple[str, str]]) -> None

Initialise the modal.

Parameters:

Name Type Description Default
title str

Heading displayed above the parameter table.

required
rows list[tuple[str, str]]

List of (label, value) pairs to display as read-only rows.

required
Source code in src/aimbat/_tui/modals.py
def __init__(self, title: str, rows: list[tuple[str, str]]) -> None:
    """Initialise the modal.

    Args:
        title: Heading displayed above the parameter table.
        rows: List of `(label, value)` pairs to display as read-only rows.
    """
    super().__init__()
    self._title = title
    self._rows = rows  # [(label, value), ...]