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

Root screen of the AIMBAT Terminal User Interface.

Functions:

Name Description
main

Run the AIMBAT TUI until it exits.

AimbatTUI

Bases: _IccsLifecycleMixin, App[None]

Root screen of the AIMBAT Terminal User Interface.

Composes a header, an event status bar, a tabbed content area (Project, Live data, Snapshots) and a footer. Owns the current active event, the long-lived BoundICCS instance used by the Live data tab and the interactive tools (lifecycle managed by _IccsLifecycleMixin), and dispatches row actions and key bindings to the corresponding core functions.

Methods:

Name Description
action_add_data

Prompt for a data type, then a data source, and add it to the project.

action_new_snapshot

Prompt for an optional comment and create a snapshot of the current event's parameters.

action_open_align

Open the alignment menu and run the chosen algorithm (ICCS or MCCC).

action_open_interactive_tools

Open the interactive tools menu and run the chosen tool.

action_open_parameters

Open the parameters modal for the current event, recreating ICCS if changed.

action_refresh

Refresh all panels on demand.

action_show_help

Open the help modal for the active tab.

action_toggle_theme

Toggle between the configured dark and light themes.

action_vim_left

Switch to the previous main tab, unless a modal is open.

action_vim_right

Switch to the next main tab, unless a modal is open.

check_action

Enable or disable key bindings based on the active tab and selected event.

compose

Build the header, event bar, tabbed panels and footer.

on_mount

Initialise TUI state and start the application.

on_tab_activated

Track the active main tab and focus its table.

refresh_all

Refresh every panel to reflect the current database state.

