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
59 changes: 59 additions & 0 deletions src/toad/client/message_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,23 @@ def take_off(self) -> None:
self.composer.detach_file(self.position)


class ImageCompressionControl:
"""Shared caption and action for compressing attached images on a composer."""

composer: MessagePromptComposer

def bind_compression(self, composer: MessagePromptComposer) -> None:
self.composer = composer

@property
def compress_caption(self) -> str:
count = self.composer.compressible_image_count
return "Compress image" if count == 1 else f"Compress {count} images"

def compress_images(self) -> None:
self.composer.compress_attached_images()


class MessagePromptComposer(PromptComposer):
"""A message composer: always the agent glyph, every input accepted, and the files it
sends with the text."""
Expand Down Expand Up @@ -185,6 +202,48 @@ def detach_file(self, position: int) -> None:
self.attached_files = files[:position] + files[position + 1:]
self.show_attached()

def compress_image(self, upload: FileUpload) -> FileUpload | None:
"""Re-encode an attached image to a smaller upload, or return None if unavailable/larger."""
return None

def show_compression_summary(self, text: str) -> None:
"""Report the outcome of compressing attached images; frontends override to float a notice."""

@property
def compressible_image_count(self) -> int:
return sum(1 for upload in self.attached_files if upload.mime_type.startswith("image/"))

@property
def has_compressible_images(self) -> bool:
return self.compressible_image_count > 0

def compress_attached_images(self) -> tuple[int, int, int]:
"""Compress every attached image that shrinks; returns (count, bytes_before, bytes_after)."""
updated: list[FileUpload] = []
compressed_count = 0
bytes_before = 0
bytes_after = 0
for upload in self.attached_files:
if upload.mime_type.startswith("image/"):
smaller = self.compress_image(upload)
if smaller is not None and smaller.size < upload.size:
updated.append(smaller)
compressed_count += 1
bytes_before += upload.size
bytes_after += smaller.size
continue
updated.append(upload)
if compressed_count:
self.attached_files = tuple(updated)
self.show_attached()
noun = "image" if compressed_count == 1 else "images"
self.show_compression_summary(
f"Compressed {compressed_count} {noun}: {file_size(bytes_before)} -> {file_size(bytes_after)}"
)
else:
self.show_compression_summary("Attached images are already compact")
return compressed_count, bytes_before, bytes_after

def take_files(self) -> tuple[FileUpload, ...]:
"""The files the message being sent carries; the composer holds none after."""
files, self.attached_files = self.attached_files, ()
Expand Down
2 changes: 1 addition & 1 deletion src/toad/motion.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def offset(self, elapsed: float, content_width: float, viewport_width: float) ->


# 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)
TAB_MARQUEE = MarqueeSweep(speed=28.0, pause=1.0, gap=14.0, frames_per_second=30.0)


def animations_enabled() -> bool:
Expand Down
84 changes: 74 additions & 10 deletions src/toad/qt/composer.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import shiboken6

from agent_comms.messaging.mentions import MentionCandidate
from agent_comms.messaging.message_files import FileUpload
from PySide6.QtCore import QEvent, Qt, QTimer, Slot
from PySide6.QtGui import QColor, QFont, QGuiApplication, QKeyEvent, QPalette, QTextCursor
from pyqt_reactive.widgets.shared.list_item_delegate import LAYOUT_ROLE, MultilinePreviewItemDelegate
Expand All @@ -26,6 +27,9 @@
QListWidgetItem,
QPlainTextEdit,
QPushButton,
QScrollArea,
QScroller,
QSizePolicy,
QVBoxLayout,
QWidget,
)
Expand All @@ -37,7 +41,7 @@
from toad.client.composer_pool import ComposerDraft, ComposerPoolHost
from toad.client.line_blocks import FailureRole, LineRole, MutedRole
from toad.client.mention_completion import MentionCompletion, MentionEditor
from toad.client.message_files import AttachedFileChip, MessagePromptComposer
from toad.client.message_files import AttachedFileChip, ImageCompressionControl, MessagePromptComposer
from toad.client.prompt_composer import (
ComposerOffer,
MentionCandidateOffer,
Expand Down Expand Up @@ -67,7 +71,7 @@
SubmitsContract,
)
from toad.qt.composer_vim import ComposerVimMode, apply_normal_key
from toad.qt.file_pickers import open_file_dialog, open_path_search
from toad.qt.file_pickers import compress_image_bytes, open_file_dialog, open_path_search
from toad.qt.lines import QtLineRenderer
from toad.qt.queue_ui import QtDeliveryControls, QtQueueHint, QtQueueInspection, QtQueueSummary, RowReveal
from toad.qt.prompt_stack import QtInfoBar
Expand Down Expand Up @@ -863,17 +867,30 @@ class QtAttachedFileChip(AttachedFileChip, QtPushButton):
"""An attached file as a button over the editor; tapping it takes the file off."""

