8bdfd5728c8cc7d82e68b5bd6c4fb2ccc92f5119
[WebKit-https.git] / Source / WebCore / platform / ios / PlatformPasteboardIOS.mm
1 /*
2  * Copyright (C) 2013 Apple Inc.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
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.
12  *
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.
24  */
25
26 #import "config.h"
27 #import "PlatformPasteboard.h"
28
29 #import "Color.h"
30 #import "Image.h"
31 #import "Pasteboard.h"
32 #import "SharedBuffer.h"
33 #import "URL.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>
43
44 SOFT_LINK_FRAMEWORK(UIKit)
45 SOFT_LINK_CLASS(UIKit, UIImage)
46 SOFT_LINK_CLASS(UIKit, UIPasteboard)
47
48 namespace WebCore {
49
50 PlatformPasteboard::PlatformPasteboard()
51     : m_pasteboard([getUIPasteboardClass() generalPasteboard])
52 {
53 }
54
55 #if ENABLE(DATA_INTERACTION)
56 PlatformPasteboard::PlatformPasteboard(const String& name)
57 {
58     if (name == "data interaction pasteboard")
59         m_pasteboard = [WebItemProviderPasteboard sharedInstance];
60     else
61         m_pasteboard = [getUIPasteboardClass() generalPasteboard];
62 }
63 #else
64 PlatformPasteboard::PlatformPasteboard(const String&)
65     : m_pasteboard([getUIPasteboardClass() generalPasteboard])
66 {
67 }
68 #endif
69
70 void PlatformPasteboard::getTypes(Vector<String>& types)
71 {
72     for (NSString *pasteboardType in [m_pasteboard pasteboardTypes])
73         types.append(pasteboardType);
74 }
75
76 void PlatformPasteboard::getTypesByFidelityForItemAtIndex(Vector<String>& types, int index)
77 {
78     if (index >= [m_pasteboard numberOfItems] || ![m_pasteboard respondsToSelector:@selector(pasteboardTypesByFidelityForItemAtIndex:)])
79         return;
80
81     NSArray *pasteboardTypesByFidelity = [m_pasteboard pasteboardTypesByFidelityForItemAtIndex:index];
82     for (NSString *typeIdentifier in pasteboardTypesByFidelity)
83         types.append(typeIdentifier);
84 }
85
86 RefPtr<SharedBuffer> PlatformPasteboard::bufferForType(const String& type)
87 {
88     if (NSData *data = [m_pasteboard dataForPasteboardType:type])
89         return SharedBuffer::create(data);
90     return nullptr;
91 }
92
93 void PlatformPasteboard::getPathnamesForType(Vector<String>&, const String&) const
94 {
95 }
96
97 int PlatformPasteboard::numberOfFiles() const
98 {
99     return [m_pasteboard respondsToSelector:@selector(numberOfFiles)] ? [m_pasteboard numberOfFiles] : 0;
100 }
101
102 Vector<String> PlatformPasteboard::filenamesForDataInteraction()
103 {
104     if (![m_pasteboard respondsToSelector:@selector(droppedFileURLs)])
105         return { };
106
107     Vector<String> filenames;
108     for (NSURL *fileURL in [m_pasteboard droppedFileURLs])
109         filenames.append(fileURL.path);
110
111     return filenames;
112 }
113
114 String PlatformPasteboard::stringForType(const String& type)
115 {
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];
120
121         if ([value isKindOfClass:[NSAttributedString class]])
122             return [(NSAttributedString *)value string];
123
124         if ([value isKindOfClass:[NSString class]])
125             return (NSString *)value;
126     }
127     return String();
128 }
129
130 Color PlatformPasteboard::color()
131 {
132     return Color();
133 }
134
135 URL PlatformPasteboard::url()
136 {
137     return URL();
138 }
139
140 long PlatformPasteboard::copy(const String&)
141 {
142     return 0;
143 }
144
145 long PlatformPasteboard::addTypes(const Vector<String>&)
146 {
147     return 0;
148 }
149
150 long PlatformPasteboard::setTypes(const Vector<String>&)
151 {
152     return 0;
153 }
154
155 long PlatformPasteboard::setBufferForType(SharedBuffer*, const String&)
156 {
157     return 0;
158 }
159
160 long PlatformPasteboard::setPathnamesForType(const Vector<String>&, const String&)
161 {
162     return 0;
163 }
164
165 long PlatformPasteboard::setStringForType(const String&, const String&)
166 {
167     return 0;
168 }
169
170 long PlatformPasteboard::changeCount() const
171 {
172     return [m_pasteboard changeCount];
173 }
174
175 String PlatformPasteboard::uniqueName()
176 {
177     return String();
178 }
179
180 String PlatformPasteboard::platformPasteboardTypeForSafeTypeForDOMToReadAndWrite(const String& domType)
181 {
182     if (domType == "text/plain")
183         return kUTTypePlainText;
184
185     if (domType == "text/html")
186         return kUTTypeHTML;
187
188     if (domType == "text/uri-list")
189         return kUTTypeURL;
190
191     return { };
192 }
193
194 static NSString *webIOSPastePboardType = @"iOS rich content paste pasteboard type";
195
196 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
197
198 static void registerItemToPasteboard(WebItemProviderRegistrationInfoList *representationsToRegister, id <AbstractPasteboard> pasteboard)
199 {
200     if (UIItemProvider *itemProvider = representationsToRegister.itemProvider)
201         [pasteboard setItemProviders:@[ itemProvider ]];
202     else
203         [pasteboard setItemProviders:@[ ]];
204
205     if ([pasteboard respondsToSelector:@selector(stageRegistrationList:)])
206         [pasteboard stageRegistrationList:representationsToRegister];
207 }
208
209 #else
210
211 static RetainPtr<NSDictionary> richTextRepresentationsForPasteboardWebContent(const PasteboardWebContent& content)
212 {
213     RetainPtr<NSMutableDictionary> representations = adoptNS([[NSMutableDictionary alloc] init]);
214
215     ASSERT(content.clientTypes.size() == content.clientData.size());
216     for (size_t i = 0, size = content.clientTypes.size(); i < size; ++i)
217         [representations setValue:content.clientData[i]->createNSData().get() forKey:content.clientTypes[i]];
218
219     if (content.dataInWebArchiveFormat) {
220         [representations setValue:(NSData *)content.dataInWebArchiveFormat->createNSData().get() forKey:WebArchivePboardType];
221         // Flag for UIKit to know that this copy contains rich content. This will trigger a two-step paste.
222         [representations setValue:webIOSPastePboardType forKey:webIOSPastePboardType];
223     }
224
225     if (content.dataInRTFDFormat)
226         [representations setValue:content.dataInRTFDFormat->createNSData().get() forKey:(NSString *)kUTTypeFlatRTFD];
227     if (content.dataInRTFFormat)
228         [representations setValue:content.dataInRTFFormat->createNSData().get() forKey:(NSString *)kUTTypeRTF];
229
230     return representations;
231 }
232
233 #endif
234
235 #if ENABLE(DATA_INTERACTION)
236
237 static void addRepresentationsForPlainText(WebItemProviderRegistrationInfoList *itemsToRegister, const String& plainText)
238 {
239     if (plainText.isEmpty())
240         return;
241
242     NSURL *platformURL = [NSURL URLWithString:plainText];
243     if (URL(platformURL).isValid())
244         [itemsToRegister addRepresentingObject:platformURL];
245
246     [itemsToRegister addData:[(NSString *)plainText dataUsingEncoding:NSUTF8StringEncoding] forType:(NSString *)kUTTypeUTF8PlainText];
247 }
248
249 bool PlatformPasteboard::allowReadingURLAtIndex(const URL& url, int index) const
250 {
251     NSItemProvider *itemProvider = (NSUInteger)index < [m_pasteboard itemProviders].count ? [[m_pasteboard itemProviders] objectAtIndex:index] : nil;
252     for (NSString *type in itemProvider.registeredTypeIdentifiers) {
253         if (UTTypeConformsTo((CFStringRef)type, kUTTypeURL))
254             return true;
255     }
256
257     return url.isValid();
258 }
259
260 #else
261
262 bool PlatformPasteboard::allowReadingURLAtIndex(const URL&, int) const
263 {
264     return true;
265 }
266
267 #endif
268
269 void PlatformPasteboard::write(const PasteboardWebContent& content)
270 {
271 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
272     auto representationsToRegister = adoptNS([[WebItemProviderRegistrationInfoList alloc] init]);
273
274     [representationsToRegister addData:[webIOSPastePboardType dataUsingEncoding:NSUTF8StringEncoding] forType:webIOSPastePboardType];
275
276     ASSERT(content.clientTypes.size() == content.clientData.size());
277     for (size_t i = 0, size = content.clientTypes.size(); i < size; ++i)
278         [representationsToRegister addData:content.clientData[i]->createNSData().get() forType:content.clientTypes[i]];
279
280     if (content.dataInWebArchiveFormat)
281         [representationsToRegister addData:content.dataInWebArchiveFormat->createNSData().get() forType:WebArchivePboardType];
282
283     if (content.dataInAttributedStringFormat) {
284         NSAttributedString *attributedString = [NSKeyedUnarchiver unarchiveObjectWithData:content.dataInAttributedStringFormat->createNSData().get()];
285         if (attributedString)
286             [representationsToRegister addRepresentingObject:attributedString];
287     }
288
289     if (content.dataInRTFDFormat)
290         [representationsToRegister addData:content.dataInRTFDFormat->createNSData().get() forType:(NSString *)kUTTypeFlatRTFD];
291
292     if (content.dataInRTFFormat)
293         [representationsToRegister addData:content.dataInRTFFormat->createNSData().get() forType:(NSString *)kUTTypeRTF];
294
295     if (!content.dataInHTMLFormat.isEmpty()) {
296         NSData *htmlAsData = [(NSString *)content.dataInHTMLFormat dataUsingEncoding:NSUTF8StringEncoding];
297         [representationsToRegister addData:htmlAsData forType:(NSString *)kUTTypeHTML];
298     }
299
300     if (!content.dataInStringFormat.isEmpty())
301         addRepresentationsForPlainText(representationsToRegister.get(), content.dataInStringFormat);
302
303     registerItemToPasteboard(representationsToRegister.get(), m_pasteboard.get());
304 #else
305     RetainPtr<NSMutableDictionary> representations = adoptNS([[NSMutableDictionary alloc] init]);
306     [representations addEntriesFromDictionary:richTextRepresentationsForPasteboardWebContent(content).autorelease()];
307
308     NSString *textAsString = content.dataInStringFormat;
309     [representations setValue:[textAsString dataUsingEncoding:NSUTF8StringEncoding] forKey:(NSString *)kUTTypeUTF8PlainText];
310     [representations setValue:[textAsString dataUsingEncoding:NSUTF16StringEncoding] forKey:(NSString *)kUTTypeUTF16PlainText];
311     // FIXME: We vend "public.text" here for backwards compatibility with pre-iOS 11 apps. In the future, we should stop vending this UTI,
312     // and instead set data for concrete plain text types. See <https://bugs.webkit.org/show_bug.cgi?id=173317>.
313     [representations setValue:textAsString forKey:(NSString *)kUTTypeText];
314
315     // Explicitly cast m_pasteboard to UIPasteboard * to work around rdar://problem/33383354.
316     ASSERT([m_pasteboard isKindOfClass:getUIPasteboardClass()]);
317     [(UIPasteboard *)m_pasteboard setItems:@[representations.get()]];
318 #endif
319 }
320
321 void PlatformPasteboard::write(const PasteboardImage& pasteboardImage)
322 {
323 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
324     auto representationsToRegister = adoptNS([[WebItemProviderRegistrationInfoList alloc] init]);
325
326     auto& types = pasteboardImage.clientTypes;
327     auto& data = pasteboardImage.clientData;
328     ASSERT(types.size() == data.size());
329     for (size_t i = 0, size = types.size(); i < size; ++i)
330         [representationsToRegister addData:data[i]->createNSData().get() forType:types[i]];
331
332     if (pasteboardImage.resourceData && !pasteboardImage.resourceMIMEType.isEmpty()) {
333         auto utiOrMIMEType = pasteboardImage.resourceMIMEType;
334         if (!isDeclaredUTI(utiOrMIMEType))
335             utiOrMIMEType = UTIFromMIMEType(utiOrMIMEType);
336
337         auto imageData = pasteboardImage.resourceData->createNSData();
338         [representationsToRegister addData:imageData.get() forType:(NSString *)utiOrMIMEType];
339         [representationsToRegister setPreferredPresentationSize:pasteboardImage.imageSize];
340         [representationsToRegister setSuggestedName:pasteboardImage.suggestedName];
341     }
342
343     // FIXME: When writing a PasteboardImage, we currently always place the image data at a higer fidelity than the
344     // associated image URL. However, in the case of an image enclosed by an anchor, we might want to consider the
345     // the URL (i.e. the anchor's href attribute) to be a higher fidelity representation.
346     if (!pasteboardImage.url.url.isEmpty()) {
347         if (NSURL *nsURL = pasteboardImage.url.url)
348             [representationsToRegister addRepresentingObject:nsURL];
349     }
350
351     registerItemToPasteboard(representationsToRegister.get(), m_pasteboard.get());
352 #else
353     RetainPtr<NSMutableDictionary> representations = adoptNS([[NSMutableDictionary alloc] init]);
354     if (!pasteboardImage.resourceMIMEType.isNull()) {
355         [representations setObject:pasteboardImage.resourceData->createNSData().get() forKey:pasteboardImage.resourceMIMEType];
356         if (!pasteboardImage.url.url.isNull())
357             [representations setObject:(NSURL *)pasteboardImage.url.url forKey:(NSString *)kUTTypeURL];
358     }
359
360     // Explicitly cast m_pasteboard to UIPasteboard * to work around rdar://problem/33383354.
361     ASSERT([m_pasteboard isKindOfClass:getUIPasteboardClass()]);
362     [(UIPasteboard *)m_pasteboard setItems:@[representations.get()]];
363 #endif
364 }
365
366 void PlatformPasteboard::write(const String& pasteboardType, const String& text)
367 {
368 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
369     auto representationsToRegister = adoptNS([[WebItemProviderRegistrationInfoList alloc] init]);
370     [representationsToRegister setPreferredPresentationStyle:WebPreferredPresentationStyleInline];
371
372     NSString *pasteboardTypeAsNSString = pasteboardType;
373     if (!text.isEmpty() && pasteboardTypeAsNSString.length) {
374         auto pasteboardTypeAsCFString = (CFStringRef)pasteboardTypeAsNSString;
375         if (UTTypeConformsTo(pasteboardTypeAsCFString, kUTTypeURL) || UTTypeConformsTo(pasteboardTypeAsCFString, kUTTypeText))
376             addRepresentationsForPlainText(representationsToRegister.get(), text);
377         else
378             [representationsToRegister addData:[pasteboardTypeAsNSString dataUsingEncoding:NSUTF8StringEncoding] forType:pasteboardType];
379     }
380
381     registerItemToPasteboard(representationsToRegister.get(), m_pasteboard.get());
382 #else
383     RetainPtr<NSDictionary> representations = adoptNS([[NSMutableDictionary alloc] init]);
384
385     NSString *textAsString = text;
386     if (pasteboardType == String(kUTTypeURL)) {
387         [representations setValue:adoptNS([[NSURL alloc] initWithString:text]).get() forKey:pasteboardType];
388         [representations setValue:textAsString forKey:(NSString *)kUTTypeText];
389     } else if (!pasteboardType.isNull())
390         [representations setValue:textAsString forKey:pasteboardType];
391
392     auto cfPasteboardType = pasteboardType.createCFString();
393     if (UTTypeConformsTo(cfPasteboardType.get(), kUTTypeText) || UTTypeConformsTo(cfPasteboardType.get(), kUTTypeURL)) {
394         [representations setValue:[textAsString dataUsingEncoding:NSUTF8StringEncoding] forKey:(NSString *)kUTTypeUTF8PlainText];
395         [representations setValue:[textAsString dataUsingEncoding:NSUTF16StringEncoding] forKey:(NSString *)kUTTypeUTF16PlainText];
396     }
397
398     // Explicitly cast m_pasteboard to UIPasteboard * to work around rdar://problem/33383354.
399     ASSERT([m_pasteboard isKindOfClass:getUIPasteboardClass()]);
400     [(UIPasteboard *)m_pasteboard setItems:@[representations.get()]];
401 #endif
402 }
403
404 void PlatformPasteboard::write(const PasteboardURL& url)
405 {
406 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
407     auto representationsToRegister = adoptNS([[WebItemProviderRegistrationInfoList alloc] init]);
408     [representationsToRegister setPreferredPresentationStyle:WebPreferredPresentationStyleInline];
409
410     if (NSURL *nsURL = url.url) {
411         if (!url.title.isEmpty())
412             nsURL._title = url.title;
413         [representationsToRegister addRepresentingObject:nsURL];
414     }
415
416     registerItemToPasteboard(representationsToRegister.get(), m_pasteboard.get());
417 #else
418     write(kUTTypeURL, url.url.string());
419 #endif
420 }
421
422 static const char *safeTypeForDOMToReadAndWriteForPlatformType(const String& platformType)
423 {
424     auto cfType = platformType.createCFString();
425     if (UTTypeConformsTo(cfType.get(), kUTTypePlainText))
426         return ASCIILiteral("text/plain");
427
428     if (UTTypeConformsTo(cfType.get(), kUTTypeHTML))
429         return ASCIILiteral("text/html");
430
431     if (UTTypeConformsTo(cfType.get(), kUTTypeURL))
432         return ASCIILiteral("text/uri-list");
433
434     return nullptr;
435 }
436
437 Vector<String> PlatformPasteboard::typesSafeForDOMToReadAndWrite() const
438 {
439 #if TARGET_OS_IPHONE
440     ListHashSet<String> domPasteboardTypes;
441     for (NSItemProvider *provider in [m_pasteboard itemProviders]) {
442         if (!provider.teamData.length)
443             continue;
444
445         id teamDataObject = [NSKeyedUnarchiver unarchiveObjectWithData:provider.teamData];
446         if (!teamDataObject || ![teamDataObject isKindOfClass:[NSDictionary class]])
447             continue;
448
449         id customTypes = [(NSDictionary *)teamDataObject objectForKey:@(customWebKitPasteboardDataType)];
450         if (![customTypes isKindOfClass:[NSArray class]])
451             continue;
452
453         for (NSString *type in customTypes)
454             domPasteboardTypes.add(type);
455     }
456
457     if (NSData *serializedCustomData = [m_pasteboard dataForPasteboardType:@(customWebKitPasteboardDataType)]) {
458         auto buffer = SharedBuffer::create(serializedCustomData);
459         for (auto& type : customDataFromSharedBuffer(buffer.get()).orderedTypes)
460             domPasteboardTypes.add(type);
461     }
462
463     for (NSString *type in [m_pasteboard pasteboardTypes]) {
464         if ([type isEqualToString:@(customWebKitPasteboardDataType)])
465             continue;
466
467         if (isSafeTypeForDOMToReadAndWrite(type)) {
468             domPasteboardTypes.add(type);
469             continue;
470         }
471
472         if (auto* coercedType = safeTypeForDOMToReadAndWriteForPlatformType(type))
473             domPasteboardTypes.add(String::fromUTF8(coercedType));
474     }
475
476     Vector<String> result;
477     copyToVector(domPasteboardTypes, result);
478     return result;
479 #else
480     return { };
481 #endif
482 }
483
484 long PlatformPasteboard::write(const PasteboardCustomData& data)
485 {
486 #if TARGET_OS_IPHONE
487     auto representationsToRegister = adoptNS([[WebItemProviderRegistrationInfoList alloc] init]);
488     [representationsToRegister setPreferredPresentationStyle:WebPreferredPresentationStyleInline];
489
490     if (data.sameOriginCustomData.size()) {
491         if (auto serializedSharedBuffer = sharedBufferFromCustomData(data)->createNSData()) {
492             // We stash the list of supplied pasteboard types in teamData here for compatibility with drag and drop.
493             // Since the contents of item providers cannot be loaded prior to drop, but the pasteboard types are
494             // contained within the custom data blob and we need to vend them to the page when firing `dragover`
495             // events, we need an additional in-memory representation of the pasteboard types array that contains
496             // all of the custom types. We use the teamData property, available on NSItemProvider on iOS, to store
497             // this information, since the contents of teamData are immediately available prior to the drop.
498             NSMutableArray<NSString *> *typesAsNSArray = [NSMutableArray array];
499             for (auto& type : data.orderedTypes)
500                 [typesAsNSArray addObject:type];
501             [representationsToRegister setTeamData:[NSKeyedArchiver archivedDataWithRootObject:@{ @(customWebKitPasteboardDataType) : typesAsNSArray }]];
502             [representationsToRegister addData:serializedSharedBuffer.get() forType:@(customWebKitPasteboardDataType)];
503         }
504     }
505
506     for (auto& type : data.orderedTypes) {
507         NSString *stringValue = data.platformData.get(type);
508         if (!stringValue.length)
509             continue;
510
511         auto cocoaType = platformPasteboardTypeForSafeTypeForDOMToReadAndWrite(type).createCFString();
512         if (UTTypeConformsTo(cocoaType.get(), kUTTypeURL))
513             [representationsToRegister addRepresentingObject:[NSURL URLWithString:stringValue]];
514         else if (UTTypeConformsTo(cocoaType.get(), kUTTypePlainText))
515             [representationsToRegister addRepresentingObject:stringValue];
516         else
517             [representationsToRegister addData:[stringValue dataUsingEncoding:NSUTF8StringEncoding] forType:(NSString *)cocoaType.get()];
518     }
519
520     registerItemToPasteboard(representationsToRegister.get(), m_pasteboard.get());
521     return [m_pasteboard changeCount];
522 #else
523     UNUSED_PARAM(data);
524 #endif
525 }
526
527 int PlatformPasteboard::count()
528 {
529     return [m_pasteboard numberOfItems];
530 }
531
532 RefPtr<SharedBuffer> PlatformPasteboard::readBuffer(int index, const String& type)
533 {
534     NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:index];
535
536     RetainPtr<NSArray> pasteboardItem = [m_pasteboard dataForPasteboardType:type inItemSet:indexSet];
537
538     if (![pasteboardItem count])
539         return nullptr;
540     return SharedBuffer::create([pasteboardItem.get() objectAtIndex:0]);
541 }
542
543 String PlatformPasteboard::readString(int index, const String& type)
544 {
545     NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:index];
546
547     NSArray *pasteboardValues = [m_pasteboard valuesForPasteboardType:type inItemSet:indexSet];
548     if (!pasteboardValues.count) {
549         NSArray<NSData *> *pasteboardData = [m_pasteboard dataForPasteboardType:type inItemSet:indexSet];
550         if (!pasteboardData.count)
551             return { };
552         pasteboardValues = pasteboardData;
553     }
554
555     RetainPtr<id> value = [pasteboardValues objectAtIndex:0];
556     if ([value isKindOfClass:[NSData class]])
557         value = adoptNS([[NSString alloc] initWithData:(NSData *)value.get() encoding:NSUTF8StringEncoding]);
558     
559     if (type == String(kUTTypePlainText) || type == String(kUTTypeHTML)) {
560         ASSERT([value isKindOfClass:[NSString class]]);
561         return [value isKindOfClass:[NSString class]] ? value.get() : nil;
562     }
563     if (type == String(kUTTypeText)) {
564         ASSERT([value isKindOfClass:[NSString class]] || [value isKindOfClass:[NSAttributedString class]]);
565         if ([value isKindOfClass:[NSString class]])
566             return value.get();
567         if ([value isKindOfClass:[NSAttributedString class]])
568             return [(NSAttributedString *)value string];
569     } else if (type == String(kUTTypeURL)) {
570         ASSERT([value isKindOfClass:[NSURL class]] || [value isKindOfClass:[NSString class]]);
571         if ([value isKindOfClass:[NSString class]])
572             value = [NSURL URLWithString:value.get()];
573         if ([value isKindOfClass:[NSURL class]] && allowReadingURLAtIndex((NSURL *)value, index))
574             return [(NSURL *)value absoluteString];
575     }
576
577     return String();
578 }
579
580 URL PlatformPasteboard::readURL(int index, const String& type, String& title)
581 {
582     NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:index];
583
584     RetainPtr<NSArray> pasteboardItem = [m_pasteboard valuesForPasteboardType:type inItemSet:indexSet];
585
586     if (![pasteboardItem count])
587         return URL();
588
589     id value = [pasteboardItem objectAtIndex:0];
590     ASSERT([value isKindOfClass:[NSURL class]]);
591     if (![value isKindOfClass:[NSURL class]])
592         return URL();
593
594     if (!allowReadingURLAtIndex((NSURL *)value, index))
595         return { };
596
597 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
598     title = [value _title];
599 #else
600     UNUSED_PARAM(title);
601 #endif
602
603     return (NSURL *)value;
604 }
605
606 void PlatformPasteboard::updateSupportedTypeIdentifiers(const Vector<String>& types)
607 {
608     if (![m_pasteboard respondsToSelector:@selector(updateSupportedTypeIdentifiers:)])
609         return;
610
611     NSMutableArray *typesArray = [NSMutableArray arrayWithCapacity:types.size()];
612     for (auto type : types)
613         [typesArray addObject:(NSString *)type];
614
615     [m_pasteboard updateSupportedTypeIdentifiers:typesArray];
616 }
617
618 }