Source code in src/aimbat/_tui/app.py
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
class AimbatTUI(_IccsLifecycleMixin, App[None]):
    """Root screen of the AIMBAT Terminal User Interface.

    Composes a header, an event status bar, a tabbed content area (Project,
    Live data, Snapshots) and a footer. Owns the current active event, the
    long-lived `BoundICCS` instance used by the Live data tab and the
    interactive tools (lifecycle managed by `_IccsLifecycleMixin`), and
    dispatches row actions and key bindings to the corresponding core
    functions.
    """

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

    BINDINGS = [
        Binding("i", "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:
        """Build the header, event bar, tabbed panels and footer."""
        yield Header()
        yield Static(id="event-bar")
        with TabbedContent(initial="tab-project"):
            with TabPane("Project", id="tab-project"):
                yield ProjectPanel()
            with TabPane("Live data", id="tab-seismograms"):
                yield SeismogramPanel()
            with TabPane("Snapshots", id="tab-snapshots"):
                yield SnapshotPanel()
        yield Footer()

    def on_mount(self) -> None:
        """Initialise TUI state and start the application.

        If no project exists in the current directory, prompts to create
        one. If a project exists but its database schema is out of date,
        prompts to upgrade before entry is allowed. Otherwise creates the
        ICCS instance for the current event (if any) and populates all
        panels. Also starts the periodic ICCS staleness check.
        """
        self._init_iccs_lifecycle()
        self._current_event_id: uuid.UUID | None = None
        self._active_tab: str = "tab-project"

        self.theme = _DEFAULT_THEME

        logger.info("TUI started.")
        if not _project_exists(engine):
            self.push_screen(NoProjectModal(), self._on_no_project_modal)
        else:
            warning = _build_staleness_warning(get_current_revision(engine))
            if warning is not None:
                self.push_screen(
                    SchemaStaleModal(str(warning)), self._on_schema_stale_modal
                )
            else:
                self._create_iccs()
                self.refresh_all()

    def _on_no_project_modal(self, create: bool | None) -> None:
        """Handle the result of `NoProjectModal`.

        Creates a new project and the ICCS instance if the user opted in,
        otherwise exits the application.

        Args:
            create: Whether the user chose to create a new project.
        """
        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()

    def _on_schema_stale_modal(self, upgrade: bool | None) -> None:
        """Handle the result of `SchemaStaleModal`.

        Exits the application if the user declines to upgrade. Otherwise
        runs the database upgrade and, on success, creates the ICCS
        instance and refreshes all panels. Exits with an error message if
        the upgrade itself fails.

        Args:
            upgrade: Whether the user chose to upgrade the project database.
        """
        if not upgrade:
            logger.info("User declined to upgrade the project database. Exiting.")
            self.exit()
            return

        logger.info("User chose to upgrade the project database.")
        try:
            upgrade_project(engine)
        except SchemaMismatchError as exc:
            logger.error(f"Automatic upgrade failed: {exc}")
            self.exit(return_code=1, message=str(exc))
            return

        self._create_iccs()
        self.refresh_all()

    @on(TabbedContent.TabActivated)
    def on_tab_activated(self, event: TabbedContent.TabActivated) -> None:
        """Track the active main tab and focus its table.

        Updates `_active_tab`, refreshes key-binding availability, moves
        focus to the tab's `DataTable` unless a `Tabs` widget already has
        focus, and clears the highlighted row's detail panels when
        switching into an empty Live data or Snapshots tab.
        """
        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":
            self.query_one(SeismogramPanel).clear_selection_if_empty()
        elif event.pane.id == "tab-snapshots":
            self.query_one(SnapshotPanel).clear_selection_if_empty()

    def check_action(self, action: str, parameters: tuple[object, ...]) -> bool | None:
        """Enable or disable key bindings based on the active tab and selected event.

        Args:
            action: Name of the action being checked.
            parameters: Arguments the action would be called with.

        Returns:
            Whether the action is currently available.
        """
        if action == "add_data":
            return self._active_tab == "tab-project"
        if action == "new_snapshot":
            return (
                self._active_tab == "tab-seismograms"
                and self._current_event_id is not None
            )
        if action in {"open_interactive_tools", "open_align"}:
            return (
                self._active_tab == "tab-seismograms"
                and self._current_event_id is not None
            )
        if action == "open_parameters":
            if self._current_event_id is None:
                return False
            if self._active_tab == "tab-seismograms":
                return True
            if self._active_tab == "tab-project":
                # `self.focused` is the DataTable itself when a table has
                # keyboard focus (DataTable has no focusable descendants), so
                # comparing its id directly is sufficient - this would need
                # revisiting if DataTable ever grew focusable child widgets.
                return getattr(self.focused, "id", None) == "project-event-table"
            return False
        return True

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

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

        Clears a stale `_current_event_id` if the referenced event no longer
        exists.

        Args:
            session: Database session used to look up the event.

        Returns:
            The currently selected event.

        Raises:
            NoResultFound: If no event has been selected, or the previously
                selected 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]:
        """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 (including
        `KeyboardInterrupt`) is shown in the terminal while still suspended,
        then re-raised after Textual has fully resumed so callers can log it
        or update state - callers should not also display it to the user
        (e.g. via `self.notify`), since it was already shown here.
        """
        console = Console()
        caught: BaseException | None = None
        with self.suspend():
            console.clear()
            if label is not None:
                console.print(
                    Panel(
                        f"[bold]{label}[/bold]\n\nClose the matplotlib window to return to AIMBAT.",
                        title="Interactive Tool Running",
                        border_style="bright_blue",
                        padding=(1, 4),
                    )
                )
            try:
                yield
            except KeyboardInterrupt as exc:
                caught = exc
                console.print("\n[bold yellow]Cancelled.[/bold yellow]")
                console.input("\n[dim]Press Enter to return to AIMBAT...[/dim]")
            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

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

    def refresh_all(self) -> None:
        """Refresh every panel to reflect the current database state.

        The default choice after any mutation. A targeted
        `<Panel>.refresh_data(...)` call is appropriate only when no other
        panel's displayed data (including `column_property` counts and the
        live quality getters) is affected by the change; record that
        reasoning as a comment at the call site.

        The event bar and all three panels share one session, so the id pool
        `uuid_shortener` caches on it is fetched once for the whole refresh
        rather than once per panel.
        """
        self.refresh_bindings()
        with Session(engine) as session:
            self._refresh_event_bar(session)
            self.query_one(ProjectPanel).refresh_data(session, self._current_event_id)
            self.query_one(SeismogramPanel).refresh_data(
                session, self._current_event_id, self._iccs_lifecycle.bound
            )
            self.query_one(SnapshotPanel).refresh_data(session, self._current_event_id)

    def _refresh_event_bar(self, session: Session) -> None:
        """Update the status bar with the current event's time, location and ICCS status.

        Shows a prompt to select an event or add data when no event is
        selected, or an error message if the current event could not be
        loaded.

        Args:
            session: Database session to read the current event with.
        """
        bar = self.query_one("#event-bar", Static)
        try:
            event = self._get_current_event(session)
            iccs_status = (
                " ● ICCS ready" if self._iccs_lifecycle.ready else " ○ no ICCS"
            )
            time_str = fmt_timestamp(event.time) if event.time else "unknown"
            lat = f"{event.latitude:.3f}°"
            lon = f"{event.longitude:.3f}°"
            modified = (
                f"  modified: {fmt_timestamp(event.last_modified)}"
                if event.last_modified is not None
                else ""
            )
            bar.update(
                f"▶ {time_str}  |  {lat}, {lon}{modified}  [dim]{iccs_status}  switch "
                + "events on the Project tab[/dim]"
            )
        except NoResultFound:
            has_events = session.exec(select(AimbatEvent)).first() is not None
            if has_events:
                bar.update(
                    "[red]No event selected: select one on the Project tab[/red]"
                )
            else:
                bar.update("[red]No data in project: press i to add data[/red]")
        except RuntimeError as exc:
            bar.update(f"[red]{exc}[/red]")

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

    @on(ProjectPanel.RowActionChosen)
    def _project_row_action_chosen(self, message: ProjectPanel.RowActionChosen) -> None:
        """Dispatch a row action chosen on the Project tab."""
        self._handle_row_action(message.tab, message.item_id, message.action)

    @on(SeismogramPanel.RowActionChosen)
    def _seismogram_row_action_chosen(
        self, message: SeismogramPanel.RowActionChosen
    ) -> None:
        """Dispatch a row action chosen on the Live data tab."""
        self._handle_row_action("tab-seismograms", message.item_id, message.action)

    @on(SnapshotPanel.ActionChosen)
    def _snapshot_action_chosen(self, message: SnapshotPanel.ActionChosen) -> None:
        """Dispatch a row action chosen on the Snapshots tab.

        Preview and results-saving actions are handled directly since they
        carry extra `context`/`all_seismograms` options not shared with the
        other tabs' row actions; all other actions go through
        `_handle_row_action`.
        """
        if message.action == "preview_stack":
            self._preview_snapshot_plot(
                message.item_id, "stack", message.context, message.all_seismograms
            )
        elif message.action == "preview_image":
            self._preview_snapshot_plot(
                message.item_id, "image", message.context, message.all_seismograms
            )
        elif message.action == "save_results":
            self._save_snapshot_results(message.item_id)
        else:
            self._handle_row_action("tab-snapshots", message.item_id, message.action)

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

    def _handle_row_action(self, tab: str, item_id: str, action: str | None) -> None:
        """Route a row action chosen from a table's action menu or footer hotkey to its handler.

        Args:
            tab: ID of the tab the row belongs to.
            item_id: ID of the row's underlying database entity.
            action: Action key chosen, or `None` if the menu was cancelled.
        """
        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:
        """Make the given event the active event and rebuild its ICCS instance."""
        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:
        """Flip the `completed` flag on the given event's parameters."""
        logger.debug(f"User toggled completed flag for event {item_id[:8]}.")
        try:
            with Session(engine) as session:
                toggle_event_completed(session, uuid.UUID(item_id))
            self.refresh_all()
            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:
        """Suspend the TUI and show a matplotlib plot of seismograms for an event or station.

        Args:
            tab: Tab the row belongs to; determines whether `item_id`
                refers to an event or a station.
            item_id: ID of the event or station whose seismograms to plot.
        """
        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(event, return_fig=False)
                    else:
                        station = session.get(AimbatStation, item_uuid)
                        if station is None:
                            return
                        plot_seismograms(station, return_fig=False)
        except KeyboardInterrupt:
            pass
        except Exception as exc:
            logger.exception(f"Viewing seismograms failed: {exc}")

    def _toggle_seismogram_bool(self, item_id: str, param: SeismogramParameter) -> None:
        """Flip a boolean seismogram parameter (select or flip) and update the in-memory ICCS instance.

        Persists the new value to the database, mutates the matching
        seismogram in the live ICCS instance directly so the Live data table
        keeps its cross-correlation values, then refreshes every panel.

        Args:
            item_id: ID of the seismogram to update.
            param: Boolean parameter to toggle.
        """
        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)
                set_seismogram_parameter(session, seis_uuid, param, new_value)
            bound = self._iccs_lifecycle.bound
            if bound is not None:
                for iccs_seis in bound.iccs.seismograms:
                    if iccs_seis.extra.get("id") == seis_uuid:
                        setattr(iccs_seis, param, new_value)
                        bound.iccs.clear_cache()
                        bound.created_at = Timestamp.now("UTC")
                        break
            # A select/flip change fires the quality-invalidation triggers,
            # nulling iccs_cc and the MCCC quality columns for the whole event
            # - which the Project panel's event-quality and per-station
            # cc_mean/cc_sem readouts display. Refresh everything so those
            # panels drop the now-invalid values instead of showing them until
            # the next unrelated refresh.
            self.refresh_all()
            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:
        """Reset a seismogram's processing parameters to their defaults."""
        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:
        """Show a confirmation dialog, then delete the row's entity if confirmed.

        Args:
            tab: Tab the row belongs to; determines which entity type
                `item_id` refers to (event, station, seismogram or
                snapshot).
            item_id: ID of the entity to delete.
        """
        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._iccs_lifecycle.clear()
                    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_all()
                    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:
        """Open a modal listing the event parameters captured in a snapshot."""
        try:
            with Session(engine) as session:
                snap = session.get(AimbatSnapshot, uuid.UUID(snap_id))
                if snap is None:
                    return
                data = snap.event_parameters_snapshot.model_dump(mode="json")
            rows: list[tuple[str, str]] = []
            for attr in AimbatEventParametersBase.model_fields:
                title = tui_display_title(AimbatEventParametersBase, attr)
                display = str(tui_cell(AimbatEventParametersBase, title, data[attr]))
                rows.append((title, 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:
        """Prompt for a file path and write a snapshot's results to it as JSON."""
        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:
        """Suspend the TUI and show a matplotlib stack or matrix-image plot rebuilt from a snapshot.

        Args:
            snap_id: ID of the snapshot to rebuild ICCS from.
            plot_type: Either `"stack"` or `"image"`.
            context: Whether to plot the context window rather than the CC window.
            all_seis: Whether to include seismograms not currently selected.
        """
        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 KeyboardInterrupt:
            pass
        except Exception as exc:
            logger.exception(f"Snapshot preview failed: {exc}")

    def _confirm_rollback(self, snap_id: str) -> None:
        """Show a confirmation dialog, then roll the active event back to a snapshot if confirmed."""

        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:
        """Open the parameters modal for the current event, recreating ICCS if changed."""
        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: select one on the Project tab",
                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_add_data(self) -> None:
        """Prompt for a data type, then a data source, and add it to the project."""
        actions = [
            (dt.value, dt.name.replace("_", " "))
            for dt in DataType
            if supports_station_creation(dt)
            or supports_event_creation(dt)
            or supports_seismogram_creation(dt)
        ]

        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:
                        (
                            added_datasources,
                            _existing_station_ids,
                            _existing_event_ids,
                            existing_seismogram_ids,
                            _duplicate_warnings,
                        ) = add_data_to_project(session, [path], data_type)
                        session.commit()
                        snapshotted, failures = create_snapshots_for_added_data(
                            session, added_datasources, existing_seismogram_ids
                        )
                    logger.info(f"User added data file: {path}.")
                    self.notify(f"Added: {path.name}", severity="information")
                    if snapshotted:
                        n = len(snapshotted)
                        self.notify(
                            f"Snapshotted {n} event{'' if n == 1 else 's'}",
                            severity="information",
                        )
                    for event_id, error in failures:
                        self.notify(
                            f"Could not create an automatic snapshot for event {event_id}: {error}",
                            severity="warning",
                        )
                    self.refresh_all()
                except Exception as exc:
                    logger.exception(f"Failed to add data file {path}: {exc}")
                    self.notify(exception_message(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 action_open_interactive_tools(self) -> None:
        """Open the interactive tools menu and run the chosen tool."""
        if not self._require_iccs():
            return

        def on_result(result: ToolLaunchResult | None) -> None:
            if result is not None:
                self._run_tool(
                    result.tool, result.context, result.all_seismograms, result.causal
                )

        self.push_screen(InteractiveToolsModal(), on_result)

    def _run_tool(
        self, tool: str, context: bool, all_seis: bool, causal: bool | None
    ) -> None:
        """Run an interactive tool from `TOOL_REGISTRY` or `CAUSAL_TOOL_REGISTRY`.

        Uses the long-lived ICCS instance so waveform data do not need to be
        reloaded. Suspends the TUI while the tool's matplotlib window is
        open and refreshes all panels once it closes.

        Args:
            tool: Key identifying the tool in the registry.
            context: Whether to operate on the context window rather than
                the CC window.
            all_seis: Whether to include seismograms not currently selected.
            causal: Zero-phase/causal filter setting; only meaningful for
                tools in `CAUSAL_TOOL_REGISTRY`, otherwise `None`.
        """
        logger.debug(
            f"User launched interactive tool '{tool}' (context={context}, "
            + f"all_seis={all_seis}, causal={causal})."
        )
        bound = self._iccs_lifecycle.bound
        if bound is None:
            self.notify("ICCS not ready: please wait", severity="warning")
            return
        iccs = bound.iccs
        is_causal_tool = tool in CAUSAL_TOOL_REGISTRY
        label = (
            CAUSAL_TOOL_REGISTRY[tool][0] if is_causal_tool else TOOL_REGISTRY[tool][0]
        )

        try:
            with Session(engine) as session:
                event_id = self._get_current_event(session).id

            # No session is held across the tool: it blocks for as long as its
            # plot window is open, and opens a short-lived one of its own
            # afterwards if it has something to save.
            with self._suspend(label):
                if is_causal_tool:
                    assert causal is not None
                    CAUSAL_TOOL_REGISTRY[tool][1](
                        event_id, iccs, context, all_seis, causal
                    )
                else:
                    TOOL_REGISTRY[tool][1](event_id, iccs, context, all_seis)
        except KeyboardInterrupt:
            self.notify(f"{label} cancelled", timeout=2)
            return
        except Exception as exc:
            logger.exception(f"Interactive tool '{tool}' raised: {exc}")
            return

        if tool in VIEW_ONLY_TOOLS:
            # A display-only tool changed nothing; just repaint. Deliberately
            # leave bound.created_at alone - bumping it would mask an external
            # commit (a CLI edit, an align worker) made while the plot window
            # was open, so the staleness poller could no longer rebuild.
            self.refresh_all()
        else:
            # The tool persisted a parameter or pick change: the triggers have
            # nulled iccs_cc and the in-memory instance is now stale. Rebuild it
            # (which re-persists iccs_cc and refreshes every panel), matching the
            # Parameters modal's on-close behaviour.
            self._create_iccs()
        self.notify("Done", timeout=2)

    def action_open_align(self) -> None:
        """Open the alignment menu and run the chosen algorithm (ICCS or MCCC)."""
        if not self._require_iccs():
            return

        def on_result(result: tuple[str, bool, bool, bool] | None) -> None:
            if result is None:
                return
            # Re-checked here, not just in the guard above: the modal is
            # async, so the staleness poll can clear the instance via
            # `_create_iccs()` while it is open.
            bound = self._iccs_lifecycle.bound
            if bound is None:
                self.notify("ICCS not ready: please wait", severity="warning")
                return
            self._run_align_tool(bound, *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 and post the result to the main thread.

        Note:
            `run_iccs`/`run_mccc` mutate `bound.iccs` in place on this
            worker thread while it runs. Nothing prevents the main thread's
            5s staleness poll or a panel refresh from reading `bound.iccs`
            (or replacing `bound` via `_create_iccs()`) concurrently - there
            is no lock. Not currently known to cause a visible failure in
            practice, but a torn read is possible while an alignment is in
            flight.

        Args:
            bound: The current `BoundICCS` instance to align.
            algorithm: Either `"iccs"` or `"mccc"`.
            autoflip: Whether ICCS should automatically flip polarity-reversed
                seismograms.
            autoselect: Whether ICCS should automatically deselect
                poorly-correlated seismograms.
            all_seis: Whether MCCC should run over all seismograms rather
                than only the selected ones.
        """
        logger.debug(
            f"Alignment worker starting: algorithm={algorithm!r}, autoflip="
            + f"{autoflip!r}, autoselect={autoselect!r}, all_seis={all_seis!r}."
        )
        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
        # Stamp created_at here, before posting to the event loop, so the
        # staleness poller cannot observe last_modified > created_at between
        # this call_from_thread and _post_align_complete actually running.
        bound.created_at = Timestamp.now("UTC")
        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:
        """Refresh all panels and show the alignment result notification.

        Args:
            msg: Notification text.
            severity: Notification severity level.
        """
        self.refresh_all()
        self.notify(msg, severity=severity, timeout=4)

    def action_new_snapshot(self) -> None:
        """Prompt for an optional comment and create a snapshot of the current event's parameters."""

        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_all()
                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:
        """Switch to the previous main tab, unless a modal is open."""
        if not isinstance(self.screen, ModalScreen):
            self.query_one(TabbedContent).query_one(Tabs).action_previous_tab()

    def action_vim_right(self) -> None:
        """Switch to the next main tab, unless a modal is open."""
        if not isinstance(self.screen, ModalScreen):
            self.query_one(TabbedContent).query_one(Tabs).action_next_tab()

    def action_toggle_theme(self) -> None:
        """Toggle between the configured dark and light themes."""
        self.theme = _LIGHT_THEME if self.theme == _DEFAULT_THEME else _DEFAULT_THEME

    def action_show_help(self) -> None:
        """Open the help modal for the active tab."""
        self.push_screen(HelpModal(self._active_tab))

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

action_add_data

action_add_data() -> None

Prompt for a data type, then a data source, and add it to the project.

Source code in src/aimbat/_tui/app.py
def action_add_data(self) -> None:
    """Prompt for a data type, then a data source, and add it to the project."""
    actions = [
        (dt.value, dt.name.replace("_", " "))
        for dt in DataType
        if supports_station_creation(dt)
        or supports_event_creation(dt)
        or supports_seismogram_creation(dt)
    ]

    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:
                    (
                        added_datasources,
                        _existing_station_ids,
                        _existing_event_ids,
                        existing_seismogram_ids,
                        _duplicate_warnings,
                    ) = add_data_to_project(session, [path], data_type)
                    session.commit()
                    snapshotted, failures = create_snapshots_for_added_data(
                        session, added_datasources, existing_seismogram_ids
                    )
                logger.info(f"User added data file: {path}.")
                self.notify(f"Added: {path.name}", severity="information")
                if snapshotted:
                    n = len(snapshotted)
                    self.notify(
                        f"Snapshotted {n} event{'' if n == 1 else 's'}",
                        severity="information",
                    )
                for event_id, error in failures:
                    self.notify(
                        f"Could not create an automatic snapshot for event {event_id}: {error}",
                        severity="warning",
                    )
                self.refresh_all()
            except Exception as exc:
                logger.exception(f"Failed to add data file {path}: {exc}")
                self.notify(exception_message(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)

action_new_snapshot

action_new_snapshot() -> None

Prompt for an optional comment and create a snapshot of the current event's parameters.

Source code in src/aimbat/_tui/app.py
def action_new_snapshot(self) -> None:
    """Prompt for an optional comment and create a snapshot of the current event's parameters."""

    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_all()
            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)

action_open_align

action_open_align() -> None

Open the alignment menu and run the chosen algorithm (ICCS or MCCC).

Source code in src/aimbat/_tui/app.py
def action_open_align(self) -> None:
    """Open the alignment menu and run the chosen algorithm (ICCS or MCCC)."""
    if not self._require_iccs():
        return

    def on_result(result: tuple[str, bool, bool, bool] | None) -> None:
        if result is None:
            return
        # Re-checked here, not just in the guard above: the modal is
        # async, so the staleness poll can clear the instance via
        # `_create_iccs()` while it is open.
        bound = self._iccs_lifecycle.bound
        if bound is None:
            self.notify("ICCS not ready: please wait", severity="warning")
            return
        self._run_align_tool(bound, *result)

    self.push_screen(AlignModal(), on_result)

action_open_interactive_tools

action_open_interactive_tools() -> None

Open the interactive tools menu and run the chosen tool.

Source code in src/aimbat/_tui/app.py
def action_open_interactive_tools(self) -> None:
    """Open the interactive tools menu and run the chosen tool."""
    if not self._require_iccs():
        return

    def on_result(result: ToolLaunchResult | None) -> None:
        if result is not None:
            self._run_tool(
                result.tool, result.context, result.all_seismograms, result.causal
            )

    self.push_screen(InteractiveToolsModal(), on_result)

action_open_parameters

action_open_parameters() -> None

Open the parameters modal for the current event, recreating ICCS if changed.

Source code in src/aimbat/_tui/app.py
def action_open_parameters(self) -> None:
    """Open the parameters modal for the current event, recreating ICCS if changed."""
    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: select one on the Project tab",
            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)

action_refresh

action_refresh() -> None

Refresh all panels on demand.

Source code in src/aimbat/_tui/app.py
def action_refresh(self) -> None:
    """Refresh all panels on demand."""
    logger.debug("User triggered manual refresh.")
    self.refresh_all()
    self.notify("Refreshed", timeout=1)

action_show_help

action_show_help() -> None

Open the help modal for the active tab.

Source code in src/aimbat/_tui/app.py
def action_show_help(self) -> None:
    """Open the help modal for the active tab."""
    self.push_screen(HelpModal(self._active_tab))

action_toggle_theme

action_toggle_theme() -> None

Toggle between the configured dark and light themes.

Source code in src/aimbat/_tui/app.py
def action_toggle_theme(self) -> None:
    """Toggle between the configured dark and light themes."""
    self.theme = _LIGHT_THEME if self.theme == _DEFAULT_THEME else _DEFAULT_THEME

action_vim_left

action_vim_left() -> None

Switch to the previous main tab, unless a modal is open.

Source code in src/aimbat/_tui/app.py
def action_vim_left(self) -> None:
    """Switch to the previous main tab, unless a modal is open."""
    if not isinstance(self.screen, ModalScreen):
        self.query_one(TabbedContent).query_one(Tabs).action_previous_tab()

action_vim_right

action_vim_right() -> None

Switch to the next main tab, unless a modal is open.

Source code in src/aimbat/_tui/app.py
def action_vim_right(self) -> None:
    """Switch to the next main tab, unless a modal is open."""
    if not isinstance(self.screen, ModalScreen):
        self.query_one(TabbedContent).query_one(Tabs).action_next_tab()

check_action

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

Enable or disable key bindings based on the active tab and selected event.

Parameters:

Name Type Description Default
action str

Name of the action being checked.

required
parameters tuple[object, ...]

Arguments the action would be called with.

required

Returns:

Type Description
bool | None

Whether the action is currently available.

Source code in src/aimbat/_tui/app.py
def check_action(self, action: str, parameters: tuple[object, ...]) -> bool | None:
    """Enable or disable key bindings based on the active tab and selected event.

    Args:
        action: Name of the action being checked.
        parameters: Arguments the action would be called with.

    Returns:
        Whether the action is currently available.
    """
    if action == "add_data":
        return self._active_tab == "tab-project"
    if action == "new_snapshot":
        return (
            self._active_tab == "tab-seismograms"
            and self._current_event_id is not None
        )
    if action in {"open_interactive_tools", "open_align"}:
        return (
            self._active_tab == "tab-seismograms"
            and self._current_event_id is not None
        )
    if action == "open_parameters":
        if self._current_event_id is None:
            return False
        if self._active_tab == "tab-seismograms":
            return True
        if self._active_tab == "tab-project":
            # `self.focused` is the DataTable itself when a table has
            # keyboard focus (DataTable has no focusable descendants), so
            # comparing its id directly is sufficient - this would need
            # revisiting if DataTable ever grew focusable child widgets.
            return getattr(self.focused, "id", None) == "project-event-table"
        return False
    return True

compose

compose() -> ComposeResult

Build the header, event bar, tabbed panels and footer.

Source code in src/aimbat/_tui/app.py
def compose(self) -> ComposeResult:
    """Build the header, event bar, tabbed panels and footer."""
    yield Header()
    yield Static(id="event-bar")
    with TabbedContent(initial="tab-project"):
        with TabPane("Project", id="tab-project"):
            yield ProjectPanel()
        with TabPane("Live data", id="tab-seismograms"):
            yield SeismogramPanel()
        with TabPane("Snapshots", id="tab-snapshots"):
            yield SnapshotPanel()
    yield Footer()

on_mount

on_mount() -> None

Initialise TUI state and start the application.

If no project exists in the current directory, prompts to create one. If a project exists but its database schema is out of date, prompts to upgrade before entry is allowed. Otherwise creates the ICCS instance for the current event (if any) and populates all panels. Also starts the periodic ICCS staleness check.

Source code in src/aimbat/_tui/app.py
def on_mount(self) -> None:
    """Initialise TUI state and start the application.

    If no project exists in the current directory, prompts to create
    one. If a project exists but its database schema is out of date,
    prompts to upgrade before entry is allowed. Otherwise creates the
    ICCS instance for the current event (if any) and populates all
    panels. Also starts the periodic ICCS staleness check.
    """
    self._init_iccs_lifecycle()
    self._current_event_id: uuid.UUID | None = None
    self._active_tab: str = "tab-project"

    self.theme = _DEFAULT_THEME

    logger.info("TUI started.")
    if not _project_exists(engine):
        self.push_screen(NoProjectModal(), self._on_no_project_modal)
    else:
        warning = _build_staleness_warning(get_current_revision(engine))
        if warning is not None:
            self.push_screen(
                SchemaStaleModal(str(warning)), self._on_schema_stale_modal
            )
        else:
            self._create_iccs()
            self.refresh_all()

on_tab_activated

on_tab_activated(event: TabActivated) -> None

Track the active main tab and focus its table.

Updates _active_tab, refreshes key-binding availability, moves focus to the tab's DataTable unless a Tabs widget already has focus, and clears the highlighted row's detail panels when switching into an empty Live data or Snapshots tab.

Source code in src/aimbat/_tui/app.py
@on(TabbedContent.TabActivated)
def on_tab_activated(self, event: TabbedContent.TabActivated) -> None:
    """Track the active main tab and focus its table.

    Updates `_active_tab`, refreshes key-binding availability, moves
    focus to the tab's `DataTable` unless a `Tabs` widget already has
    focus, and clears the highlighted row's detail panels when
    switching into an empty Live data or Snapshots tab.
    """
    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":
        self.query_one(SeismogramPanel).clear_selection_if_empty()
    elif event.pane.id == "tab-snapshots":
        self.query_one(SnapshotPanel).clear_selection_if_empty()

refresh_all

refresh_all() -> None

Refresh every panel to reflect the current database state.

The default choice after any mutation. A targeted <Panel>.refresh_data(...) call is appropriate only when no other panel's displayed data (including column_property counts and the live quality getters) is affected by the change; record that reasoning as a comment at the call site.

The event bar and all three panels share one session, so the id pool uuid_shortener caches on it is fetched once for the whole refresh rather than once per panel.

Source code in src/aimbat/_tui/app.py
def refresh_all(self) -> None:
    """Refresh every panel to reflect the current database state.

    The default choice after any mutation. A targeted
    `<Panel>.refresh_data(...)` call is appropriate only when no other
    panel's displayed data (including `column_property` counts and the
    live quality getters) is affected by the change; record that
    reasoning as a comment at the call site.

    The event bar and all three panels share one session, so the id pool
    `uuid_shortener` caches on it is fetched once for the whole refresh
    rather than once per panel.
    """
    self.refresh_bindings()
    with Session(engine) as session:
        self._refresh_event_bar(session)
        self.query_one(ProjectPanel).refresh_data(session, self._current_event_id)
        self.query_one(SeismogramPanel).refresh_data(
            session, self._current_event_id, self._iccs_lifecycle.bound
        )
        self.query_one(SnapshotPanel).refresh_data(session, self._current_event_id)

main

main() -> None

Run the AIMBAT TUI until it exits.

Configures logging first, for the same reason aimbat.app.main does: the aimbat-tui script reaches this function without passing through the CLI entrypoint.

Raises:

Type Description
RuntimeError

If the TUI exited after an unhandled exception (a non-zero App.return_code), so the process reports failure rather than exiting 0 despite the crash.

Source code in src/aimbat/_tui/app.py
def main() -> None:
    """Run the AIMBAT TUI until it exits.

    Configures logging first, for the same reason `aimbat.app.main` does: the
    `aimbat-tui` script reaches this function without passing through the CLI
    entrypoint.

    Raises:
        RuntimeError: If the TUI exited after an unhandled exception (a
            non-zero `App.return_code`), so the process reports failure
            rather than exiting 0 despite the crash.
    """
    from aimbat.logger import configure_logging

    configure_logging()

    app = AimbatTUI()
    app.run()
    if app.return_code:
        raise RuntimeError(
            "AIMBAT TUI exited after an unhandled error - see the crash report "
            + "above for details."
        )

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.

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.

ToolLaunchResult

Result of choosing a tool in InteractiveToolsModal.

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.

action_cancel

Dismiss without choosing an action.

action_select

Trigger selection of the row under the cursor.

compose

Build the title, action table and navigate/select/cancel hint.

on_mount

Populate the action table from _actions.

row_selected

Dismiss with the chosen action's key.

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:
        """Build the title, action table and navigate/select/cancel hint."""
        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:
        """Populate the action table from `_actions`."""
        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:
        """Dismiss with the chosen action's key."""
        self.dismiss(event.row_key.value)

    def action_select(self) -> None:
        """Trigger selection of the row under the cursor."""
        self.query_one(DataTable).action_select_cursor()

    def action_cancel(self) -> None:
        """Dismiss without choosing an action."""
        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), ...]

action_cancel

action_cancel() -> None

Dismiss without choosing an action.

Source code in src/aimbat/_tui/modals.py
def action_cancel(self) -> None:
    """Dismiss without choosing an action."""
    self.dismiss(None)

action_select

action_select() -> None

Trigger selection of the row under the cursor.

Source code in src/aimbat/_tui/modals.py
def action_select(self) -> None:
    """Trigger selection of the row under the cursor."""
    self.query_one(DataTable).action_select_cursor()

compose

compose() -> ComposeResult

Build the title, action table and navigate/select/cancel hint.

Source code in src/aimbat/_tui/modals.py
def compose(self) -> ComposeResult:
    """Build the title, action table and navigate/select/cancel hint."""
    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,
        )

on_mount

on_mount() -> None

Populate the action table from _actions.

Source code in src/aimbat/_tui/modals.py
def on_mount(self) -> None:
    """Populate the action table from `_actions`."""
    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()

row_selected

row_selected(event: RowSelected) -> None

Dismiss with the chosen action's key.

Source code in src/aimbat/_tui/modals.py
@on(DataTable.RowSelected)
def row_selected(self, event: DataTable.RowSelected) -> None:
    """Dismiss with the chosen action's key."""
    self.dismiss(event.row_key.value)

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).

