Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/toad/client/name_wave.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@

from ui_theme.effects import NAME_WAVE, Band, Effect

from toad.motion import TAB_MARQUEE, MarqueeSweep


class BandCells:
"""How a `Band` (fractions of a line) covers a line of `width` cells: each edge rounds
Expand Down Expand Up @@ -94,3 +96,34 @@ def follow_activity(self, busy: bool) -> None:
def name_bold(self) -> bool:
"""The whole name is bold while the wave runs."""
return self.wave_running()


class TitleMarquee:
"""Shared banner-scroll state for overflowing tab titles. Runs on the frontend's
`AnimationClock` only while at least one title exceeds its visible rect."""

marquee_effect: ClassVar[MarqueeSweep] = TAB_MARQUEE

def marquee_running(self) -> bool:
raise NotImplementedError

def start_marquee(self) -> None:
raise NotImplementedError

def stop_marquee(self) -> None:
raise NotImplementedError

def marquee_elapsed(self) -> float:
raise NotImplementedError

def follow_overflow(self, overflowing: bool) -> None:
if overflowing:
if not self.marquee_running():
self.start_marquee()
elif self.marquee_running():
self.stop_marquee()

def marquee_offset(self, content_width: float, viewport_width: float) -> float:
if not self.marquee_running():
return 0.0
return self.marquee_effect.offset(self.marquee_elapsed(), content_width, viewport_width)
32 changes: 32 additions & 0 deletions src/toad/motion.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,38 @@ def final(self) -> Mix:
ARRIVAL = Cascade(NEW_TEXT, span=0.4)


@dataclass(frozen=True)
class MarqueeSweep(Effect[Amount]):
"""Continuous banner scroll for an overflowing label: pauses at the start, then scrolls at
`speed` units/s with `gap` units before wrapping back to zero."""

speed: float
pause: float
gap: float
frames_per_second: float = 30.0
duration: float | None = None

def frame(self, elapsed: float) -> Amount:
return Amount(elapsed)

@property
def final(self) -> Amount:
return Amount(0.0)

def offset(self, elapsed: float, content_width: float, viewport_width: float) -> float:
"""Horizontal scroll offset for `content_width` inside `viewport_width` at `elapsed` s."""
if content_width <= viewport_width + 0.5 or viewport_width <= 0 or self.speed <= 0:
return 0.0
distance = content_width + self.gap
period = self.pause + distance / self.speed
t = elapsed % period
return 0.0 if t <= self.pause else (t - self.pause) * self.speed


# Overflowing tab titles banner-scroll on the shared clock after a 1 s readable pause.
TAB_MARQUEE = MarqueeSweep(speed=28.0, pause=1.0, gap=24.0, frames_per_second=30.0)


def animations_enabled() -> bool:
"""Whether this process animates: Textual's own animation level, which the TUI's clock
already follows, so one environment setting turns motion off in both frontends."""
Expand Down
24 changes: 16 additions & 8 deletions src/toad/qt/file_pickers.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,19 +39,19 @@ def read_picked(url: QUrl, composer: MessagePromptComposer) -> None:


def open_file_dialog(parent: QWidget, composer: MessagePromptComposer) -> QFileDialog:
"""Qt's file dialog over ``parent``, attaching the file it returns."""
"""Qt's file dialog over ``parent``, attaching all files it returns."""
dialog = QFileDialog(parent, AttachFileAction.title)
dialog.setFileMode(QFileDialog.FileMode.ExistingFile)
# An accepted dialog holds its one choice: Qt's own dialog emits no urlSelected, and
# Android's document picker answers with a content:// URL, so both are read from here.
dialog.setFileMode(QFileDialog.FileMode.ExistingFiles)
# An accepted dialog holds its chosen URLs: Qt's own dialog emits no urlSelected, and
# Android's document picker returns one or more content:// URLs via ClipData/getData.
dialog.accepted.connect(lambda: [read_picked(url, composer) for url in dialog.selectedUrls()])
dialog.finished.connect(dialog.deleteLater)
dialog.open()
return dialog


class QtPathSearch(PresentedWindow, ProjectPathSearch, QDialog):
"""The project's paths, ranked as you type; choosing one attaches that file."""
"""The project's paths, ranked as you type; choosing one or more attaches those files."""

shown_limit = 100

