Skip to content

aimbat._tui

AIMBAT Terminal User Interface.

Modules:

Name Description
app

AIMBAT Terminal User Interface application.

modals

Modal screens for the AIMBAT TUI.

app

AIMBAT Terminal User Interface application.

Classes:

Name Description
AimbatTUI

AIMBAT Terminal User Interface.

Functions:

Name Description
main

Entry point for the AIMBAT TUI.

AimbatTUI

Bases: App[None]

AIMBAT Terminal User Interface.

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

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

    BINDINGS = [
        Binding("e", "switch_event", "Events", show=True),
        Binding("d", "add_data", "Add Data", show=True),
        Binding("p", "open_interactive_tools", "Interactive 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("t", "toggle_theme", "Theme", show=True),
        Binding("H", "vim_left", "Vim left", show=False),
        Binding("L", "vim_right", "Vim right", show=False),
        Binding("q", "quit", "Quit", show=True),
    ]

    def compose(self) -> ComposeResult:
        yield Header()
        yield Static(id="event-bar")
        with TabbedContent(initial="tab-seismograms"):
            with TabPane("Seismograms", id="tab-seismograms"):
                yield VimDataTable(id="seismogram-table")
            with TabPane("Parameters", id="tab-parameters"):
                yield VimDataTable(id="parameter-table")
            with TabPane("Stations", id="tab-stations"):
                yield VimDataTable(id="station-table")
            with TabPane("Snapshots", id="tab-snapshots"):
                yield VimDataTable(id="snapshot-table")
        yield Footer()

    def on_mount(self) -> None:
        self._bound_iccs: BoundICCS | None = None
        self._iccs_last_modified_seen: Timestamp | None = None
        self._active_tab: str = "tab-seismograms"

        self.theme = _DEFAULT_THEME

        self._setup_seismogram_table()
        self._setup_parameter_table()
        self._setup_station_table()
        self._setup_snapshot_table()

        self.set_interval(5, self._check_iccs_staleness)
        self._create_iccs()
        self.refresh_all()

    @on(TabbedContent.TabActivated)
    def on_tab_activated(self, event: TabbedContent.TabActivated) -> None:
        if event.pane.id:
            self._active_tab = event.pane.id
            self.refresh_bindings()
            if not isinstance(self.focused, Tabs):
                try:
                    event.pane.query_one(DataTable).focus()
                except Exception:
                    pass

    def check_action(self, action: str, parameters: tuple[object, ...]) -> bool | None:
        tab = getattr(self, "_active_tab", "")
        if action == "new_snapshot":
            return True if tab == "tab-snapshots" else False
        return True

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

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

        ICCS construction reads waveform data, so it must not block the asyncio event loop.
        """
        self._bound_iccs = None
        self._worker_create_iccs()

    @work(thread=True)
    def _worker_create_iccs(self) -> None:
        """Background worker: create ICCS instance without blocking the UI."""
        try:
            with Session(engine) as session:
                active_event = get_active_event(session)
                bound_iccs = create_iccs_instance(session, active_event)
        except (NoResultFound, RuntimeError):
            return
        except Exception as exc:
            self.call_from_thread(
                self.notify, f"ICCS init failed: {exc}", severity="error"
            )
            return
        self.call_from_thread(self._assign_iccs, bound_iccs)

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

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

    def _setup_seismogram_table(self) -> None:
        t = self.query_one("#seismogram-table", DataTable)
        t.cursor_type = "row"
        t.add_columns(
            "ID", "Network", "Station", "Channel", "Select", "Flip", "Δt (s)", "CC"
        )

    def _setup_parameter_table(self) -> None:
        t = self.query_one("#parameter-table", DataTable)
        t.cursor_type = "row"
        t.add_columns("Parameter", "Value", "Description")

    def _setup_station_table(self) -> None:
        t = self.query_one("#station-table", DataTable)
        t.cursor_type = "row"
        t.add_columns(
            "ID", "Network", "Name", "Location", "Channel", "Lat °", "Lon °", "Elev m"
        )

    def _setup_snapshot_table(self) -> None:
        t = self.query_one("#snapshot-table", DataTable)
        t.cursor_type = "row"
        t.add_columns("ID", "Date (UTC)", "Comment", "Seismograms", "Select", "Flip")

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

    def refresh_all(self) -> None:
        self._refresh_event_bar()
        self._refresh_seismograms()
        self._refresh_parameters()
        self._refresh_stations()
        self._refresh_snapshots()

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

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

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

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

        ccnorm_map: dict[uuid.UUID, float] = {}
        if self._bound_iccs is not None:
            try:
                for iccs_seis, ccnorm in zip(
                    self._bound_iccs.iccs.seismograms, self._bound_iccs.iccs.ccnorms
                ):
                    ccnorm_map[iccs_seis.extra["id"]] = float(ccnorm)
            except Exception:
                pass

        try:
            with Session(engine) as session:
                event = get_active_event(session)
                seismograms = sorted(
                    event.seismograms,
                    key=lambda s: ccnorm_map.get(s.id, -2.0),
                    reverse=True,
                )
                for seis in seismograms:
                    station = seis.station
                    params = seis.parameters
                    short_id = str(seis.id)[:8]
                    net = station.network if station else "—"
                    name = station.name if station else "—"
                    chan = station.channel if station else "—"
                    selected = "✓" if params and params.select else "✗"
                    flipped = "↕" if params and params.flip else " "
                    t1 = params.t1 if params else None
                    if seis.t0 and t1:
                        dt = f"{(t1 - seis.t0).total_seconds():.3f}"
                    else:
                        dt = "—"
                    cc = f"{ccnorm_map[seis.id]:.3f}" if seis.id in ccnorm_map else "—"
                    table.add_row(
                        short_id,
                        net,
                        name,
                        chan,
                        selected,
                        flipped,
                        dt,
                        cc,
                        key=str(seis.id),
                    )
        except (NoResultFound, RuntimeError):
            pass
        if table.row_count > 0:
            table.move_cursor(row=min(saved_row, table.row_count - 1))

    def _refresh_parameters(self) -> None:
        table = self.query_one("#parameter-table", DataTable)
        saved_row = table.cursor_row
        table.clear()
        try:
            with Session(engine) as session:
                event = get_active_event(session)
                p = event.parameters
                for attr, field_info in AimbatEventParametersBase.model_fields.items():
                    value = getattr(p, attr)
                    if isinstance(value, bool):
                        display = "✓" if value else "✗"
                    elif isinstance(value, Timedelta):
                        display = f"{value.total_seconds():.2f}"
                    else:
                        display = f"{value}"
                    label = field_info.title or attr
                    desc = field_info.description or ""
                    table.add_row(label, display, desc, key=attr)
        except (NoResultFound, RuntimeError):
            pass
        if table.row_count > 0:
            table.move_cursor(row=min(saved_row, table.row_count - 1))

    def _refresh_stations(self) -> None:
        table = self.query_one("#station-table", DataTable)
        saved_row = table.cursor_row
        table.clear()
        try:
            with Session(engine) as session:
                event = get_active_event(session)
                seen: set[uuid.UUID] = set()
                for seis in event.seismograms:
                    st = seis.station
                    if st and st.id not in seen:
                        seen.add(st.id)
                        short_id = str(st.id)[:8]
                        lat = f"{st.latitude:.3f}" if st.latitude is not None else "—"
                        lon = f"{st.longitude:.3f}" if st.longitude is not None else "—"
                        elev = (
                            f"{st.elevation:.0f}" if st.elevation is not None else "—"
                        )
                        table.add_row(
                            short_id,
                            st.network,
                            st.name,
                            st.location or "—",
                            st.channel,
                            lat,
                            lon,
                            elev,
                            key=str(st.id),
                        )
        except (NoResultFound, RuntimeError):
            pass
        if table.row_count > 0:
            table.move_cursor(row=min(saved_row, table.row_count - 1))

    def _refresh_snapshots(self) -> None:
        table = self.query_one("#snapshot-table", DataTable)
        saved_row = table.cursor_row
        table.clear()
        try:
            with Session(engine) as session:
                event = get_active_event(session)
                for snap in event.snapshots:
                    short_id = str(snap.id)[:8]
                    date_str = str(snap.date)[:19] if snap.date else "—"
                    comment = snap.comment or "—"
                    seismogram_count = str(snap.seismogram_count)
                    selected_count = str(snap.selected_seismogram_count)
                    flipped_count = str(snap.flipped_seismogram_count)
                    table.add_row(
                        short_id,
                        date_str,
                        comment,
                        seismogram_count,
                        selected_count,
                        flipped_count,
                        key=str(snap.id),
                    )
        except (NoResultFound, RuntimeError):
            pass
        if table.row_count > 0:
            table.move_cursor(row=min(saved_row, table.row_count - 1))

    # ------------------------------------------------------------------
    # Parameter editing
    # ------------------------------------------------------------------

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

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

    @on(DataTable.RowSelected, "#snapshot-table")
    def snapshot_row_selected(self, event: DataTable.RowSelected) -> None:
        if event.row_key.value:
            self._open_row_action_menu(
                "tab-snapshots",
                event.row_key.value,
                f"Snapshot  {event.row_key.value[:8]}",
            )

    @on(DataTable.RowSelected, "#parameter-table")
    def parameter_row_selected(self, event: DataTable.RowSelected) -> None:
        attr = event.row_key.value
        if not attr:
            return
        self._edit_parameter(attr)

    def _edit_parameter(self, attr: str) -> None:
        """Toggle a bool parameter, or open input modal for others."""
        try:
            with Session(engine) as session:
                active_event = get_active_event(session)
                current = getattr(active_event.parameters, attr)
        except (NoResultFound, RuntimeError) as exc:
            self.notify(str(exc), severity="error")
            return

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

        # Numeric / timedelta — open input modal
        if isinstance(current, Timedelta):
            current_str = f"{current.total_seconds():.2f}"
            unit = "s"
        else:
            current_str = f"{current}"
            unit = ""

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

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

    def _apply_parameter(self, attr: str, value: object) -> None:
        """Write a parameter to the DB and sync to the in-memory ICCS object."""
        iccs = self._bound_iccs.iccs if self._bound_iccs is not None else None

        # Validate with ICCS first — before touching the DB — so invalid values
        # are rejected without being persisted.
        if iccs is not None and hasattr(iccs, attr):
            try:
                setattr(iccs, attr, value)
                iccs.clear_cache()
            except ValueError as exc:
                self.notify(str(exc), severity="error")
                return

        try:
            with Session(engine) as session:
                active_event = get_active_event(session)
                if attr in {p.value for p in EventParameter}:
                    set_event_parameter(
                        session, active_event, EventParameter(attr), value
                    )  # type: ignore[call-overload]
                else:
                    # mccc_damp / mccc_min_ccnorm — not in EventParameter enum
                    validated = AimbatEventParametersBase.model_validate(
                        active_event.parameters, update={attr: value}
                    )
                    setattr(active_event.parameters, attr, getattr(validated, attr))
                    session.add(active_event)
                    session.commit()
        except ValidationError as exc:
            msgs = "; ".join(
                e["msg"].removeprefix("Value error, ") for e in exc.errors()
            )
            self.notify(msgs, severity="error")
            self._create_iccs()  # revert ICCS to DB state
            return
        except Exception as exc:
            self.notify(str(exc), severity="error")
            self._create_iccs()  # revert ICCS to DB state
            return

        if self._bound_iccs is None:
            # Parameter change may have fixed previously invalid ranges.
            self._create_iccs()
        else:
            # Acknowledge our own write so staleness check doesn't recreate.
            self._bound_iccs.created_at = Timestamp.now("UTC")

        self._refresh_parameters()
        self._refresh_seismograms()
        self._refresh_event_bar()
        self.notify(f"{attr} updated", timeout=2)

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

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

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

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

    def _handle_row_action(self, tab: str, item_id: str, action: str | None) -> None:
        if action == "delete":
            self._confirm_delete(tab, item_id)
        elif action == "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 _toggle_seismogram_bool(self, item_id: str, param: SeismogramParameter) -> None:
        try:
            seis_uuid = uuid.UUID(item_id)
            with Session(engine) as session:
                seis = session.get(AimbatSeismogram, seis_uuid)
                if seis is None:
                    raise ValueError(f"Seismogram {item_id} not found")
                new_value = not getattr(seis.parameters, param)
                setattr(seis.parameters, param, new_value)
                session.add(seis)
                session.commit()
            if self._bound_iccs is not None:
                for iccs_seis in self._bound_iccs.iccs.seismograms:
                    if iccs_seis.extra.get("id") == seis_uuid:
                        setattr(iccs_seis, param, new_value)
                        self._bound_iccs.iccs.clear_cache()
                        self._bound_iccs.created_at = Timestamp.now("UTC")
                        break
            self._refresh_seismograms()
            self.notify(f"{param} toggled", timeout=2)
        except Exception as exc:
            self.notify(str(exc), severity="error")

    def _reset_seismogram_parameters(self, item_id: str) -> None:
        try:
            with Session(engine) as session:
                reset_seismogram_parameters_by_id(session, uuid.UUID(item_id))
            self.refresh_all()
            self.notify("Seismogram parameters reset", timeout=2)
        except Exception as exc:
            self.notify(str(exc), severity="error")

    def _confirm_delete(self, tab: str, item_id: str) -> None:
        messages = {
            "tab-seismograms": "Delete this seismogram?",
            "tab-stations": "Delete this station and all its seismograms?",
            "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 == "tab-seismograms":
                    with Session(engine) as session:
                        delete_seismogram_by_id(session, uuid.UUID(item_id))
                    self._create_iccs()
                    self.refresh_all()
                    self.notify("Seismogram deleted", timeout=2)
                elif tab == "tab-stations":
                    with Session(engine) as session:
                        delete_station_by_id(session, uuid.UUID(item_id))
                    self._create_iccs()
                    self.refresh_all()
                    self.notify("Station deleted", timeout=2)
                elif tab == "tab-snapshots":
                    with Session(engine) as session:
                        delete_snapshot_by_id(session, uuid.UUID(item_id))
                    self._refresh_snapshots()
                    self.notify("Snapshot deleted", timeout=2)
            except Exception as exc:
                self.notify(str(exc), severity="error")

        self.push_screen(ConfirmModal(msg), on_confirm)

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

    def _confirm_rollback(self, snap_id: str) -> None:
        def on_confirm(confirmed: bool | None) -> None:
            if not confirmed:
                return
            try:
                with Session(engine) as session:
                    rollback_to_snapshot_by_id(session, uuid.UUID(snap_id))
                    if self._bound_iccs is not None:
                        active_event = get_active_event(session)
                        sync_iccs_parameters(
                            session, active_event, self._bound_iccs.iccs
                        )
                        self._bound_iccs.created_at = Timestamp.now("UTC")
                if self._bound_iccs is None:
                    self._create_iccs()
                self.refresh_all()
                self.notify("Rolled back to snapshot", timeout=3)
            except Exception as exc:
                self.notify(str(exc), severity="error")

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

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

    def action_switch_event(self) -> None:
        def on_result(event_id: uuid.UUID | None) -> None:
            if event_id is not None:
                self._create_iccs()
            self.refresh_all()

        self.push_screen(EventSwitcherModal(), on_result)

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

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

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

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

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

    def _require_iccs(self) -> bool:
        """Return True if ICCS is ready; show a contextual warning and return False otherwise."""
        if self._bound_iccs is not None:
            return True
        try:
            with Session(engine) as session:
                get_active_event(session)
            self.notify(
                "ICCS not ready — check event parameters (Parameters tab)",
                severity="warning",
            )
        except (NoResultFound, RuntimeError):
            self.notify("No active event — press e to select one", severity="warning")
        return False

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

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

        self.push_screen(InteractiveToolsModal(), on_result)

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

        Uses the long-lived ICCS instance (waveform data already loaded) and runs
        matplotlib on the main thread via App.suspend(), which is the correct
        Textual pattern for blocking terminal-adjacent processes.
        """
        if self._bound_iccs is None:
            self.notify("ICCS not ready — please wait", severity="warning")
            return
        _TOOL_LABELS = {
            "phase": "Phase arrival (t1)",
            "window": "Time window",
            "ccnorm": "Min CC norm",
        }
        tool_label = _TOOL_LABELS.get(tool, tool)

        try:
            with self.suspend():
                console = Console()
                console.clear()
                console.print(
                    Panel(
                        f"[bold]{tool_label}[/bold]\n\n"
                        "Close the matplotlib window to return to AIMBAT.",
                        title="Interactive Tool Running",
                        border_style="bright_blue",
                        padding=(1, 4),
                    )
                )
                with Session(engine) as session:
                    active_event = get_active_event(session)
                    if tool == "phase":
                        update_pick(
                            session,
                            self._bound_iccs.iccs,
                            context,
                            all_seis,
                            False,
                            return_fig=False,
                        )
                    elif tool == "window":
                        update_timewindow(
                            session,
                            active_event,
                            self._bound_iccs.iccs,
                            context,
                            all_seis,
                            False,
                            return_fig=False,
                        )
                    elif tool == "ccnorm":
                        update_min_ccnorm(
                            session,
                            active_event,
                            self._bound_iccs.iccs,
                            context,
                            all_seis,
                            return_fig=False,
                        )
                console.clear()
        except Exception as exc:
            self.notify(str(exc), severity="error")
            return
        self._bound_iccs.created_at = Timestamp.now("UTC")
        self._refresh_parameters()
        self._refresh_seismograms()
        self._refresh_event_bar()
        self.notify("Done", timeout=2)

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

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

        self.push_screen(AlignModal(), on_result)

    @work(thread=True)
    def _run_align_tool(
        self,
        iccs: ICCS,
        algorithm: str,
        autoflip: bool,
        autoselect: bool,
        all_seis: bool,
    ) -> None:
        """Run ICCS or MCCC in a background thread."""
        try:
            with Session(engine) as session:
                if algorithm == "iccs":
                    run_iccs(session, iccs, autoflip, autoselect)
                elif algorithm == "mccc":
                    active_event = get_active_event(session)
                    run_mccc(session, active_event, iccs, all_seis)
        except Exception as exc:
            self.call_from_thread(self.notify, str(exc), severity="error")
            return
        self.call_from_thread(self._post_align_complete)

    def _post_align_complete(self) -> None:
        # Acknowledge our own writes (t1/flip/select written back by ICCS/MCCC)
        # so the staleness check doesn't recreate an ICCS we just ran.
        if self._bound_iccs is not None:
            self._bound_iccs.created_at = Timestamp.now("UTC")
        self.refresh_all()
        self.notify("Alignment complete", timeout=3)

    def action_new_snapshot(self) -> None:
        def on_comment(comment: str | None) -> None:
            if comment is None:
                return
            try:
                with Session(engine) as session:
                    active_event = get_active_event(session)
                    create_snapshot(session, active_event, comment or None)
                self._refresh_snapshots()
                self.notify("Snapshot created", timeout=2)
            except Exception as exc:
                self.notify(str(exc), severity="error")

        self.push_screen(SnapshotCommentModal(), on_comment)

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

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

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

    def action_refresh(self) -> None:
        self.refresh_all()
        self.notify("Refreshed", timeout=1)

main

main() -> None

Entry point for the AIMBAT TUI.

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

modals

Modal screens for the AIMBAT TUI.

Classes:

Name Description
ActionMenuModal

Generic context-action menu for a selected table row.

AlignModal

Menu for running ICCS or MCCC alignment.

ConfirmModal

Generic yes/no confirmation dialog.

EventSwitcherModal

Modal screen for selecting and activating a seismic event.

InteractiveToolsModal

Menu for launching interactive matplotlib pick tools.

ParameterInputModal

Modal for entering a new numeric/timedelta parameter value.

SnapshotCommentModal

Prompt for an optional snapshot comment.

SnapshotDetailsModal

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

ActionMenuModal

Bases: ModalScreen[str | None]

Generic context-action menu for a selected table row.

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

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:
        super().__init__()
        self._title = title
        self._actions = actions  # [(action_key, display_label), ...]

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

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

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

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

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

AlignModal

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

Menu for running ICCS or MCCC alignment.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

ConfirmModal

Bases: ModalScreen[bool | None]

Generic yes/no confirmation dialog.

Dismisses True on confirm, False on cancel.

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:
        super().__init__()
        self._message = message

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

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

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

EventSwitcherModal

Bases: ModalScreen[UUID | None]

Modal screen for selecting and activating a seismic event.

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

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

    def __init__(self) -> None:
        super().__init__()
        self._selected_event_id: str | None = None

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

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

    def on_mount(self) -> None:
        table = self.query_one(DataTable)
        table.cursor_type = "row"
        table.add_columns(
            "",
            "",
            "ID",
            "Time (UTC)",
            "Lat °",
            "Lon °",
            "Depth km",
            "Seismograms",
            "Stations",
        )
        self._populate(table)

    def _populate(self, table: DataTable) -> None:
        try:
            with Session(engine) as session:
                events = session.exec(select(AimbatEvent)).all()
                active_id: uuid.UUID | None = None
                try:
                    active_id = get_active_event(session).id
                except NoResultFound:
                    pass

                for event in events:
                    active_marker = "●" if event.id == active_id else " "
                    done_marker = "✓" if event.parameters.completed else " "
                    short_id = str(event.id)[:8]
                    time_str = str(event.time)[:19] if event.time else "—"
                    lat = f"{event.latitude:.3f}" if event.latitude is not None else "—"
                    lon = (
                        f"{event.longitude:.3f}" if event.longitude is not None else "—"
                    )
                    depth = (
                        f"{event.depth / 1000:.1f}" if event.depth is not None else "—"
                    )
                    table.add_row(
                        active_marker,
                        done_marker,
                        short_id,
                        time_str,
                        lat,
                        lon,
                        depth,
                        str(event.seismogram_count),
                        str(event.station_count),
                        key=str(event.id),
                    )
        except RuntimeError as exc:
            self.notify(str(exc), severity="error")
            self.dismiss(None)

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

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

    @on(DataTable.RowSelected, "#event-table")
    def row_selected(self, event: DataTable.RowSelected) -> None:
        row_key = event.row_key.value
        if not row_key:
            return
        try:
            event_uuid = uuid.UUID(row_key)
            with Session(engine) as session:
                set_active_event_by_id(session, event_uuid)
                session.commit()
            self.dismiss(event_uuid)
        except Exception as exc:
            self.notify(str(exc), severity="error")

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

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

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

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

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

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

InteractiveToolsModal

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

Menu for launching interactive matplotlib pick tools.

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

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

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

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

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

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

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

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

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

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

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

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

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

ParameterInputModal

Bases: ModalScreen[str | None]

Modal for entering a new numeric/timedelta parameter 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:
        super().__init__()
        self._param_name = param_name
        self._current = current
        self._unit = unit

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

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

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

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

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

SnapshotCommentModal

Bases: ModalScreen[str | None]

Prompt for an optional snapshot comment.

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

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

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

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

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

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

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

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

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

SnapshotDetailsModal

Bases: ModalScreen[None]

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

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:
        super().__init__()
        self._title = title
        self._rows = rows  # [(label, value), ...]

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

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

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