Methods:

Name Description
__init__

Initialise the modal with all toggles off and ICCS as the highlighted algorithm.

action_cancel

Dismiss without choosing an algorithm.

action_select

Trigger selection of the row under the cursor.

action_toggle_all

Toggle the MCCC all-seismograms option, if MCCC is the highlighted algorithm.

action_toggle_autoflip

Toggle the ICCS autoflip option, if ICCS is the highlighted algorithm.

action_toggle_autoselect

Toggle the ICCS autoselect option, if ICCS is the highlighted algorithm.

compose

Build the title, algorithm table, toggle options display and hint.

on_mount

Populate the algorithm table.

row_highlighted

Track the highlighted algorithm and show its option toggles.

row_selected

Dismiss with the chosen algorithm and the current toggle values.

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:
        """Initialise the modal with all toggles off and ICCS as the highlighted algorithm."""
        super().__init__()
        self._autoflip = False
        self._autoselect = False
        self._all_seis = False
        self._highlighted_algorithm: str = "iccs"

    def compose(self) -> ComposeResult:
        """Build the title, algorithm table, toggle options display and hint."""
        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:
        """Populate the algorithm table."""
        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:
        """Track the highlighted algorithm and show its option toggles."""
        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:
        """Dismiss with the chosen algorithm and the current toggle values."""
        key = event.row_key.value
        if key:
            self.dismiss((key, self._autoflip, self._autoselect, self._all_seis))

    def action_toggle_autoflip(self) -> None:
        """Toggle the ICCS autoflip option, if ICCS is the highlighted algorithm."""
        if self._highlighted_algorithm == "iccs":
            self._autoflip = not self._autoflip
            self._update_options()

    def action_toggle_autoselect(self) -> None:
        """Toggle the ICCS autoselect option, if ICCS is the highlighted algorithm."""
        if self._highlighted_algorithm == "iccs":
            self._autoselect = not self._autoselect
            self._update_options()

    def action_toggle_all(self) -> None:
        """Toggle the MCCC all-seismograms option, if MCCC is the highlighted algorithm."""
        if self._highlighted_algorithm == "mccc":
            self._all_seis = not self._all_seis
            self._update_options()

    def action_select(self) -> None:
        """Trigger selection of the row under the cursor."""
        self.query_one(DataTable).action_select_cursor()

    def action_cancel(self) -> None:
        """Dismiss without choosing an algorithm."""
        self.dismiss(None)

