2 * Copyright (C) 2013 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #import "PlatformPasteboard.h"
31 #import "Pasteboard.h"
32 #import "SharedBuffer.h"
34 #import "UTIUtilities.h"
35 #import "WebItemProviderPasteboard.h"
36 #import <MobileCoreServices/MobileCoreServices.h>
37 #import <UIKit/UIImage.h>
38 #import <UIKit/UIPasteboard.h>
39 #import <pal/spi/ios/UIKitSPI.h>
40 #import <wtf/ListHashSet.h>
41 #import <wtf/SoftLinking.h>
42 #import <wtf/text/StringHash.h>
44 SOFT_LINK_FRAMEWORK(UIKit)
45 SOFT_LINK_CLASS(UIKit, UIImage)
46 SOFT_LINK_CLASS(UIKit, UIPasteboard)
50 PlatformPasteboard::PlatformPasteboard()
51 : m_pasteboard([getUIPasteboardClass() generalPasteboard])
55 #if PLATFORM(IOS) && !(PLATFORM(WATCHOS) || PLATFORM(APPLETV))
56 PlatformPasteboard::PlatformPasteboard(const String& name)
58 if (name == "data interaction pasteboard")
59 m_pasteboard = [WebItemProviderPasteboard sharedInstance];
61 m_pasteboard = [getUIPasteboardClass() generalPasteboard];
64 PlatformPasteboard::PlatformPasteboard(const String&)
65 : m_pasteboard([getUIPasteboardClass() generalPasteboard])
70 void PlatformPasteboard::getTypes(Vector<String>& types)
72 for (NSString *pasteboardType in [m_pasteboard pasteboardTypes])
73 types.append(pasteboardType);
76 void PlatformPasteboard::getTypesByFidelityForItemAtIndex(Vector<String>& types, int index)
78 if (index >= [m_pasteboard numberOfItems] || ![m_pasteboard respondsToSelector:@selector(pasteboardTypesByFidelityForItemAtIndex:)])
81 NSArray *pasteboardTypesByFidelity = [m_pasteboard pasteboardTypesByFidelityForItemAtIndex:index];
82 for (NSString *typeIdentifier in pasteboardTypesByFidelity)
83 types.append(typeIdentifier);
86 RefPtr<SharedBuffer> PlatformPasteboard::bufferForType(const String& type)
88 if (NSData *data = [m_pasteboard dataForPasteboardType:type])
89 return SharedBuffer::create(data);
93 void PlatformPasteboard::getPathnamesForType(Vector<String>&, const String&) const
97 int PlatformPasteboard::numberOfFiles() const
99 return [m_pasteboard respondsToSelector:@selector(numberOfFiles)] ? [m_pasteboard numberOfFiles] : 0;
102 Vector<String> PlatformPasteboard::filenamesForDataInteraction()
104 if (![m_pasteboard respondsToSelector:@selector(droppedFileURLs)])
107 Vector<String> filenames;
108 for (NSURL *fileURL in [m_pasteboard droppedFileURLs])
109 filenames.append(fileURL.path);
114 String PlatformPasteboard::stringForType(const String& type)
116 NSArray *values = [m_pasteboard valuesForPasteboardType:type inItemSet:[NSIndexSet indexSetWithIndex:0]];
117 for (id value in values) {
118 if ([value isKindOfClass:[NSURL class]])
119 return [(NSURL *)value absoluteString];
121 if ([value isKindOfClass:[NSAttributedString class]])
122 return [(NSAttributedString *)value string];
124 if ([value isKindOfClass:[NSString class]])
125 return (NSString *)value;
130 Color PlatformPasteboard::color()
135 URL PlatformPasteboard::url()
140 long PlatformPasteboard::copy(const String&)
145 long PlatformPasteboard::addTypes(const Vector<String>&)
150 long PlatformPasteboard::setTypes(const Vector<String>&)
155 long PlatformPasteboard::setBufferForType(SharedBuffer*, const String&)
160 long PlatformPasteboard::setPathnamesForType(const Vector<String>&, const String&)
165 long PlatformPasteboard::setStringForType(const String&, const String&)
170 long PlatformPasteboard::changeCount() const
172 return [m_pasteboard changeCount];
175 String PlatformPasteboard::uniqueName()
180 String PlatformPasteboard::platformPasteboardTypeForSafeTypeForDOMToReadAndWrite(const String& domType)
182 if (domType == "text/plain")
183 return kUTTypePlainText;
185 if (domType == "text/html")
188 if (domType == "text/uri-list")
194 #if PLATFORM(IOS) && !(PLATFORM(WATCHOS) || PLATFORM(APPLETV))
196 static NSString *webIOSPastePboardType = @"iOS rich content paste pasteboard type";
198 static void registerItemToPasteboard(WebItemProviderRegistrationInfoList *representationsToRegister, id <AbstractPasteboard> pasteboard)
200 if (UIItemProvider *itemProvider = representationsToRegister.itemProvider)
201 [pasteboard setItemProviders:@[ itemProvider ]];
203 [pasteboard setItemProviders:@[ ]];
205 if ([pasteboard respondsToSelector:@selector(stageRegistrationList:)])
206 [pasteboard stageRegistrationList:representationsToRegister];
209 static void addRepresentationsForPlainText(WebItemProviderRegistrationInfoList *itemsToRegister, const String& plainText)
211 if (plainText.isEmpty())
214 NSURL *platformURL = [NSURL URLWithString:plainText];
215 if (URL(platformURL).isValid())
216 [itemsToRegister addRepresentingObject:platformURL];
218 [itemsToRegister addData:[(NSString *)plainText dataUsingEncoding:NSUTF8StringEncoding] forType:(NSString *)kUTTypeUTF8PlainText];
221 bool PlatformPasteboard::allowReadingURLAtIndex(const URL& url, int index) const
223 NSItemProvider *itemProvider = (NSUInteger)index < [m_pasteboard itemProviders].count ? [[m_pasteboard itemProviders] objectAtIndex:index] : nil;
224 for (NSString *type in itemProvider.registeredTypeIdentifiers) {
225 if (UTTypeConformsTo((CFStringRef)type, kUTTypeURL))
229 return url.isValid();
232 void PlatformPasteboard::write(const PasteboardWebContent& content)
234 auto representationsToRegister = adoptNS([[WebItemProviderRegistrationInfoList alloc] init]);
236 [representationsToRegister addData:[webIOSPastePboardType dataUsingEncoding:NSUTF8StringEncoding] forType:webIOSPastePboardType];
238 ASSERT(content.clientTypes.size() == content.clientData.size());
239 for (size_t i = 0, size = content.clientTypes.size(); i < size; ++i)
240 [representationsToRegister addData:content.clientData[i]->createNSData().get() forType:content.clientTypes[i]];
242 if (content.dataInWebArchiveFormat)
243 [representationsToRegister addData:content.dataInWebArchiveFormat->createNSData().get() forType:WebArchivePboardType];
245 if (content.dataInAttributedStringFormat) {
246 NSAttributedString *attributedString = [NSKeyedUnarchiver unarchiveObjectWithData:content.dataInAttributedStringFormat->createNSData().get()];
247 if (attributedString)
248 [representationsToRegister addRepresentingObject:attributedString];
251 if (content.dataInRTFDFormat)
252 [representationsToRegister addData:content.dataInRTFDFormat->createNSData().get() forType:(NSString *)kUTTypeFlatRTFD];
254 if (content.dataInRTFFormat)
255 [representationsToRegister addData:content.dataInRTFFormat->createNSData().get() forType:(NSString *)kUTTypeRTF];
257 if (!content.dataInHTMLFormat.isEmpty()) {
258 NSData *htmlAsData = [(NSString *)content.dataInHTMLFormat dataUsingEncoding:NSUTF8StringEncoding];
259 [representationsToRegister addData:htmlAsData forType:(NSString *)kUTTypeHTML];
262 if (!content.dataInStringFormat.isEmpty())
263 addRepresentationsForPlainText(representationsToRegister.get(), content.dataInStringFormat);
265 registerItemToPasteboard(representationsToRegister.get(), m_pasteboard.get());
268 void PlatformPasteboard::write(const PasteboardImage& pasteboardImage)
270 auto representationsToRegister = adoptNS([[WebItemProviderRegistrationInfoList alloc] init]);
272 auto& types = pasteboardImage.clientTypes;
273 auto& data = pasteboardImage.clientData;
274 ASSERT(types.size() == data.size());
275 for (size_t i = 0, size = types.size(); i < size; ++i)
276 [representationsToRegister addData:data[i]->createNSData().get() forType:types[i]];
278 if (pasteboardImage.resourceData && !pasteboardImage.resourceMIMEType.isEmpty()) {
279 auto utiOrMIMEType = pasteboardImage.resourceMIMEType;
280 if (!isDeclaredUTI(utiOrMIMEType))
281 utiOrMIMEType = UTIFromMIMEType(utiOrMIMEType);
283 auto imageData = pasteboardImage.resourceData->createNSData();
284 [representationsToRegister addData:imageData.get() forType:(NSString *)utiOrMIMEType];
285 [representationsToRegister setPreferredPresentationSize:pasteboardImage.imageSize];
286 [representationsToRegister setSuggestedName:pasteboardImage.suggestedName];
289 // FIXME: When writing a PasteboardImage, we currently always place the image data at a higer fidelity than the
290 // associated image URL. However, in the case of an image enclosed by an anchor, we might want to consider the
291 // the URL (i.e. the anchor's href attribute) to be a higher fidelity representation.
292 if (!pasteboardImage.url.url.isEmpty()) {
293 if (NSURL *nsURL = pasteboardImage.url.url)
294 [representationsToRegister addRepresentingObject:nsURL];
297 registerItemToPasteboard(representationsToRegister.get(), m_pasteboard.get());
300 void PlatformPasteboard::write(const String& pasteboardType, const String& text)
302 auto representationsToRegister = adoptNS([[WebItemProviderRegistrationInfoList alloc] init]);
303 [representationsToRegister setPreferredPresentationStyle:WebPreferredPresentationStyleInline];
305 NSString *pasteboardTypeAsNSString = pasteboardType;
306 if (!text.isEmpty() && pasteboardTypeAsNSString.length) {
307 auto pasteboardTypeAsCFString = (CFStringRef)pasteboardTypeAsNSString;
308 if (UTTypeConformsTo(pasteboardTypeAsCFString, kUTTypeURL) || UTTypeConformsTo(pasteboardTypeAsCFString, kUTTypeText))
309 addRepresentationsForPlainText(representationsToRegister.get(), text);
311 [representationsToRegister addData:[pasteboardTypeAsNSString dataUsingEncoding:NSUTF8StringEncoding] forType:pasteboardType];
314 registerItemToPasteboard(representationsToRegister.get(), m_pasteboard.get());
317 void PlatformPasteboard::write(const PasteboardURL& url)
319 auto representationsToRegister = adoptNS([[WebItemProviderRegistrationInfoList alloc] init]);
320 [representationsToRegister setPreferredPresentationStyle:WebPreferredPresentationStyleInline];
322 if (NSURL *nsURL = url.url) {
323 if (!url.title.isEmpty())
324 nsURL._title = url.title;
325 [representationsToRegister addRepresentingObject:nsURL];
328 registerItemToPasteboard(representationsToRegister.get(), m_pasteboard.get());
331 static const char *safeTypeForDOMToReadAndWriteForPlatformType(const String& platformType)
333 auto cfType = platformType.createCFString();
334 if (UTTypeConformsTo(cfType.get(), kUTTypePlainText))
335 return ASCIILiteral("text/plain");
337 if (UTTypeConformsTo(cfType.get(), kUTTypeHTML))
338 return ASCIILiteral("text/html");
340 if (UTTypeConformsTo(cfType.get(), kUTTypeURL))
341 return ASCIILiteral("text/uri-list");
346 static const char originKeyForTeamData[] = "com.apple.WebKit.drag-and-drop-team-data.origin";
347 static const char customTypesKeyForTeamData[] = "com.apple.WebKit.drag-and-drop-team-data.custom-types";
349 Vector<String> PlatformPasteboard::typesSafeForDOMToReadAndWrite(const String& origin) const
351 ListHashSet<String> domPasteboardTypes;
352 for (NSItemProvider *provider in [m_pasteboard itemProviders]) {
353 if (!provider.teamData.length)
356 id teamDataObject = [NSKeyedUnarchiver unarchiveObjectWithData:provider.teamData];
357 if (!teamDataObject || ![teamDataObject isKindOfClass:[NSDictionary class]])
360 id originInTeamData = [(NSDictionary *)teamDataObject objectForKey:@(originKeyForTeamData)];
361 if (![originInTeamData isKindOfClass:[NSString class]])
363 if (String((NSString *)originInTeamData) != origin)
366 id customTypes = [(NSDictionary *)teamDataObject objectForKey:@(customTypesKeyForTeamData)];
367 if (![customTypes isKindOfClass:[NSArray class]])
370 for (NSString *type in customTypes)
371 domPasteboardTypes.add(type);
374 if (NSData *serializedCustomData = [m_pasteboard dataForPasteboardType:@(PasteboardCustomData::cocoaType())]) {
375 auto data = PasteboardCustomData::fromSharedBuffer(SharedBuffer::create(serializedCustomData).get());
376 if (data.origin == origin) {
377 for (auto& type : data.orderedTypes)
378 domPasteboardTypes.add(type);
382 for (NSString *type in [m_pasteboard pasteboardTypes]) {
383 if ([type isEqualToString:@(PasteboardCustomData::cocoaType())])
386 if (Pasteboard::isSafeTypeForDOMToReadAndWrite(type)) {
387 domPasteboardTypes.add(type);
391 if (auto* coercedType = safeTypeForDOMToReadAndWriteForPlatformType(type))
392 domPasteboardTypes.add(String::fromUTF8(coercedType));
395 Vector<String> result;
396 copyToVector(domPasteboardTypes, result);
400 long PlatformPasteboard::write(const PasteboardCustomData& data)
402 auto representationsToRegister = adoptNS([[WebItemProviderRegistrationInfoList alloc] init]);
403 [representationsToRegister setPreferredPresentationStyle:WebPreferredPresentationStyleInline];
405 if (data.sameOriginCustomData.size()) {
406 if (auto serializedSharedBuffer = data.createSharedBuffer()->createNSData()) {
407 // We stash the list of supplied pasteboard types in teamData here for compatibility with drag and drop.
408 // Since the contents of item providers cannot be loaded prior to drop, but the pasteboard types are
409 // contained within the custom data blob and we need to vend them to the page when firing `dragover`
410 // events, we need an additional in-memory representation of the pasteboard types array that contains
411 // all of the custom types. We use the teamData property, available on NSItemProvider on iOS, to store
412 // this information, since the contents of teamData are immediately available prior to the drop.
413 NSMutableArray<NSString *> *typesAsNSArray = [NSMutableArray array];
414 for (auto& type : data.orderedTypes)
415 [typesAsNSArray addObject:type];
416 [representationsToRegister setTeamData:[NSKeyedArchiver archivedDataWithRootObject:@{
417 @(originKeyForTeamData) : data.origin, @(customTypesKeyForTeamData) : typesAsNSArray }]];
418 [representationsToRegister addData:serializedSharedBuffer.get() forType:@(PasteboardCustomData::cocoaType())];
422 for (auto& type : data.orderedTypes) {
423 NSString *stringValue = data.platformData.get(type);
424 if (!stringValue.length)
427 auto cocoaType = platformPasteboardTypeForSafeTypeForDOMToReadAndWrite(type).createCFString();
428 if (UTTypeConformsTo(cocoaType.get(), kUTTypeURL))
429 [representationsToRegister addRepresentingObject:[NSURL URLWithString:stringValue]];
430 else if (UTTypeConformsTo(cocoaType.get(), kUTTypePlainText))
431 [representationsToRegister addRepresentingObject:stringValue];
433 [representationsToRegister addData:[stringValue dataUsingEncoding:NSUTF8StringEncoding] forType:(NSString *)cocoaType.get()];
436 registerItemToPasteboard(representationsToRegister.get(), m_pasteboard.get());
437 return [m_pasteboard changeCount];
442 bool PlatformPasteboard::allowReadingURLAtIndex(const URL&, int) const
447 void PlatformPasteboard::write(const PasteboardWebContent&)
451 void PlatformPasteboard::write(const PasteboardImage&)
455 void PlatformPasteboard::write(const String&, const String&)
459 void PlatformPasteboard::write(const PasteboardURL&)
463 Vector<String> PlatformPasteboard::typesSafeForDOMToReadAndWrite(const String&) const
468 long PlatformPasteboard::write(const PasteboardCustomData&)
475 int PlatformPasteboard::count()
477 return [m_pasteboard numberOfItems];
480 RefPtr<SharedBuffer> PlatformPasteboard::readBuffer(int index, const String& type)
482 NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:index];
484 RetainPtr<NSArray> pasteboardItem = [m_pasteboard dataForPasteboardType:type inItemSet:indexSet];
486 if (![pasteboardItem count])
488 return SharedBuffer::create([pasteboardItem.get() objectAtIndex:0]);
491 String PlatformPasteboard::readString(int index, const String& type)
493 NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:index];
495 NSArray *pasteboardValues = [m_pasteboard valuesForPasteboardType:type inItemSet:indexSet];
496 if (!pasteboardValues.count) {
497 NSArray<NSData *> *pasteboardData = [m_pasteboard dataForPasteboardType:type inItemSet:indexSet];
498 if (!pasteboardData.count)
500 pasteboardValues = pasteboardData;
503 RetainPtr<id> value = [pasteboardValues objectAtIndex:0];
504 if ([value isKindOfClass:[NSData class]])
505 value = adoptNS([[NSString alloc] initWithData:(NSData *)value.get() encoding:NSUTF8StringEncoding]);
507 if (type == String(kUTTypePlainText) || type == String(kUTTypeHTML)) {
508 ASSERT([value isKindOfClass:[NSString class]]);
509 return [value isKindOfClass:[NSString class]] ? value.get() : nil;
511 if (type == String(kUTTypeText)) {
512 ASSERT([value isKindOfClass:[NSString class]] || [value isKindOfClass:[NSAttributedString class]]);
513 if ([value isKindOfClass:[NSString class]])
515 if ([value isKindOfClass:[NSAttributedString class]])
516 return [(NSAttributedString *)value string];
517 } else if (type == String(kUTTypeURL)) {
518 ASSERT([value isKindOfClass:[NSURL class]] || [value isKindOfClass:[NSString class]]);
519 if ([value isKindOfClass:[NSString class]])
520 value = [NSURL URLWithString:value.get()];
521 if ([value isKindOfClass:[NSURL class]] && allowReadingURLAtIndex((NSURL *)value, index))
522 return [(NSURL *)value absoluteString];
528 URL PlatformPasteboard::readURL(int index, const String& type, String& title)
530 NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:index];
531 RetainPtr<NSArray> pasteboardItem = [m_pasteboard valuesForPasteboardType:type inItemSet:indexSet];
533 if (![pasteboardItem count])
536 id value = [pasteboardItem objectAtIndex:0];
538 if ([value isKindOfClass:[NSData class]]) {
539 id plist = [NSPropertyListSerialization propertyListWithData:(NSData *)value options:NSPropertyListImmutable format:NULL error:NULL];
540 if (![plist isKindOfClass:[NSArray class]])
542 NSArray *plistArray = (NSArray *)plist;
543 if (plistArray.count < 2)
545 if (plistArray.count == 2)
546 url = [NSURL URLWithString:plistArray[0]];
547 else // The first string is the relative URL.
548 url = [NSURL URLWithString:plistArray[0] relativeToURL:[NSURL URLWithString:plistArray[1]]];
550 ASSERT([value isKindOfClass:[NSURL class]]);
551 if (![value isKindOfClass:[NSURL class]])
553 url = (NSURL *)value;
556 if (!allowReadingURLAtIndex(url, index))
559 #if PLATFORM(IOS) && !(PLATFORM(WATCHOS) || PLATFORM(APPLETV))
560 title = [url _title];
568 void PlatformPasteboard::updateSupportedTypeIdentifiers(const Vector<String>& types)
570 if (![m_pasteboard respondsToSelector:@selector(updateSupportedTypeIdentifiers:)])
573 NSMutableArray *typesArray = [NSMutableArray arrayWithCapacity:types.size()];
574 for (auto type : types)
575 [typesArray addObject:(NSString *)type];
577 [m_pasteboard updateSupportedTypeIdentifiers:typesArray];