diff --git a/src/toad/client/message_files.py b/src/toad/client/message_files.py index 1c2c72ab2..974878ae7 100644 --- a/src/toad/client/message_files.py +++ b/src/toad/client/message_files.py @@ -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.""" @@ -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, () diff --git a/src/toad/motion.py b/src/toad/motion.py index 4f483a333..c29e69f85 100644 --- a/src/toad/motion.py +++ b/src/toad/motion.py @@ -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: diff --git a/src/toad/qt/composer.py b/src/toad/qt/composer.py index 8b37fcb3c..00eb11fe2 100644 --- a/src/toad/qt/composer.py +++ b/src/toad/qt/composer.py @@ -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 @@ -26,6 +27,9 @@ QListWidgetItem, QPlainTextEdit, QPushButton, + QScrollArea, + QScroller, + QSizePolicy, QVBoxLayout, QWidget, ) @@ -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, @@ -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 @@ -863,7 +867,7 @@ 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) @@ -871,9 +875,22 @@ def __init__(self, composer: QtMessageComposer, position: int) -> None: 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)) @@ -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) @@ -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: diff --git a/src/toad/qt/file_pickers.py b/src/toad/qt/file_pickers.py index baf6eeb27..8c220d38e 100644 --- a/src/toad/qt/file_pickers.py +++ b/src/toad/qt/file_pickers.py @@ -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: diff --git a/src/toad/qt/name_wave.py b/src/toad/qt/name_wave.py index c685662fb..006ae160b 100644 --- a/src/toad/qt/name_wave.py +++ b/src/toad/qt/name_wave.py @@ -428,12 +428,12 @@ class QtSessionTabBar(QtWaveBandCache, TearOffTabBar): on the shared `AnimationClock` and busy tabs waving in the theme accent.""" padding_cells = 1 - TAB_GAP = 4 + TAB_GAP = 3 """Inter-tab right margin (px); read by both the tab stylesheet and `_make_close_button` so the close button sits cleanly inside the painted tab without dead padding.""" - TAB_PAD_LEFT = 6 - TAB_PAD_RIGHT = 2 - TAB_TEXT_CLOSE_GAP = 2 + TAB_PAD_LEFT = 5 + TAB_PAD_RIGHT = 1 + TAB_TEXT_CLOSE_GAP = 1 MAX_TITLE_CHARS = 16 MIN_VISIBLE_TABS = 3 @@ -476,14 +476,18 @@ def _strip_viewport_width(self) -> int: return parent.width() return 0 - def _close_slot_metrics(self) -> tuple[int, int]: - """(button_px, slot_width_px) for the right-side close button container.""" - size = max(24, self.fontMetrics().height() + 2) - return size, size + self.TAB_GAP + def _close_slot_metrics(self) -> tuple[int, int, int]: + """(button_width_px, button_height_px, slot_width_px) for the right-side close button. + Height stays thumb-friendly while width stays tight around `×` so tabs have no dead + trailing gap between the title and close glyph.""" + fm = self.fontMetrics() + height = max(24, fm.height() + 2) + width = max(18, ceil(fm.horizontalAdvance("×")) + 10) + return width, height, width + self.TAB_GAP def _tab_chrome_width(self) -> int: """Horizontal non-text pixels per tab: left pad + text/close gap + close slot + right pad.""" - _size, slot_w = self._close_slot_metrics() + _btn_w, _btn_h, slot_w = self._close_slot_metrics() return self.TAB_PAD_LEFT + self.TAB_TEXT_CLOSE_GAP + slot_w + self.TAB_PAD_RIGHT def _max_tab_width(self) -> int: @@ -542,7 +546,7 @@ def _make_close_button(self, mode: str) -> QWidget: container.setObjectName("tab-close-slot") container.setStyleSheet("QWidget#tab-close-slot { background: transparent; }") layout = QHBoxLayout(container) - size, slot_w = self._close_slot_metrics() + btn_w, btn_h, slot_w = self._close_slot_metrics() layout.setContentsMargins(0, 0, self.TAB_GAP, 0) layout.setSpacing(0) button = QtTextButton(container) @@ -551,10 +555,10 @@ def _make_close_button(self, mode: str) -> QWidget: button.setToolTip("Close tab") button.setAutoRaise(True) button.setFocusPolicy(Qt.FocusPolicy.NoFocus) - button.setFixedSize(size, size) + button.setFixedSize(btn_w, btn_h) button.clicked.connect(lambda _checked=False, target=mode: self._request_close(target)) layout.addWidget(button) - container.setFixedSize(slot_w, size) + container.setFixedSize(slot_w, btn_h) return container def _request_close(self, mode: str) -> None: @@ -574,12 +578,10 @@ def _grown(self, index: int, hint: QSize) -> QSize: def _compact_tab_size(self, index: int, base: QSize) -> QSize: text = self.tabText(index) - bold_font = QFont(self.font()) - bold_font.setBold(True) - text_w = ceil(QFontMetrics(bold_font).horizontalAdvance(text)) - btn_size, _slot_w = self._close_slot_metrics() + text_w = ceil(self.title_line(text, bold=True).lineAt(0).naturalTextWidth()) + _btn_w, btn_h, _slot_w = self._close_slot_metrics() width = min(self._max_tab_width(), self._tab_chrome_width() + max(8, text_w)) - height = max(btn_size + 6, base.height()) + height = max(btn_h + 6, base.height()) return QSize(width, height) def tabSizeHint(self, index: int) -> QSize: # type: ignore[override] @@ -614,12 +616,16 @@ def _cached_title(self, index: int) -> tuple[QRect, str]: cached = self._shown_titles.get(key) if cached is not None: return cached - _size, slot_w = self._close_slot_metrics() + _btn_w, _btn_h, slot_w = self._close_slot_metrics() close_slot = self.tabButton(index, QTabBar.ButtonPosition.RightSide) - if close_slot is not None and close_slot.width() > 0: - slot_w = close_slot.width() left = tab_rect.left() + self.TAB_PAD_LEFT - right = max(left, tab_rect.right() - slot_w - self.TAB_PAD_RIGHT - self.TAB_TEXT_CLOSE_GAP) + if (close_slot is not None and close_slot.width() > 0 + and tab_rect.left() < close_slot.geometry().left() <= tab_rect.right()): + right = max(left, close_slot.geometry().left() - self.TAB_TEXT_CLOSE_GAP) + else: + if close_slot is not None and close_slot.width() > 0: + slot_w = close_slot.width() + right = max(left, tab_rect.right() - slot_w - self.TAB_PAD_RIGHT - self.TAB_TEXT_CLOSE_GAP) rect = QRect(left, tab_rect.top(), max(0, right - left + 1), tab_rect.height()) self._shown_titles[key] = (rect, text) return rect, text @@ -778,7 +784,7 @@ def paintEvent(self, event) -> None: # type: ignore[override] if second_x < rect.right(): drawn.draw(painter, QPointF(second_x, top)) else: - drawn.draw(painter, QPointF(rect.left() + max(0.0, (rect.width() - full_w) / 2), top)) + drawn.draw(painter, QPointF(rect.left(), top)) painter.restore() if any_overflow and self.marquee.animation is None: self.marquee.follow_overflow(True) diff --git a/src/toad/qt/window.py b/src/toad/qt/window.py index cded40e65..0e134116c 100644 --- a/src/toad/qt/window.py +++ b/src/toad/qt/window.py @@ -2169,7 +2169,7 @@ def paint_chrome_colours(self) -> None: toggle_bg = renderer.theme(SidebarToggleToneColour) toggle_style = ( f"QWidget#SidebarToggle, QWidget#SidebarToggle > QWidget {{" - f" background-color: {toggle_bg}; border: none; padding: 2px 4px; }}" + f" background-color: {toggle_bg}; border: none; padding: 0px 2px; }}" ) for side in self.chrome.sidebars: side.setStyleSheet( @@ -2189,7 +2189,7 @@ def paint_chrome_colours(self) -> None: self.tabs.setStyleSheet( f"QTabBar {{ background-color: {bar_bg}; color: {active_ink}; }}" f"QTabBar::tab {{ background-color: {inactive_bg}; color: {inactive_ink}; border: none;" - f" padding: 4px 2px 4px 6px; margin-right: {self.tabs.TAB_GAP}px;" + f" padding: 4px 1px 4px 5px; margin-right: {self.tabs.TAB_GAP}px;" " border-top-left-radius: 4px; border-top-right-radius: 4px; }" f"QTabBar::tab:hover {{ background-color: {hover_bg}; color: {active_ink}; }}" f"QTabBar::tab:selected {{ background-color: {selected_bg}; color: {active_ink};" @@ -2204,7 +2204,7 @@ def paint_chrome_colours(self) -> None: sep_hex = self.palette().color(QPalette.ColorRole.Mid).name() self.navigation.setStyleSheet( scheme.styles.generate_frame_style() - + f"QFrame {{ background-color: {bar_bg}; padding: 2px 4px; }}" + + f"QFrame {{ background-color: {bar_bg}; padding: 2px 2px; }}" + f"QFrame#toad-nav-separator {{ border: none; padding: 0px; margin: 4px 0px; background: {sep_hex}; }}" ) self.float_layer.follow_scheme(scheme) diff --git a/tests/model/test_android_perf_ux_arrivals.py b/tests/model/test_android_perf_ux_arrivals.py index 976b3c0c4..f52c21927 100644 --- a/tests/model/test_android_perf_ux_arrivals.py +++ b/tests/model/test_android_perf_ux_arrivals.py @@ -285,9 +285,11 @@ def test_qt_session_tab_bar_close_button_sits_inside_painted_tab(monkeypatch): assert slot is not None btn = slot.findChild(QToolButton) assert btn is not None and btn.text() == "×" - assert btn.width() >= 24 and btn.height() >= 24 + assert btn.width() >= 18 and btn.height() >= 24 btn_in_bar = btn.geometry().translated(slot.pos()) assert btn_in_bar.right() <= tab_rect.right() - bar.TAB_GAP + text_rect, _title = bar._cached_title(index) + assert slot.geometry().left() - text_rect.right() <= bar.TAB_TEXT_CLOSE_GAP + 1 bar.tabButton(1, QTabBar.ButtonPosition.RightSide).findChild(QToolButton).click() assert closed == [1] finally: @@ -3234,3 +3236,132 @@ async def _coro(): assert row.header is first unpickled = pickle.loads(pickle.dumps(row)) assert unpickled.header == first + + +def test_android_multifile_chooser_image_compression_and_tight_tab_marquee(monkeypatch, tmp_path) -> None: + """AttachChooser offers Android 13+ multi-select Photo Picker and clears getData() when + ClipData holds multiple URIs; Qt image compression shrinks oversized/attached images; and + QtSessionTabBar eliminates dead trailing padding between title and close button.""" + monkeypatch.setenv("QT_QPA_PLATFORM", "offscreen") + app = QApplication.instance() or QApplication([]) + from PySide6.QtCore import QBuffer, QIODevice, QUrl + from PySide6.QtGui import QColor, QImage + from agent_comms.messaging.message_files import FileUpload + from toad.client.message_files import ImageCompressionControl, MessagePromptComposer + from toad.motion import TAB_MARQUEE + from toad.qt.file_pickers import compress_image_bytes, read_picked + + # 1. AttachChooser wires ACTION_PICK_IMAGES + EXTRA_PICK_IMAGES_MAX + ClipData normalization. + chooser = (Path(__file__).resolve().parents[2] + / "tools/android/keepalive/java/org/toadcomms/AttachChooser.java").read_text() + assert "MediaStore.ACTION_PICK_IMAGES" in chooser + assert "MediaStore.EXTRA_PICK_IMAGES_MAX" in chooser + assert "data.setData(null)" in chooser + assert "clip.getItemCount() > 1" in chooser + + # 2. compress_image_bytes downscales and JPEG-compresses a large photo PNG to a much smaller upload. + import random + w, h = 2200, 300 + raw = random.Random(42).randbytes(w * h * 3) + img = QImage(raw, w, h, w * 3, QImage.Format.Format_RGB888) + buf = QBuffer() + assert buf.open(QIODevice.OpenModeFlag.WriteOnly) + assert img.save(buf, "PNG") + png_bytes = bytes(buf.data().data()) + buf.close() + + compressed = compress_image_bytes("photo.png", "image/png", png_bytes) + assert compressed is not None + new_name, new_mime, jpg_bytes = compressed + assert new_name == "photo.jpg" + assert new_mime == "image/jpeg" + assert len(jpg_bytes) < len(png_bytes) + decoded = QImage.fromData(jpg_bytes) + assert not decoded.isNull() + assert max(decoded.width(), decoded.height()) <= 2048 + + # 3. MessagePromptComposer.compress_attached_images shrinks attached images and reports summary. + class FakeComposer(MessagePromptComposer): + def __init__(self) -> None: + self.attached_files = () + self.takes_files = True + self.shown = 0 + self.summaries: list[str] = [] + self.failures: list[str] = [] + + def show_files_offered(self) -> None: + pass + + def pick_in_window(self) -> None: + pass + + def pick_by_path_search(self) -> None: + pass + + def show_attached(self) -> None: + self.shown += 1 + + def show_failure(self, text: str) -> None: + self.failures.append(text) + + def show_compression_summary(self, text: str) -> None: + self.summaries.append(text) + + @property + def settings(self): + return SimpleNamespace() + + def append_to_draft(self, suffix: str) -> None: + pass + + def sync_queue(self) -> None: + pass + + def compress_image(self, upload: FileUpload) -> FileUpload | None: + out = compress_image_bytes(upload.name, upload.mime_type, upload.content) + return None if out is None else FileUpload.of(out[0], out[1], out[2]) + + comp = FakeComposer() + comp.file_picked("photo.png", png_bytes, "image/png") + comp.file_picked("notes.txt", b"hello", "text/plain") + assert comp.has_compressible_images is True + assert comp.compressible_image_count == 1 + ctrl = ImageCompressionControl() + ctrl.bind_compression(comp) + assert ctrl.compress_caption == "Compress image" + ctrl.compress_images() + assert comp.attached_files[0].name == "photo.jpg" + assert comp.attached_files[0].mime_type == "image/jpeg" + assert comp.attached_files[0].size < len(png_bytes) + assert comp.attached_files[1].name == "notes.txt" + assert any("Compressed 1 image:" in s for s in comp.summaries) + + # 4. read_picked auto-compresses an oversized PNG when it exceeds composer.read_limit. + big_png = tmp_path / "huge.png" + big_png.write_bytes(png_bytes) + + class TightLimitComposer(FakeComposer): + @property + def read_limit(self) -> int: + return len(jpg_bytes) + 4096 + + tight = TightLimitComposer() + assert len(png_bytes) > tight.read_limit + read_picked(QUrl.fromLocalFile(str(big_png)), tight) + assert tight.failures == [] + assert len(tight.attached_files) == 1 + assert tight.attached_files[0].name == "huge.jpg" + assert tight.attached_files[0].size < tight.read_limit + + # 5. Tight marquee gap and compact close-button width. + assert TAB_MARQUEE.gap == 14.0 + clock = AnimationClock(lambda _interval: None) + bar = QtSessionTabBar(clock, QColor("#ff00ff"), QColor("#ffffff")) + try: + btn_w, btn_h, slot_w = bar._close_slot_metrics() + assert btn_h >= 24 + assert btn_w <= btn_h + assert slot_w == btn_w + bar.TAB_GAP + finally: + bar.deleteLater() + app.processEvents() diff --git a/tools/android/keepalive/java/org/toadcomms/AttachChooser.java b/tools/android/keepalive/java/org/toadcomms/AttachChooser.java index 6e333c1c5..905d3cd89 100644 --- a/tools/android/keepalive/java/org/toadcomms/AttachChooser.java +++ b/tools/android/keepalive/java/org/toadcomms/AttachChooser.java @@ -11,6 +11,8 @@ import android.provider.MediaStore; import android.util.Log; import android.util.SparseArray; +import java.util.ArrayList; +import java.util.List; /** * What a composer's Attach opens on the phone: Android's own chooser - the apps that give a @@ -47,40 +49,65 @@ Intent offered(Intent intent, int requestCode) { if (intent.hasExtra(Intent.EXTRA_MIME_TYPES)) { content.putExtra(Intent.EXTRA_MIME_TYPES, intent.getStringArrayExtra(Intent.EXTRA_MIME_TYPES)); } - content.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, intent.getBooleanExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)); + boolean allowMultiple = intent.getBooleanExtra(Intent.EXTRA_ALLOW_MULTIPLE, false); + content.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, allowMultiple); Intent chooser = Intent.createChooser(content, "Attach"); + List initial = new ArrayList<>(); + if (allowMultiple && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + // Android 13+'s Photo Picker opens directly in checkbox multi-select mode, + // unlike ACTION_GET_CONTENT providers that default to single-tap selection. + Intent photoPicker = new Intent(MediaStore.ACTION_PICK_IMAGES) + .putExtra(MediaStore.EXTRA_PICK_IMAGES_MAX, MediaStore.getPickImagesMaxLimit()); + initial.add(photoPicker); + } Uri photo = newPhoto(); if (photo != null) { Intent capture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE) .putExtra(MediaStore.EXTRA_OUTPUT, photo) .addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION); capture.setClipData(ClipData.newRawUri("", photo)); - chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {capture}); + initial.add(capture); photos.put(requestCode, photo); } + if (!initial.isEmpty()) { + chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, initial.toArray(new Intent[0])); + } return chooser; } - /** The answer Qt's dialog reads for an offered request: the camera's photo when it was the camera. */ + /** The answer Qt's dialog reads for an offered request: the camera's photo when it was the camera, + * and ClipData-only when multiple files were picked so Qt reads every URI instead of stopping at getData(). */ Intent answered(int requestCode, int resultCode, Intent data) { Uri photo = photos.get(requestCode); - if (photo == null) { - return data; + if (photo != null) { + photos.remove(requestCode); + ContentResolver resolver = activity.getContentResolver(); + boolean picked = data != null && (data.getData() != null || data.getClipData() != null); + try { + if (resultCode == Activity.RESULT_OK && !picked) { + // The camera wrote the photo and answers with no URI of its own. + ContentValues taken = new ContentValues(); + taken.put(MediaStore.MediaColumns.IS_PENDING, 0); + resolver.update(photo, taken, null, null); + return new Intent().setData(photo).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + } + resolver.delete(photo, null, null); + } catch (RuntimeException failure) { + Log.e(TAG, "could not settle the camera's photo " + photo, failure); + } } - photos.remove(requestCode); - ContentResolver resolver = activity.getContentResolver(); - boolean picked = data != null && (data.getData() != null || data.getClipData() != null); - try { - if (resultCode == Activity.RESULT_OK && !picked) { - // The camera wrote the photo and answers with no URI of its own. - ContentValues taken = new ContentValues(); - taken.put(MediaStore.MediaColumns.IS_PENDING, 0); - resolver.update(photo, taken, null, null); - return new Intent().setData(photo).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + return normalizeMultiSelect(resultCode, data); + } + + /** Qt 6's QAndroidPlatformFileDialogHelper checks intent.getData() before intent.getClipData() + * and returns only that first URI whenever a picker populates both. Clearing data keeps + * ClipData and its granted read permissions intact so Qt iterates all selected URIs. */ + private static Intent normalizeMultiSelect(int resultCode, Intent data) { + if (resultCode == Activity.RESULT_OK && data != null) { + ClipData clip = data.getClipData(); + if (clip != null && clip.getItemCount() > 1 && data.getData() != null) { + data.setData(null); } - resolver.delete(photo, null, null); - } catch (RuntimeException failure) { - Log.e(TAG, "could not settle the camera's photo " + photo, failure); } return data; }