__init__

__init__() -> None

Initialise the modal with all toggles off and ICCS as the highlighted algorithm.

Source code in src/aimbat/_tui/modals.py
def __init__(self) -> None:
    """Initialise the modal with all toggles off and ICCS as the highlighted algorithm."""
    super().__init__()
    self._autoflip = False
    self._autoselect = False
    self._all_seis = False
    self._highlighted_algorithm: str = "iccs"

action_cancel

action_cancel() -> None

Dismiss without choosing an algorithm.

Source code in src/aimbat/_tui/modals.py
def action_cancel(self) -> None:
    """Dismiss without choosing an algorithm."""
    self.dismiss(None)

action_select

action_select() -> None

Trigger selection of the row under the cursor.

Source code in src/aimbat/_tui/modals.py
def action_select(self) -> None:
    """Trigger selection of the row under the cursor."""
    self.query_one(DataTable).action_select_cursor()

action_toggle_all

action_toggle_all() -> None

Toggle the MCCC all-seismograms option, if MCCC is the highlighted algorithm.

Source code in src/aimbat/_tui/modals.py
def action_toggle_all(self) -> None:
    """Toggle the MCCC all-seismograms option, if MCCC is the highlighted algorithm."""
    if self._highlighted_algorithm == "mccc":
        self._all_seis = not self._all_seis
        self._update_options()

