Files
pipelines/app/lib/features/chat/domain/chat_clipboard_paste_native.dart
T
alan 4fe16375d9 macOS paste: read more image and file kinds, never fail silently
The pasteboard reader now also takes any image AppKit can read (JPEG,
HEIC, PDF and others, converted to PNG) and the legacy Finder filenames
list. A paste with no files, no image and no text now shows which types
the clipboard held instead of doing nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 22:38:09 +00:00

125 lines
4.2 KiB
Dart

import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'chat_attachment_picker.dart';
import 'chat_clipboard_paste.dart';
/// The macOS Runner's pasteboard reader (macos/Runner/MainFlutterWindow.swift).
const MethodChannel chatClipboardFilesChannel = MethodChannel(
'pipelines/clipboard_files',
);
/// Clipboard-file paste for a desktop host whose Runner answers
/// [chatClipboardFilesChannel].
///
/// Flutter's own [Clipboard] carries text only, so a native host reads the
/// pasteboard through the Runner. Each subscription watches for the platform
/// paste shortcut (Cmd+V). When its composer may take the paste it consumes
/// the key, asks the Runner for the pasteboard's files (Finder file URLs, else
/// a copied or screenshot image) and hands them over; a pasteboard without
/// files pastes its text into the composer instead, so the consumed key never
/// loses a text paste.
ChatClipboardPaste nativeChatClipboardPaste({
MethodChannel channel = chatClipboardFilesChannel,
}) => ChatClipboardPaste(
subscribe: (onFiles, canAccept, onError, onText, canAcceptText) {
var sequence = 0;
KeyEventResult handle(KeyEvent event) {
if (event is! KeyDownEvent ||
event.logicalKey != LogicalKeyboardKey.keyV ||
!chatIsNativePasteShortcut() ||
!canAccept()) {
return KeyEventResult.ignored;
}
unawaited(
_readPasteboard(channel, onFiles, onError, onText, () => ++sequence),
);
return KeyEventResult.handled;
}
FocusManager.instance.addEarlyKeyEventHandler(handle);
return () => FocusManager.instance.removeEarlyKeyEventHandler(handle);
},
);
/// Whether the held modifiers make V the host's paste shortcut: Cmd alone on
/// macOS.
bool chatIsNativePasteShortcut() {
final keys = HardwareKeyboard.instance;
return keys.isMetaPressed &&
!keys.isControlPressed &&
!keys.isAltPressed &&
!keys.isShiftPressed;
}
Future<void> _readPasteboard(
MethodChannel channel,
ChatPasteFiles onFiles,
ChatPasteFailed onError,
ChatPasteText onText,
int Function() nextSequence,
) async {
Map<Object?, Object?>? reply;
try {
reply = await channel.invokeMapMethod<Object?, Object?>('read');
} catch (error) {
onError('Could not read pasted files: $error');
}
final files = <ChatPickedFile>[];
for (final raw in (reply?['files'] as List<Object?>?) ?? const []) {
if (raw is! Map) continue;
final mime = (raw['mime'] as String?) ?? '';
final recorded = ((raw['name'] as String?) ?? '').trim();
final bytes = raw['bytes'];
files.add(
ChatPickedFile(
name: recorded.isEmpty
? chatPastedAttachmentName(mime, nextSequence())
: recorded,
mime: mime,
bytes: bytes is Uint8List ? bytes : Uint8List(0),
),
);
}
final failures = [
for (final failure in (reply?['errors'] as List<Object?>?) ?? const [])
'$failure',
];
if (files.isNotEmpty) {
// As on web: kept files first, since adding clears an older error.
onFiles(files);
failures.forEach(onError);
return;
}
failures.forEach(onError);
if (failures.isNotEmpty) return;
try {
final text = (await Clipboard.getData(Clipboard.kTextPlain))?.text;
if (text != null && text.isNotEmpty) {
onText(text);
return;
}
} catch (_) {
onError('Could not read clipboard text.');
return;
}
// Neither files, an image nor text: say what the clipboard held rather
// than letting the paste do nothing.
final types = [
for (final type in (reply?['types'] as List<Object?>?) ?? const []) '$type',
];
if (reply != null) onError(chatNothingToPasteMessage(types));
}
/// The error for a paste whose clipboard held nothing the composer can take.
String chatNothingToPasteMessage(List<String> types) => types.isEmpty
? 'Nothing to paste: the clipboard is empty.'
: 'Nothing to paste: the clipboard holds ${types.take(6).join(', ')}.';
/// Whether [platform] has a Runner that answers [chatClipboardFilesChannel].
bool chatHostReadsClipboardFiles(TargetPlatform platform) =>
!kIsWeb && platform == TargetPlatform.macOS;