def __init__(self, composer: QtMessageComposer, position: int) -> None:
super().__init__(composer.attached_row)
super().__init__(composer.attached_chips_host)
self.show_file(composer, position)
self.setText(f"{self.caption} ✕")
self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.setToolTip("Remove this file")
self.clicked.connect(self.take_off)


class QtCompressImagesButton(ImageCompressionControl, QtPushButton):
"""One-tap button over the composer to shrink attached images before sending."""

def __init__(self, composer: QtMessageComposer) -> None:
super().__init__(composer.attached_row)
self.bind_compression(composer)
self.setText(self.compress_caption)
self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.setToolTip("Downscale and JPEG-compress attached images")
self.clicked.connect(self.compress_images)


class QtMessageComposer(MessagePromptComposer, Composer):
"""A bus message's composer on Qt: the shared message composer, an Attach button beside
Send, the attached files as chips over the editor, and Qt's two pickers."""
Send, the attached files as scrollable chips with an image-compression control over the
editor, and Qt's two pickers."""

action_methods = (*Composer.action_methods, (AttachFileAction, MessagePromptComposer.attach_file))

Expand All @@ -886,13 +903,46 @@ def __init__(self, host: ComposerHost, renderer: QtLineRenderer, placeholder: st
self.attach_button.clicked.connect(self.attach_file)
self.add_box_button(self.attach_button)
self.attached_row = QWidget(self)
chips = QHBoxLayout(self.attached_row)
chips.setContentsMargins(UiGap.frame, 0, UiGap.frame, 0)
chips.setAlignment(Qt.AlignmentFlag.AlignLeft)
row_layout = QHBoxLayout(self.attached_row)
row_layout.setContentsMargins(UiGap.frame, 0, UiGap.frame, 0)
row_layout.setSpacing(UiGap.tight)
self.attached_scroll = QScrollArea(self.attached_row)
self.attached_scroll.setFrameShape(QFrame.Shape.NoFrame)
self.attached_scroll.setWidgetResizable(True)
self.attached_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.attached_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.attached_scroll.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self.attached_chips_host = QWidget(self.attached_scroll)
self.attached_chips = QHBoxLayout(self.attached_chips_host)
self.attached_chips.setContentsMargins(0, 0, 0, 0)
self.attached_chips.setSpacing(UiGap.tight)
self.attached_chips.setAlignment(Qt.AlignmentFlag.AlignLeft)
self.attached_scroll.setWidget(self.attached_chips_host)
QScroller.grabGesture(
self.attached_scroll.viewport(),
QScroller.ScrollerGestureType.LeftMouseButtonGesture,
)
self.compress_button: QtCompressImagesButton | None = None
row_layout.addWidget(self.attached_scroll, 1)
layout = self.layout()
layout.insertWidget(layout.indexOf(self.frame_row), self.attached_row)
self.attached_row.hide()

def submit(self) -> None:
"""Allow sending attached files with or without accompanying text."""
if self.text.strip() or self.attached_files:
self.send(SubmitAction())

def compress_image(self, upload: FileUpload) -> FileUpload | None:
compressed = compress_image_bytes(upload.name, upload.mime_type, upload.content)
if compressed is None:
return None
new_name, new_mime, new_bytes = compressed
return FileUpload.of(new_name, new_mime, new_bytes)

def show_compression_summary(self, text: str) -> None:
self.host.app.show_info(text)

def pick_in_window(self) -> None:
open_file_dialog(self, self)

Expand All @@ -903,10 +953,24 @@ def show_files_offered(self) -> None:
self.attach_button.setVisible(self.takes_files)

def show_attached(self) -> None:
chips = self.attached_row.layout()
delete_layout_widgets(chips)
delete_layout_widgets(self.attached_chips)
row_layout = self.attached_row.layout()
if self.compress_button is not None:
row_layout.removeWidget(self.compress_button)
self.compress_button.hide()
self.compress_button.deleteLater()
self.compress_button = None
chip_height = 0
for position in range(len(self.attached_files)):
chips.addWidget(QtAttachedFileChip(self, position))
chip = QtAttachedFileChip(self, position)
chip_height = max(chip_height, chip.sizeHint().height())
self.attached_chips.addWidget(chip)
if self.has_compressible_images:
self.compress_button = QtCompressImagesButton(self)
chip_height = max(chip_height, self.compress_button.sizeHint().height())
row_layout.addWidget(self.compress_button, 0)
if chip_height > 0:
self.attached_scroll.setFixedHeight(chip_height + 2)
self.attached_row.setVisible(bool(self.attached_files))

def capture_composer_draft(self) -> ComposerDraft:
Expand Down
74 changes: 70 additions & 4 deletions src/toad/qt/file_pickers.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,31 +11,97 @@

from __future__ import annotations

import mimetypes
from collections.abc import Callable
from pathlib import Path

from PySide6.QtCore import QFile, QFileInfo, QIODevice, Qt, QUrl
from agent_comms.messaging.message_files import MAX_MESSAGE_FILE_BYTES
from PySide6.QtCore import QBuffer, QByteArray, QFile, QFileInfo, QIODevice, Qt, QUrl
from PySide6.QtGui import QImage
from PySide6.QtWidgets import QDialog, QFileDialog, QLineEdit, QListWidget, QVBoxLayout, QWidget

from toad.client.message_file_links import file_size
from toad.client.message_files import FileSearch, MessagePromptComposer
from toad.client.project_paths import ProjectPathSearch
from toad.prompt_actions import AttachFileAction
from toad.qt.presented_window import PresentedWindow

MAX_COMPRESSIBLE_IMAGE_BYTES = 4 * MAX_MESSAGE_FILE_BYTES
"""Maximum raw image size read when auto-compressing an oversized photo to fit a message."""


def compress_image_bytes(
name: str,
mime_type: str,
content: bytes,
*,
max_dimension: int = 2048,
jpeg_quality: int = 82,
) -> tuple[str, str, bytes] | None:
"""Re-encode an image to a smaller JPEG (downscaling longest side to ``max_dimension``).
Returns ``(new_name, "image/jpeg", encoded)`` only when smaller than ``content``."""
image = QImage.fromData(QByteArray(content))
if image.isNull():
return None
scaled = image.width() > max_dimension or image.height() > max_dimension
if scaled:
image = image.scaled(
max_dimension,
max_dimension,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation,
)
candidates: list[tuple[str, str, bytes]] = []
rgb = image.convertToFormat(QImage.Format.Format_RGB888) if image.hasAlphaChannel() else image
stem = Path(name).stem or "image"
targets = [(".jpg", "JPEG", "image/jpeg", jpeg_quality, rgb)]
if scaled:
targets.append((".png", "PNG", "image/png", -1, image))
for ext, fmt, mime, quality, source in targets:
buf = QBuffer()
if not buf.open(QIODevice.OpenModeFlag.WriteOnly):
continue
try:
if source.save(buf, fmt, quality):
encoded = bytes(buf.data().data())
if encoded:
candidates.append((f"{stem}{ext}", mime, encoded))
finally:
buf.close()
smaller = [item for item in candidates if len(item[2]) < len(content)]
return min(smaller, key=lambda item: len(item[2])) if smaller else None


def read_picked(url: QUrl, composer: MessagePromptComposer) -> None:
"""Read what a picker chose, up to what the composer can still attach, and attach it."""
"""Read what a picker chose, up to what the composer can still attach, and attach it.
An oversized image that would otherwise exceed the message byte cap is compressed first."""
# A local file's path, else the URL itself: QFile opens an Android content:// URL as is.
location = url.toLocalFile() or url.toString()
name = QFileInfo(location).fileName()
guessed_mime = mimetypes.guess_type(name)[0] or ""
picked = QFile(location)
if not picked.open(QIODevice.OpenModeFlag.ReadOnly):
composer.show_failure(f"Could not read {location}: {picked.errorString()}")
return
try:
content = bytes(picked.read(composer.read_limit).data())
limit = composer.read_limit
content = bytes(picked.read(limit).data())
if len(content) >= limit and (guessed_mime.startswith("image/") or not guessed_mime):
# Read the full image (bounded) and compress so large phone photos fit in one tap.
rest = bytes(picked.read(max(0, MAX_COMPRESSIBLE_IMAGE_BYTES - len(content))).data())
full = content + rest
if len(full) <= MAX_COMPRESSIBLE_IMAGE_BYTES:
compressed = compress_image_bytes(name, guessed_mime or "image/jpeg", full)
if compressed is not None and len(compressed[2]) < limit:
new_name, new_mime, new_bytes = compressed
composer.file_picked(new_name, new_bytes, new_mime)
composer.show_compression_summary(
f"Compressed {name}: {file_size(len(full))} -> {file_size(len(new_bytes))}"
)
return
finally:
picked.close()
composer.file_picked(QFileInfo(location).fileName(), content)
composer.file_picked(name, content)


def open_file_dialog(parent: QWidget, composer: MessagePromptComposer) -> QFileDialog:
Expand Down
Loading
Loading