action_toggle_autoflip

action_toggle_autoflip() -> None

Toggle the ICCS autoflip option, if ICCS is the highlighted algorithm.

Source code in src/aimbat/_tui/modals.py
def action_toggle_autoflip(self) -> None:
    """Toggle the ICCS autoflip option, if ICCS is the highlighted algorithm."""
    if self._highlighted_algorithm == "iccs":
        self._autoflip = not self._autoflip
        self._update_options()

action_toggle_autoselect

action_toggle_autoselect() -> None

Toggle the ICCS autoselect option, if ICCS is the highlighted algorithm.

Source code in src/aimbat/_tui/modals.py
def action_toggle_autoselect(self) -> None:
    """Toggle the ICCS autoselect option, if ICCS is the highlighted algorithm."""
    if self._highlighted_algorithm == "iccs":
        self._autoselect = not self._autoselect
        self._update_options()

compose

compose() -> ComposeResult

Build the title, algorithm table, toggle options display and hint.

Source code in src/aimbat/_tui/modals.py
def compose(self) -> ComposeResult:
    """Build the title, algorithm table, toggle options display and hint."""
    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,
        )

on_mount

on_mount() -> None

Populate the algorithm table.

Source code in src/aimbat/_tui/modals.py
def on_mount(self) -> None:
    """Populate the algorithm table."""
    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()

row_highlighted

row_highlighted(event: RowHighlighted) -> None

Track the highlighted algorithm and show its option toggles.

Source code in src/aimbat/_tui/modals.py
@on(DataTable.RowHighlighted, "#align-table")
def row_highlighted(self, event: DataTable.RowHighlighted) -> None:
    """Track the highlighted algorithm and show its option toggles."""
    self._highlighted_algorithm = event.row_key.value or "iccs"
    self._update_options()

row_selected

row_selected(event: RowSelected) -> None

Dismiss with the chosen algorithm and the current toggle values.

Source code in src/aimbat/_tui/modals.py
@on(DataTable.RowSelected, "#align-table")
def row_selected(self, event: DataTable.RowSelected) -> None:
    """Dismiss with the chosen algorithm and the current toggle values."""
    key = event.row_key.value
    if key:
        self.dismiss((key, self._autoflip, self._autoselect, self._all_seis))

ConfirmModal

Bases: ModalScreen[bool | None]

Generic yes/no confirmation dialog.

Dismisses True on confirm, False on cancel.

Methods:

Name Description
__init__

Initialise the modal.

action_cancel

Dismiss with cancellation.

action_confirm

Dismiss with confirmation.

compose

Build the confirmation message and confirm/cancel hint.

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:
        """Build the confirmation message and confirm/cancel hint."""
        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:
        """Dismiss with confirmation."""
        self.dismiss(True)

    def action_cancel(self) -> None:
        """Dismiss with cancellation."""
        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

action_cancel

action_cancel() -> None

Dismiss with cancellation.

Source code in src/aimbat/_tui/modals.py
def action_cancel(self) -> None:
    """Dismiss with cancellation."""
    self.dismiss(False)

action_confirm

action_confirm() -> None

Dismiss with confirmation.

Source code in src/aimbat/_tui/modals.py
def action_confirm(self) -> None:
    """Dismiss with confirmation."""
    self.dismiss(True)

compose

compose() -> ComposeResult

Build the confirmation message and confirm/cancel hint.

