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>
This commit is contained in:
@@ -98,12 +98,27 @@ Future<void> _readPasteboard(
|
|||||||
if (failures.isNotEmpty) return;
|
if (failures.isNotEmpty) return;
|
||||||
try {
|
try {
|
||||||
final text = (await Clipboard.getData(Clipboard.kTextPlain))?.text;
|
final text = (await Clipboard.getData(Clipboard.kTextPlain))?.text;
|
||||||
if (text != null && text.isNotEmpty) onText(text);
|
if (text != null && text.isNotEmpty) {
|
||||||
|
onText(text);
|
||||||
|
return;
|
||||||
|
}
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
onError('Could not read clipboard text.');
|
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].
|
/// Whether [platform] has a Runner that answers [chatClipboardFilesChannel].
|
||||||
bool chatHostReadsClipboardFiles(TargetPlatform platform) =>
|
bool chatHostReadsClipboardFiles(TargetPlatform platform) =>
|
||||||
!kIsWeb && platform == TargetPlatform.macOS;
|
!kIsWeb && platform == TargetPlatform.macOS;
|
||||||
|
|||||||
@@ -40,10 +40,17 @@ enum ClipboardFiles {
|
|||||||
static func read(_ board: NSPasteboard) -> [String: Any] {
|
static func read(_ board: NSPasteboard) -> [String: Any] {
|
||||||
var files: [[String: Any]] = []
|
var files: [[String: Any]] = []
|
||||||
var errors: [String] = []
|
var errors: [String] = []
|
||||||
let urls =
|
var urls =
|
||||||
board.readObjects(
|
(board.readObjects(
|
||||||
forClasses: [NSURL.self],
|
forClasses: [NSURL.self],
|
||||||
options: [.urlReadingFileURLsOnly: true]) as? [URL] ?? []
|
options: [.urlReadingFileURLsOnly: true]) ?? []).compactMap { $0 as? URL }
|
||||||
|
// Older apps put a Finder copy only in the legacy filenames list.
|
||||||
|
if urls.isEmpty,
|
||||||
|
let paths = board.propertyList(
|
||||||
|
forType: NSPasteboard.PasteboardType("NSFilenamesPboardType")) as? [String]
|
||||||
|
{
|
||||||
|
urls = paths.map { URL(fileURLWithPath: $0) }
|
||||||
|
}
|
||||||
for url in urls {
|
for url in urls {
|
||||||
var isDirectory: ObjCBool = false
|
var isDirectory: ObjCBool = false
|
||||||
if FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory),
|
if FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory),
|
||||||
@@ -67,13 +74,23 @@ enum ClipboardFiles {
|
|||||||
if urls.isEmpty, let png = image(board) {
|
if urls.isEmpty, let png = image(board) {
|
||||||
files.append(["name": "", "mime": "image/png", "bytes": FlutterStandardTypedData(bytes: png)])
|
files.append(["name": "", "mime": "image/png", "bytes": FlutterStandardTypedData(bytes: png)])
|
||||||
}
|
}
|
||||||
return ["files": files, "errors": errors]
|
// What the pasteboard held, so an unreadable paste can say so.
|
||||||
|
let types = (board.types ?? []).map { $0.rawValue }
|
||||||
|
return ["files": files, "errors": errors, "types": types]
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The pasteboard's image as PNG: its own PNG, else its TIFF converted.
|
/// The pasteboard's image as PNG: its own PNG, else its TIFF converted,
|
||||||
|
/// else any image AppKit can read from it (JPEG, HEIC, PDF, ...).
|
||||||
private static func image(_ board: NSPasteboard) -> Data? {
|
private static func image(_ board: NSPasteboard) -> Data? {
|
||||||
if let png = board.data(forType: .png) { return png }
|
if let png = board.data(forType: .png) { return png }
|
||||||
guard let tiff = board.data(forType: .tiff),
|
if let tiff = board.data(forType: .tiff),
|
||||||
|
let rep = NSBitmapImageRep(data: tiff),
|
||||||
|
let png = rep.representation(using: .png, properties: [:])
|
||||||
|
{
|
||||||
|
return png
|
||||||
|
}
|
||||||
|
guard let image = NSImage(pasteboard: board),
|
||||||
|
let tiff = image.tiffRepresentation,
|
||||||
let rep = NSBitmapImageRep(data: tiff)
|
let rep = NSBitmapImageRep(data: tiff)
|
||||||
else { return nil }
|
else { return nil }
|
||||||
return rep.representation(using: .png, properties: [:])
|
return rep.representation(using: .png, properties: [:])
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
@@ -19,6 +18,7 @@ void main() {
|
|||||||
late ChatComposerController composer;
|
late ChatComposerController composer;
|
||||||
late Map<String, Object?> pasteboard;
|
late Map<String, Object?> pasteboard;
|
||||||
late int fileReads, textReads;
|
late int fileReads, textReads;
|
||||||
|
String? clipboardText;
|
||||||
|
|
||||||
setUp(() {
|
setUp(() {
|
||||||
gateway = ComposerBarGateway();
|
gateway = ComposerBarGateway();
|
||||||
@@ -30,6 +30,7 @@ void main() {
|
|||||||
pasteboard = {'files': const [], 'errors': const []};
|
pasteboard = {'files': const [], 'errors': const []};
|
||||||
fileReads = 0;
|
fileReads = 0;
|
||||||
textReads = 0;
|
textReads = 0;
|
||||||
|
clipboardText = 'copied text';
|
||||||
final messenger =
|
final messenger =
|
||||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||||
messenger.setMockMethodCallHandler(chatClipboardFilesChannel, (call) async {
|
messenger.setMockMethodCallHandler(chatClipboardFilesChannel, (call) async {
|
||||||
@@ -40,7 +41,7 @@ void main() {
|
|||||||
messenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {
|
messenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {
|
||||||
if (call.method == 'Clipboard.getData') {
|
if (call.method == 'Clipboard.getData') {
|
||||||
textReads++;
|
textReads++;
|
||||||
return {'text': 'copied text'};
|
return clipboardText == null ? null : {'text': clipboardText};
|
||||||
}
|
}
|
||||||
if (call.method == 'Clipboard.hasStrings') return {'value': true};
|
if (call.method == 'Clipboard.hasStrings') return {'value': true};
|
||||||
return null;
|
return null;
|
||||||
@@ -93,59 +94,81 @@ void main() {
|
|||||||
}, variant: _macOS);
|
}, variant: _macOS);
|
||||||
|
|
||||||
for (final focused in [true, false]) {
|
for (final focused in [true, false]) {
|
||||||
testWidgets(
|
testWidgets('Cmd+V attaches a Finder file and a screenshot '
|
||||||
'Cmd+V attaches a Finder file and a screenshot '
|
'(${focused ? 'focused' : 'unfocused'} composer)', (tester) async {
|
||||||
'(${focused ? 'focused' : 'unfocused'} composer)',
|
pasteboard = {
|
||||||
(tester) async {
|
'files': [
|
||||||
pasteboard = {
|
{
|
||||||
'files': [
|
'name': 'report.pdf',
|
||||||
{
|
'mime': 'application/pdf',
|
||||||
'name': 'report.pdf',
|
'bytes': Uint8List.fromList([1, 2]),
|
||||||
'mime': 'application/pdf',
|
},
|
||||||
'bytes': Uint8List.fromList([1, 2]),
|
{
|
||||||
},
|
'name': '',
|
||||||
{
|
'mime': 'image/png',
|
||||||
'name': '',
|
'bytes': Uint8List.fromList([3]),
|
||||||
'mime': 'image/png',
|
},
|
||||||
'bytes': Uint8List.fromList([3]),
|
],
|
||||||
},
|
'errors': const [],
|
||||||
],
|
};
|
||||||
'errors': const [],
|
await mount(tester);
|
||||||
};
|
if (focused) {
|
||||||
await mount(tester);
|
await tester.showKeyboard(_field);
|
||||||
if (focused) {
|
} else {
|
||||||
await tester.showKeyboard(_field);
|
FocusManager.instance.primaryFocus?.unfocus();
|
||||||
} else {
|
}
|
||||||
FocusManager.instance.primaryFocus?.unfocus();
|
await tester.pump();
|
||||||
}
|
await paste(tester);
|
||||||
await tester.pump();
|
|
||||||
await paste(tester);
|
|
||||||
|
|
||||||
expect(fileReads, 1);
|
expect(fileReads, 1);
|
||||||
expect(find.text('report.pdf'), findsOneWidget);
|
expect(find.text('report.pdf'), findsOneWidget);
|
||||||
expect(find.text('pasted-1.png'), findsOneWidget);
|
expect(find.text('pasted-1.png'), findsOneWidget);
|
||||||
// The pasteboard's file-name text is not pasted alongside the files.
|
// The pasteboard's file-name text is not pasted alongside the files.
|
||||||
expect(textReads, 0);
|
expect(textReads, 0);
|
||||||
expect(composer.draft, isEmpty);
|
expect(composer.draft, isEmpty);
|
||||||
await done(tester);
|
await done(tester);
|
||||||
},
|
}, variant: _macOS);
|
||||||
variant: _macOS,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
testWidgets('Cmd+V of plain text pastes it once into the focused composer', (
|
testWidgets('a paste with nothing usable says what the clipboard held', (
|
||||||
tester,
|
tester,
|
||||||
) async {
|
) async {
|
||||||
|
pasteboard = {
|
||||||
|
'files': const [],
|
||||||
|
'errors': const [],
|
||||||
|
'types': ['com.example.private', 'public.url'],
|
||||||
|
};
|
||||||
|
clipboardText = null;
|
||||||
await mount(tester);
|
await mount(tester);
|
||||||
await tester.showKeyboard(_field);
|
await tester.showKeyboard(_field);
|
||||||
|
await tester.pump();
|
||||||
await paste(tester);
|
await paste(tester);
|
||||||
|
|
||||||
expect(fileReads, 1);
|
expect(fileReads, 1);
|
||||||
expect(textReads, 1);
|
expect(
|
||||||
expect(composer.draft, 'copied text');
|
find.text(
|
||||||
|
chatNothingToPasteMessage(['com.example.private', 'public.url']),
|
||||||
|
),
|
||||||
|
findsOneWidget,
|
||||||
|
);
|
||||||
|
expect(composer.draft, isEmpty);
|
||||||
await done(tester);
|
await done(tester);
|
||||||
}, variant: _macOS);
|
}, variant: _macOS);
|
||||||
|
|
||||||
|
testWidgets(
|
||||||
|
'Cmd+V of plain text pastes it once into the focused composer',
|
||||||
|
(tester) async {
|
||||||
|
await mount(tester);
|
||||||
|
await tester.showKeyboard(_field);
|
||||||
|
await paste(tester);
|
||||||
|
|
||||||
|
expect(fileReads, 1);
|
||||||
|
expect(textReads, 1);
|
||||||
|
expect(composer.draft, 'copied text');
|
||||||
|
await done(tester);
|
||||||
|
},
|
||||||
|
variant: _macOS,
|
||||||
|
);
|
||||||
|
|
||||||
testWidgets('an unreadable pasted file is reported, not dropped silently', (
|
testWidgets('an unreadable pasted file is reported, not dropped silently', (
|
||||||
tester,
|
tester,
|
||||||
) async {
|
) async {
|
||||||
|
|||||||
Reference in New Issue
Block a user