Expand All @@ -65,6 +65,7 @@ def __init__(self, parent: QWidget, root: Path, chosen: Callable[[Path], None],
self.query = QLineEdit(self)
self.query.setPlaceholderText(f"Search {root}")
self.results = QListWidget(self)
self.results.setSelectionMode(QListWidget.SelectionMode.ExtendedSelection)
layout = QVBoxLayout(self)
layout.addWidget(self.query)
layout.addWidget(self.results, 1)
Expand All @@ -91,12 +92,19 @@ def show_paths(self, spellings: list[str]) -> None:
self.results.setCurrentRow(0)

def choose_current(self) -> None:
if (item := self.results.currentItem()) is not None:
selected = [item.text() for item in self.results.selectedItems()]
if selected:
self.choose_many(selected)
elif (item := self.results.currentItem()) is not None:
self.choose(item.text())

def choose(self, spelling: str) -> None:
def choose_many(self, spellings: list[str]) -> None:
self.accept()
self.chosen(self.root / spelling)
for spelling in spellings:
self.chosen(self.root / spelling)

def choose(self, spelling: str) -> None:
self.choose_many([spelling])


def open_path_search(parent: QWidget, composer: MessagePromptComposer, root: Path, run: Callable) -> QtPathSearch:
Expand Down
81 changes: 62 additions & 19 deletions src/toad/qt/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,8 @@ def __init__(self, renderer: QtLineRenderer, pictures: RowPictures, processes: R
self._colour_cache: tuple[ColourScheme, str, QColor, QColor] | None = None
self._font_metrics_cache: tuple[QFont, float, int] | None = None
self._font_spec_cache: tuple[QFont, str, float] | None = None
self._frame_paint: tuple[QWidget | None, QFont, QPalette, float, QImage.Format, str, QColor, QColor, str, float, int] | None = None
self._backing_format_cache: tuple[int, int, QImage.Format] | None = None
self._frame_paint: tuple[QWidget | None, QFont, float, QImage.Format, str, QColor, QColor, str, float, int] | None = None
self._frame_source_mode = False

@staticmethod
Expand Down Expand Up @@ -233,17 +234,24 @@ def background_qcolor(self) -> QColor:
def foreground_qcolor(self) -> QColor:
return self._theme_colours()[2]

def link(self, links: LinkContext) -> None:
"""Rows draw with these names from now on; rows prepared before are stale."""
def link(self, links: LinkContext) -> bool:
"""Rows draw with these names from now on; rows prepared before are stale.
Returns True when `links` actually changed so a parallel `acquire_links` with
unchanged links never wipes prepared rows and flashes an already-loaded view."""
if links == self.renderer.links:
return False
self.renderer = self.app_renderer.with_links(links)
self.links_revision += 1
# Every row's key names the links it was drawn with: none keeps its height.
self.forget_row_sizes()
return True

def restyle(self) -> None:
"""The app's renderer took a new scheme or diff marks: rows draw by it from now on,
with the names they had; rows prepared before are stale."""
self.link(self.renderer.links)
self.renderer = self.app_renderer.with_links(self.renderer.links)
self.links_revision += 1
self.forget_row_sizes()

def row_key(self, fragment: HistoryFragment):
return fragment.key
Expand Down Expand Up @@ -532,6 +540,7 @@ def release_documents(self) -> None:
suspending the app, a new width)."""
super().release_documents()
self.pictures.clear()
self._backing_format_cache = None

def _paint_tile_document(
self, drawing: QPainter, palette: QPalette, document: QTextDocument,
Expand Down Expand Up @@ -600,17 +609,24 @@ def _paint_plain_row(

def _resolve_frame_paint(
self, painter: QPainter, viewport_width: int = 0,
) -> tuple[QWidget | None, QFont, QPalette, float, QImage.Format, str, QColor, QColor, str, float, int]:
) -> tuple[QWidget | None, QFont, float, QImage.Format, str, QColor, QColor, str, float, int]:
device = self.view.backing_device()
font = device.font() if device is not None else QFont()
palette = device.palette() if device is not None else QPalette()
ratio = painter.device().devicePixelRatioF()
img_format = self._backing_image_format(device, painter)
paint_device = painter.device()
ratio = paint_device.devicePixelRatioF()
cached_fmt = self._backing_format_cache
dev_id = id(paint_device)
wid_id = id(device)
if cached_fmt is not None and cached_fmt[0] == dev_id and cached_fmt[1] == wid_id:
img_format = cached_fmt[2]
else:
img_format = self._backing_image_format(device, painter)
self._backing_format_cache = (dev_id, wid_id, img_format)
bg_hex, bg_color, fg_color = self._theme_colours()
font_family, font_size = self._font_spec(font)
layout_w = self.layout_width(viewport_width) if viewport_width else 0
return (
device, font, palette, ratio, img_format, bg_hex, bg_color, fg_color,
device, font, ratio, img_format, bg_hex, bg_color, fg_color,
font_family, font_size, layout_w,
)

Expand All @@ -634,6 +650,13 @@ def paint_row(
return
arrival = self.view.arrival_state(fragment.key, rect.height()) if self.view.has_active_arrivals else SETTLED_ARRIVAL
paint_rect = rect.translated(0, round(arrival.offset_y)) if arrival.offset_y else rect
# Clip an arriving non-final row to its own layout slot so its downward slide offset
# never draws over the sibling row underneath it while the arrival animation is running.
clip_to_slot = bool(arrival.offset_y and row + 1 < self.view.model_rows.rowCount())
row_clip = (
(QRegion(rect) if clip_region is None else clip_region.intersected(QRegion(rect)))
if clip_to_slot else clip_region
)
highlight = self.view.tap_highlight
if highlight.matches_row(fragment.key):
frame = self._frame_paint
Expand All @@ -642,11 +665,11 @@ def paint_row(
)
document = self.final_document_for(fragment, font, self.layout_width(paint_rect.width()))
if document is not None:
self._paint_document_direct(painter, document, paint_rect, clip_region, arrival, highlight)
self._paint_document_direct(painter, document, paint_rect, row_clip, arrival, highlight)
self.view.row_painted(fragment, paint_rect)
return
if not self.paint_pictures(painter, fragment, paint_rect, clip_region, arrival):
self._paint_plain_row(painter, fragment, paint_rect, clip_region, arrival)
if not self.paint_pictures(painter, fragment, paint_rect, row_clip, arrival, clip_to_shown=clip_to_slot):
self._paint_plain_row(painter, fragment, paint_rect, row_clip, arrival)
self.view.row_painted(fragment, paint_rect)

def paint_pictures(
Expand All @@ -656,16 +679,19 @@ def paint_pictures(
rect: QRect,
clip_region: QRegion | None,
arrival: ViewportArrivalState = SETTLED_ARRIVAL,
*,
clip_to_shown: bool = False,
) -> bool:
"""The tiles of the row that this paint shows, each drawn once into a backing-store-matched
`QImage` and blitted with `CompositionMode_Source` on subsequent frames."""
frame = self._frame_paint
if frame is None:
frame = self._resolve_frame_paint(painter)
(
_device, font, palette, ratio, img_format, bg_hex, bg_color, _fg_color,
device, font, ratio, img_format, bg_hex, bg_color, _fg_color,
font_family, font_size, layout_w,
) = frame
palette: QPalette | None = None
width = layout_w or self.layout_width(rect.width())
cache_key = (((fragment.key, fragment.shown, fragment.revision), self.links_revision, font_family, font_size, width), width)
document = self._documents.get(cache_key)
Expand Down Expand Up @@ -693,12 +719,14 @@ def paint_pictures(
rect_h = rect.height()
look = (rect_w, rect_h, ratio, bg_hex, img_format)
row_id = id(document) if document is not None else (id(self), fragment.key)
needs_state = arrival.active or not self._frame_source_mode
needs_state = arrival.active or clip_to_shown or not self._frame_source_mode
if needs_state:
painter.save()
if clip_to_shown:
painter.setClipRect(shown)
if arrival.active:
painter.setOpacity(arrival.opacity)
else:
elif not self._frame_source_mode:
painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_Source)
plain_doc: QTextDocument | None = None
tile_h = self.TILE
Expand All @@ -723,6 +751,8 @@ def paint_pictures(
tile_key = (row_id, tile_y, tile_x)
picture = pictures_kept(tile_key, look, document)
if picture is None:
if palette is None:
palette = device.palette() if device is not None else QPalette()
picture = QImage(
max(1, round(width * ratio)),
max(1, round(height * ratio)),
Expand Down Expand Up @@ -1318,7 +1348,7 @@ def draw_pinned(self, headers: tuple[Divider, ...], x: int, width: int) -> None:
in `laid_out` and `_pixmap_cache` so scrolling back and forth across message
boundaries avoids re-running `setHtml` / layout / rasterization or no-op geometry calls."""
window = self.history_window
context = (width, window.font().key(), window.rows.links_revision, id(window.rows.renderer))
context = (width, window.rows._font_spec(window.font()), window.rows.links_revision, id(window.rows.renderer))
drawn = (headers, x, context)
if drawn == self.drawn:
return
Expand Down Expand Up @@ -1637,9 +1667,12 @@ def _on_widget_destroyed(self, *_args) -> None:
self.stop_arrival_motion()

async def acquire_links(self, app) -> None:
"""The names this conversation's bodies link through; the rows draw again with them."""
self.rows.link(await LinkContext.observed(app.renderer.links.root, app.coordination_access))
self.show_pages()
"""The names this conversation's bodies link through; redraw rows only if links changed."""
links = await LinkContext.observed(app.renderer.links.root, app.coordination_access)
changed = self.rows.link(links)
app.renderer.links = links
if changed:
self.show_pages()

def action_page_down(self) -> None:
"""Move the reader one page toward the latest message (Textual's `ReaderAction`
Expand Down Expand Up @@ -2183,6 +2216,16 @@ def keep_tail_after_resize(self, was: int, now: int) -> None:
if was != now and self.follows_tail and not self.widget_gone:
self.follow_latest()

def apply_measured_rows(self, updates: list[tuple[int, int, int]]) -> None:
"""Commit background height measurements after flushing pending reader scroll so
`request_reader_layout()` anchors against pre-update geometry."""
if not updates or self.widget_gone:
return
self._flush_reader_scroll()
for row, height, extent in updates:
self._set_row_geometry(row, height, extent, False)
self.rows_changed()

def rows_changed(self) -> None:
"""Prepared rows changed height: lay them out again; the layout keeps the reader's
message. A destroyed window has no reader to serve."""
Expand Down
Loading
Loading