Source code in src/aimbat/_tui/modals.py
def compose(self) -> ComposeResult:
    """Build the confirmation message and confirm/cancel hint."""
    with Container(id="confirm-dialog"):
        yield Label(self._message, classes=_CSS.TITLE)
        yield Label(
            _Hint.CONFIRM_CANCEL,
            classes=_CSS.HINT,
        )

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.

action_cancel

Close the modal.

compose

Build the title, rendered help Markdown and close hint.

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:
        """Build the title, rendered help Markdown and close hint."""
        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:
        """Close the modal."""
        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

action_cancel

action_cancel() -> None

Close the modal.

Source code in src/aimbat/_tui/modals.py
def action_cancel(self) -> None:
    """Close the modal."""
    self.dismiss(None)

compose

compose() -> ComposeResult

Build the title, rendered help Markdown and close hint.

Source code in src/aimbat/_tui/modals.py
def compose(self) -> ComposeResult:
    """Build the title, rendered help Markdown and close hint."""
    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)

InteractiveToolsModal

Bases: ModalScreen[ToolLaunchResult | None]

Menu for launching interactive matplotlib tools.

Options are toggled with key bindings so no Checkbox widgets are needed. Dismisses with a ToolLaunchResult or None on cancel.

Methods:

Name Description
__init__

Initialise the modal with context enabled and all-seismograms/causal defaults.

action_cancel

Dismiss without choosing a tool.

action_select

Trigger selection of the row under the cursor.

action_toggle_all

Toggle the all-seismograms option.

action_toggle_context

Toggle the context option.

action_toggle_zero_phase

Toggle the causal/zero-phase filter option, if the highlighted tool supports it.

compose

Build the title, tool table, toggle options display and hint.

on_mount

Populate the tool table and set the causal default for the first tool.

row_highlighted

Track the highlighted tool and reset the causal toggle to its default.

row_selected

Dismiss with the chosen tool and the current toggle values.

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

    Options are toggled with key bindings so no Checkbox widgets are needed.
    Dismisses with a `ToolLaunchResult` 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),
        Binding("z", "toggle_zero_phase", "Zero-phase", show=False),
    ]

    def __init__(self) -> None:
        """Initialise the modal with context enabled and all-seismograms/causal defaults."""
        super().__init__()
        self._use_context = True
        self._all_seis = False
        self._highlighted_tool: str = ""
        self._causal: bool = True

    def compose(self) -> ComposeResult:
        """Build the title, tool table, toggle options display and hint."""
        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:
        """Populate the tool table and set the causal default for the first tool."""
        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._highlighted_tool = _TOOLS[0][0]
        self._causal = CAUSAL_DEFAULTS.get(self._highlighted_tool, True)
        self._update_options()
        table.focus()

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

    @on(DataTable.RowHighlighted, "#tools-table")
    def row_highlighted(self, event: DataTable.RowHighlighted) -> None:
        """Track the highlighted tool and reset the causal toggle to its default."""
        self._highlighted_tool = event.row_key.value or ""
        self._causal = CAUSAL_DEFAULTS.get(self._highlighted_tool, True)
        self._update_options()

    @on(DataTable.RowSelected, "#tools-table")
    def row_selected(self, event: DataTable.RowSelected) -> None:
        """Dismiss with the chosen tool and the current toggle values."""
        key = event.row_key.value
        if key:
            causal = self._causal if key in CAUSAL_DEFAULTS else None
            self.dismiss(
                ToolLaunchResult(key, self._use_context, self._all_seis, causal)
            )

    def action_toggle_context(self) -> None:
        """Toggle the context option."""
        self._use_context = not self._use_context
        self._update_options()

    def action_toggle_all(self) -> None:
        """Toggle the all-seismograms option."""
        self._all_seis = not self._all_seis
        self._update_options()

    def action_toggle_zero_phase(self) -> None:
        """Toggle the causal/zero-phase filter option, if the highlighted tool supports it."""
        if self._highlighted_tool in CAUSAL_DEFAULTS:
            self._causal = not self._causal
            self._update_options()

    def action_select(self) -> None:
        """Trigger selection of the row under the cursor."""
        self.query_one(DataTable).action_select_cursor()

    def action_cancel(self) -> None:
        """Dismiss without choosing a tool."""
        self.dismiss(None)

__init__

__init__() -> None

Initialise the modal with context enabled and all-seismograms/causal defaults.

Source code in src/aimbat/_tui/modals.py
def __init__(self) -> None:
    """Initialise the modal with context enabled and all-seismograms/causal defaults."""
    super().__init__()
    self._use_context = True
    self._all_seis = False
    self._highlighted_tool: str = ""
    self._causal: bool = True

action_cancel

action_cancel() -> None

Dismiss without choosing a tool.

Source code in src/aimbat/_tui/modals.py
def action_cancel(self) -> None:
    """Dismiss without choosing a tool."""
    self.dismiss(None)

action_select

action_select() -> None

Trigger selection of the row under the cursor.

Source code in src/aimbat/_tui/modals.py
def action_select(self) -> None:
    """Trigger selection of the row under the cursor."""
    self.query_one(DataTable).action_select_cursor()

action_toggle_all

action_toggle_all() -> None

Toggle the all-seismograms option.

Source code in src/aimbat/_tui/modals.py
def action_toggle_all(self) -> None:
    """Toggle the all-seismograms option."""
    self._all_seis = not self._all_seis
    self._update_options()

action_toggle_context

action_toggle_context() -> None

Toggle the context option.

Source code in src/aimbat/_tui/modals.py
def action_toggle_context(self) -> None:
    """Toggle the context option."""
    self._use_context = not self._use_context
    self._update_options()

action_toggle_zero_phase

action_toggle_zero_phase() -> None

Toggle the causal/zero-phase filter option, if the highlighted tool supports it.

Source code in src/aimbat/_tui/modals.py
def action_toggle_zero_phase(self) -> None:
    """Toggle the causal/zero-phase filter option, if the highlighted tool supports it."""
    if self._highlighted_tool in CAUSAL_DEFAULTS:
        self._causal = not self._causal
        self._update_options()

compose

compose() -> ComposeResult

Build the title, tool table, toggle options display and hint.

Source code in src/aimbat/_tui/modals.py
def compose(self) -> ComposeResult:
    """Build the title, tool table, toggle options display and hint."""
    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,
        )

on_mount

on_mount() -> None

Populate the tool table and set the causal default for the first tool.

Source code in src/aimbat/_tui/modals.py
def on_mount(self) -> None:
    """Populate the tool table and set the causal default for the first tool."""
    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._highlighted_tool = _TOOLS[0][0]
    self._causal = CAUSAL_DEFAULTS.get(self._highlighted_tool, True)
    self._update_options()
    table.focus()

row_highlighted

row_highlighted(event: RowHighlighted) -> None

Track the highlighted tool and reset the causal toggle to its default.

Source code in src/aimbat/_tui/modals.py
@on(DataTable.RowHighlighted, "#tools-table")
def row_highlighted(self, event: DataTable.RowHighlighted) -> None:
    """Track the highlighted tool and reset the causal toggle to its default."""
    self._highlighted_tool = event.row_key.value or ""
    self._causal = CAUSAL_DEFAULTS.get(self._highlighted_tool, True)
    self._update_options()

row_selected

row_selected(event: RowSelected) -> None

Dismiss with the chosen tool and the current toggle values.

Source code in src/aimbat/_tui/modals.py
@on(DataTable.RowSelected, "#tools-table")
def row_selected(self, event: DataTable.RowSelected) -> None:
    """Dismiss with the chosen tool and the current toggle values."""
    key = event.row_key.value
    if key:
        causal = self._causal if key in CAUSAL_DEFAULTS else None
        self.dismiss(
            ToolLaunchResult(key, self._use_context, self._all_seis, causal)
        )

NoProjectModal

Bases: ModalScreen[bool]

Shown on startup when no project exists.

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

Methods:

Name Description
action_create

Dismiss, indicating a project should be created.

action_quit_app

Dismiss, indicating the application should quit.

compose

Build the no-project message and create/quit hint.

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:
        """Build the no-project message and create/quit hint."""
        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:
        """Dismiss, indicating a project should be created."""
        self.dismiss(True)

    def action_quit_app(self) -> None:
        """Dismiss, indicating the application should quit."""
        self.dismiss(False)

action_create

action_create() -> None

Dismiss, indicating a project should be created.

Source code in src/aimbat/_tui/modals.py
def action_create(self) -> None:
    """Dismiss, indicating a project should be created."""
    self.dismiss(True)

action_quit_app

action_quit_app() -> None

Dismiss, indicating the application should quit.

Source code in src/aimbat/_tui/modals.py
def action_quit_app(self) -> None:
    """Dismiss, indicating the application should quit."""
    self.dismiss(False)

compose

