"""Modal dialog that lets the user pick one format from a table. Used both for the audio-only selection and the video (or combined audio+video) selection, since the table layout is identical: format_id, resolution, acodec, vcodec, format. """ from __future__ import annotations from textual.app import ComposeResult from textual.containers import Container, Horizontal from textual.screen import ModalScreen from textual.widgets import Button, DataTable, Label from i18n import I18n from ..models import FormatEntry class FormatSelectScreen(ModalScreen[FormatEntry | None]): """Shows ``entries`` in a table and returns the row the user picked. Returns ``None`` (via Cancel, Escape, or an empty table) so the caller can treat that as "no valid entry selected". """ # Styling for this screen lives in the app's shared external stylesheet # (app/styles.tcss), loaded via DownloadManagerApp.CSS_PATH. BINDINGS = [("escape", "cancel", "Cancel")] def __init__(self, title: str, entries: list[FormatEntry]) -> None: super().__init__() self._title = title self._entries = entries def compose(self) -> ComposeResult: i18n = I18n() with Container(): yield Label(self._title, id="dialog-title") table: DataTable[str] = DataTable(id="format-table", cursor_type="row") table.add_columns( i18n.t("table.format_id", default="Format ID"), i18n.t("table.resolution", default="Resolution"), i18n.t("table.acodec", default="Audio codec"), i18n.t("table.vcodec", default="Video codec"), i18n.t("table.format", default="Format"), ) for entry in self._entries: table.add_row( entry.format_id, entry.resolution, entry.acodec, entry.vcodec, entry.format, key=entry.format_id, ) yield table with Horizontal(): yield Button( i18n.t("button.ok", default="OK"), id="select-ok", variant="primary", disabled=not self._entries, ) yield Button(i18n.t("button.cancel", default="Cancel"), id="select-cancel") def on_mount(self) -> None: if self._entries: self.query_one(DataTable).focus() def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None: self._confirm(event.row_key.value) def on_button_pressed(self, event: Button.Pressed) -> None: if event.button.id == "select-ok": table = self.query_one(DataTable) if table.row_count == 0 or table.cursor_row is None: self.dismiss(None) return row_key, _ = table.coordinate_to_cell_key(table.cursor_coordinate) self._confirm(row_key.value) else: self.dismiss(None) def action_cancel(self) -> None: self.dismiss(None) def _confirm(self, format_id: str | None) -> None: for entry in self._entries: if entry.format_id == format_id: self.dismiss(entry) return self.dismiss(None)