compose() -> ComposeResult

Build the no-project message and create/quit hint.

Source code in src/aimbat/_tui/modals.py
def compose(self) -> ComposeResult:
    """Build the no-project message and create/quit hint."""
    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,
        )

ParameterInputModal

Bases: ModalScreen[str | None]

Modal for entering a new numeric/timedelta parameter value.

Methods:

Name Description
__init__

Initialise the modal.

action_cancel

Dismiss without a value.

action_save

Dismiss with the current input value.

compose

Build the title, current-value hint, input field and save/cancel hint.

on_mount

Focus the input field.

submitted

Dismiss with the submitted value.

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:
        """Build the title, current-value hint, input field and save/cancel hint."""
        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:
        """Focus the input field."""
        self.query_one(Input).focus()

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

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

    def action_cancel(self) -> None:
        """Dismiss without a value."""
        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

action_cancel

action_cancel() -> None

Dismiss without a value.

Source code in src/aimbat/_tui/modals.py
def action_cancel(self) -> None:
    """Dismiss without a value."""
    self.dismiss(None)

action_save

action_save() -> None

Dismiss with the current input value.

Source code in src/aimbat/_tui/modals.py
def action_save(self) -> None:
    """Dismiss with the current input value."""
    self.dismiss(self.query_one("#param-input", Input).value.strip())

compose

compose() -> ComposeResult

Build the title, current-value hint, input field and save/cancel hint.

Source code in src/aimbat/_tui/modals.py
def compose(self) -> ComposeResult:
    """Build the title, current-value hint, input field and save/cancel hint."""
    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,
        )

on_mount

on_mount() -> None

Focus the input field.

Source code in src/aimbat/_tui/modals.py
def on_mount(self) -> None:
    """Focus the input field."""
    self.query_one(Input).focus()

submitted

submitted(event: Submitted) -> None

Dismiss with the submitted value.

Source code in src/aimbat/_tui/modals.py
@on(Input.Submitted)
def submitted(self, event: Input.Submitted) -> None:
    """Dismiss with the submitted value."""
    self.dismiss(event.value.strip())

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.

action_cancel

Close the modal, reporting whether any parameter was changed.

action_select

Trigger selection of the row under the cursor.

compose

Build the title, parameter table and navigate/edit/close hint.

on_mount

Configure the parameter table's columns and load its rows.

row_selected

Open the edit dialog for the selected parameter.

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:
        """Build the title, parameter table and navigate/edit/close hint."""
        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:
        """Configure the parameter table's columns and load its rows."""
        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:
        """Open the edit dialog for the selected parameter."""
        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:
                new_val: Timedelta | float
                if isinstance(current, Timedelta):
                    new_val = 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: Timedelta | bool | float | int | str
    ) -> 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,
                )
        except ValidationError as exc:
            self.notify(format_validation_error(exc), 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:
        """Trigger selection of the row under the cursor."""
        self.query_one(DataTable).action_select_cursor()

    def action_cancel(self) -> None:
        """Close the modal, reporting whether any parameter was changed."""
        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

action_cancel

action_cancel() -> None

Close the modal, reporting whether any parameter was changed.

Source code in src/aimbat/_tui/modals.py
def action_cancel(self) -> None:
    """Close the modal, reporting whether any parameter was changed."""
    self.dismiss(self._changed)

action_select

action_select() -> None

Trigger selection of the row under the cursor.

Source code in src/aimbat/_tui/modals.py
def action_select(self) -> None:
    """Trigger selection of the row under the cursor."""
    self.query_one(DataTable).action_select_cursor()

compose

compose() -> ComposeResult

Build the title, parameter table and navigate/edit/close hint.

Source code in src/aimbat/_tui/modals.py
def compose(self) -> ComposeResult:
    """Build the title, parameter table and navigate/edit/close hint."""
    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)

on_mount

on_mount() -> None

Configure the parameter table's columns and load its rows.

Source code in src/aimbat/_tui/modals.py
def on_mount(self) -> None:
    """Configure the parameter table's columns and load its rows."""
    table = self.query_one(DataTable)
    table.cursor_type = "row"
    table.add_columns("Parameter", "Value", "Description")
    self._populate()
    table.focus()

row_selected

row_selected(event: RowSelected) -> None

Open the edit dialog for the selected parameter.

Source code in src/aimbat/_tui/modals.py
@on(DataTable.RowSelected)
def row_selected(self, event: DataTable.RowSelected) -> None:
    """Open the edit dialog for the selected parameter."""
    attr = event.row_key.value
    if not attr:
        return
    self._edit_parameter(attr)

SchemaStaleModal

Bases: ModalScreen[bool]

Shown on startup when the project's database schema is out of date.

Blocks entry to the main UI entirely, mirroring NoProjectModal - proceeding into panels that query columns the live schema doesn't have would crash with a raw sqlalchemy.exc.OperationalError from whichever panel happens to touch the drifted table first, rather than a clean, attributable message. Dismisses True if the user chose to upgrade now, False to quit.

Methods:

Name Description
__init__

Initialise the modal.

action_quit_app

Dismiss, indicating the application should quit.

action_upgrade

Dismiss, indicating the database should be upgraded.

compose

Build the staleness message and upgrade/quit hint.

Source code in src/aimbat/_tui/modals.py
class SchemaStaleModal(ModalScreen[bool]):
    """Shown on startup when the project's database schema is out of date.

    Blocks entry to the main UI entirely, mirroring `NoProjectModal` -
    proceeding into panels that query columns the live schema doesn't have
    would crash with a raw `sqlalchemy.exc.OperationalError` from whichever
    panel happens to touch the drifted table first, rather than a clean,
    attributable message. Dismisses True if the user chose to upgrade now,
    False to quit.
    """

    BINDINGS = [
        Binding("u", "upgrade", show=False),
        Binding("enter", "upgrade", show=False),
        Binding("q", "quit_app", show=False),
        Binding("escape", "quit_app", show=False),
    ]

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

        Args:
            message: The staleness message from `_build_staleness_warning`.
        """
        super().__init__()
        self._message = message

    def compose(self) -> ComposeResult:
        """Build the staleness message and upgrade/quit hint."""
        with Container(id="confirm-dialog"):
            yield Label(self._message, classes=_CSS.TITLE)
            yield Label(
                (
                    "[@click='screen.upgrade'][bold]u[/bold] / ⏎ upgrade now[/]   "
                    + "[@click='screen.quit_app'][bold]q[/bold] / ⎋ quit[/]"
                ),
                classes=_CSS.HINT,
            )

    def action_upgrade(self) -> None:
        """Dismiss, indicating the database should be upgraded."""
        self.dismiss(True)

    def action_quit_app(self) -> None:
        """Dismiss, indicating the application should quit."""
        self.dismiss(False)

__init__

__init__(message: str) -> None

Initialise the modal.

Parameters:

Name Type Description Default
message str

The staleness message from _build_staleness_warning.

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

    Args:
        message: The staleness message from `_build_staleness_warning`.
    """
    super().__init__()
    self._message = message

action_quit_app

action_quit_app() -> None

Dismiss, indicating the application should quit.

Source code in src/aimbat/_tui/modals.py
def action_quit_app(self) -> None:
    """Dismiss, indicating the application should quit."""
    self.dismiss(False)

action_upgrade

action_upgrade() -> None

Dismiss, indicating the database should be upgraded.

Source code in src/aimbat/_tui/modals.py
def action_upgrade(self) -> None:
    """Dismiss, indicating the database should be upgraded."""
    self.dismiss(True)

compose

compose() -> ComposeResult

Build the staleness message and upgrade/quit hint.

Source code in src/aimbat/_tui/modals.py
def compose(self) -> ComposeResult:
    """Build the staleness message and upgrade/quit hint."""
    with Container(id="confirm-dialog"):
        yield Label(self._message, classes=_CSS.TITLE)
        yield Label(
            (
                "[@click='screen.upgrade'][bold]u[/bold] / ⏎ upgrade now[/]   "
                + "[@click='screen.quit_app'][bold]q[/bold] / ⎋ quit[/]"
            ),
            classes=_CSS.HINT,
        )

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.

action_cancel

Dismiss without choosing an action.

action_select

Trigger selection of the row under the cursor.

action_toggle_all

Toggle the all-seismograms option, if the highlighted action is a preview action.

action_toggle_context

Toggle the context option, if the highlighted action is a preview action.

compose

Build the title, action table, toggle options display and hint.

on_mount

Populate the action table from _actions.

row_highlighted

Track the highlighted action and show its toggles if it is a preview action.

row_selected

Dismiss with the chosen action and the current toggle values.

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, actions: list[RowAction]) -> None:
        """Initialise the modal.

        Args:
            title: Heading displayed above the action list.
            actions: Row actions shown as rows (same registry the Snapshots
                tab's footer hotkeys are built from).
        """
        super().__init__()
        self._title = title
        self._actions = actions
        self._use_context = True
        self._all_seis = False
        self._highlighted: str = ""

    def compose(self) -> ComposeResult:
        """Build the title, action table, toggle options display and hint."""
        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:
        """Populate the action table from `_actions`."""
        table = self.query_one(DataTable)
        table.cursor_type = "row"
        table.add_column("action")
        for action in self._actions:
            table.add_row(action.label, key=action.id)
        table.styles.height = len(self._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:
        """Track the highlighted action and show its toggles if it is a preview action."""
        self._highlighted = event.row_key.value or ""
        self._update_options()

    @on(DataTable.RowSelected, "#snapshot-action-table")
    def row_selected(self, event: DataTable.RowSelected) -> None:
        """Dismiss with the chosen action and the current toggle values."""
        key = event.row_key.value
        if key:
            self.dismiss((key, self._use_context, self._all_seis))

    def action_toggle_context(self) -> None:
        """Toggle the context option, if the highlighted action is a preview action."""
        if self._highlighted in _PREVIEW_ACTIONS:
            self._use_context = not self._use_context
            self._update_options()

    def action_toggle_all(self) -> None:
        """Toggle the all-seismograms option, if the highlighted action is a preview action."""
        if self._highlighted in _PREVIEW_ACTIONS:
            self._all_seis = not self._all_seis
            self._update_options()

    def action_select(self) -> None:
        """Trigger selection of the row under the cursor."""
        self.query_one(DataTable).action_select_cursor()

    def action_cancel(self) -> None:
        """Dismiss without choosing an action."""
        self.dismiss(None)

__init__

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

Initialise the modal.

Parameters:

Name Type Description Default
title str

Heading displayed above the action list.

required
actions list[RowAction]

Row actions shown as rows (same registry the Snapshots tab's footer hotkeys are built from).

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

    Args:
        title: Heading displayed above the action list.
        actions: Row actions shown as rows (same registry the Snapshots
            tab's footer hotkeys are built from).
    """
    super().__init__()
    self._title = title
    self._actions = actions
    self._use_context = True
    self._all_seis = False
    self._highlighted: str = ""

action_cancel

action_cancel() -> None

Dismiss without choosing an action.

Source code in src/aimbat/_tui/modals.py
def action_cancel(self) -> None:
    """Dismiss without choosing an action."""
    self.dismiss(None)

action_select

action_select() -> None

Trigger selection of the row under the cursor.

Source code in src/aimbat/_tui/modals.py
def action_select(self) -> None:
    """Trigger selection of the row under the cursor."""
    self.query_one(DataTable).action_select_cursor()

action_toggle_all

action_toggle_all() -> None

Toggle the all-seismograms option, if the highlighted action is a preview action.

Source code in src/aimbat/_tui/modals.py
def action_toggle_all(self) -> None:
    """Toggle the all-seismograms option, if the highlighted action is a preview action."""
    if self._highlighted in _PREVIEW_ACTIONS:
        self._all_seis = not self._all_seis
        self._update_options()

action_toggle_context

action_toggle_context() -> None

Toggle the context option, if the highlighted action is a preview action.

Source code in src/aimbat/_tui/modals.py
def action_toggle_context(self) -> None:
    """Toggle the context option, if the highlighted action is a preview action."""
    if self._highlighted in _PREVIEW_ACTIONS:
        self._use_context = not self._use_context
        self._update_options()

compose

compose() -> ComposeResult

Build the title, action table, toggle options display and hint.

Source code in src/aimbat/_tui/modals.py
def compose(self) -> ComposeResult:
    """Build the title, action table, toggle options display and hint."""
    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)

on_mount

on_mount() -> None

Populate the action table from _actions.

Source code in src/aimbat/_tui/modals.py
def on_mount(self) -> None:
    """Populate the action table from `_actions`."""
    table = self.query_one(DataTable)
    table.cursor_type = "row"
    table.add_column("action")
    for action in self._actions:
        table.add_row(action.label, key=action.id)
    table.styles.height = len(self._actions)
    table.focus()

row_highlighted

row_highlighted(event: RowHighlighted) -> None

Track the highlighted action and show its toggles if it is a preview action.

Source code in src/aimbat/_tui/modals.py
@on(DataTable.RowHighlighted, "#snapshot-action-table")
def row_highlighted(self, event: DataTable.RowHighlighted) -> None:
    """Track the highlighted action and show its toggles if it is a preview action."""
    self._highlighted = event.row_key.value or ""
    self._update_options()

row_selected

row_selected(event: RowSelected) -> None

Dismiss with the chosen action and the current toggle values.

Source code in src/aimbat/_tui/modals.py
@on(DataTable.RowSelected, "#snapshot-action-table")
def row_selected(self, event: DataTable.RowSelected) -> None:
    """Dismiss with the chosen action and the current toggle values."""
    key = event.row_key.value
    if key:
        self.dismiss((key, self._use_context, self._all_seis))

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.

Methods:

Name Description
action_cancel

Dismiss without creating a snapshot.

action_save

Dismiss with the current comment input value.

compose

Build the title, comment input and save/cancel hint.

on_mount

Focus the comment input field.

submitted

Dismiss with the submitted comment.

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:
        """Build the title, comment input and save/cancel hint."""
        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:
        """Focus the comment input field."""
        self.query_one(Input).focus()

    @on(Input.Submitted)
    def submitted(self, event: Input.Submitted) -> None:
        """Dismiss with the submitted comment."""
        self.dismiss(event.value.strip())

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

    def action_cancel(self) -> None:
        """Dismiss without creating a snapshot."""
        self.dismiss(None)

action_cancel

action_cancel() -> None

Dismiss without creating a snapshot.

Source code in src/aimbat/_tui/modals.py
def action_cancel(self) -> None:
    """Dismiss without creating a snapshot."""
    self.dismiss(None)

action_save

action_save() -> None

Dismiss with the current comment input value.

Source code in src/aimbat/_tui/modals.py
def action_save(self) -> None:
    """Dismiss with the current comment input value."""
    self.dismiss(self.query_one("#param-input", Input).value.strip())

compose

compose() -> ComposeResult

Build the title, comment input and save/cancel hint.

Source code in src/aimbat/_tui/modals.py
def compose(self) -> ComposeResult:
    """Build the title, comment input and save/cancel hint."""
    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,
        )

on_mount

on_mount() -> None

Focus the comment input field.

Source code in src/aimbat/_tui/modals.py
def on_mount(self) -> None:
    """Focus the comment input field."""
    self.query_one(Input).focus()

submitted

submitted(event: Submitted) -> None

Dismiss with the submitted comment.

Source code in src/aimbat/_tui/modals.py
@on(Input.Submitted)
def submitted(self, event: Input.Submitted) -> None:
    """Dismiss with the submitted comment."""
    self.dismiss(event.value.strip())

SnapshotDetailsModal

Bases: ModalScreen[None]

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

Methods:

Name Description
__init__

Initialise the modal.

action_cancel

Close the modal.

compose

Build the title, read-only parameter table and close hint.

on_mount

Populate the table from _rows.

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:
        """Build the title, read-only parameter table and close hint."""
        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:
        """Populate the table from `_rows`."""
        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:
        """Close the modal."""
        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), ...]

action_cancel

action_cancel() -> None

Close the modal.

Source code in src/aimbat/_tui/modals.py
def action_cancel(self) -> None:
    """Close the modal."""
    self.dismiss(None)

compose

compose() -> ComposeResult

Build the title, read-only parameter table and close hint.

Source code in src/aimbat/_tui/modals.py
def compose(self) -> ComposeResult:
    """Build the title, read-only parameter table and close hint."""
    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)

on_mount

on_mount() -> None

Populate the table from _rows.

Source code in src/aimbat/_tui/modals.py
def on_mount(self) -> None:
    """Populate the table from `_rows`."""
    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

ToolLaunchResult

Bases: NamedTuple

Result of choosing a tool in InteractiveToolsModal.

causal is None for tools that don't take a causal argument.

Parameters:

Name Type Description Default
tool ForwardRef
None
context ForwardRef
None
all_seismograms ForwardRef
None
causal ForwardRef
None
Source code in src/aimbat/_tui/modals.py
class ToolLaunchResult(NamedTuple):
    """Result of choosing a tool in `InteractiveToolsModal`.

    `causal` is `None` for tools that don't take a causal argument.
    """

    tool: str
    context: bool
    all_seismograms: bool
    causal: bool | None