3db8ad4e0a223fb1f187c59d60dcfbb8ab15e69b
[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/SoftLinking.h>
41
42 SOFT_LINK_FRAMEWORK(UIKit)
43 SOFT_LINK_CLASS(UIKit, UIImage)
44 SOFT_LINK_CLASS(UIKit, UIPasteboard)
45
46 namespace WebCore {
47
48 PlatformPasteboard::PlatformPasteboard()
49     : m_pasteboard([getUIPasteboardClass() generalPasteboard])
50 {
51 }
52
53 #if ENABLE(DATA_INTERACTION)
54 PlatformPasteboard::PlatformPasteboard(const String& name)
55 {
56     if (name == "data interaction pasteboard")
57         m_pasteboard = [WebItemProviderPasteboard sharedInstance];
58     else
59         m_pasteboard = [getUIPasteboardClass() generalPasteboard];
60 }
61 #else
62 PlatformPasteboard::PlatformPasteboard(const String&)
63     : m_pasteboard([getUIPasteboardClass() generalPasteboard])
64 {
65 }
66 #endif
67
68 void PlatformPasteboard::getTypes(Vector<String>& types)
69 {
70     for (NSString *pasteboardType in [m_pasteboard pasteboardTypes])
71         types.append(pasteboardType);
72 }
73
74 void PlatformPasteboard::getTypesByFidelityForItemAtIndex(Vector<String>& types, int index)
75 {
76     if (index >= [m_pasteboard numberOfItems] || ![m_pasteboard respondsToSelector:@selector(pasteboardTypesByFidelityForItemAtIndex:)])
77         return;
78
79     NSArray *pasteboardTypesByFidelity = [m_pasteboard pasteboardTypesByFidelityForItemAtIndex:index];
80     for (NSString *typeIdentifier in pasteboardTypesByFidelity)
81         types.append(typeIdentifier);
82 }
83
84 RefPtr<SharedBuffer> PlatformPasteboard::bufferForType(const String&)
85 {
86     return nullptr;
87 }
88
89 void PlatformPasteboard::getPathnamesForType(Vector<String>&, const String&)
90 {
91 }
92
93 int PlatformPasteboard::numberOfFiles()
94 {
95     return [m_pasteboard respondsToSelector:@selector(numberOfFiles)] ? [m_pasteboard numberOfFiles] : 0;
96 }
97
98 Vector<String> PlatformPasteboard::filenamesForDataInteraction()
99 {
100     if (![m_pasteboard respondsToSelector:@selector(fileURLsForDataInteraction)])
101         return { };
102
103     Vector<String> filenames;
104     for (NSURL *fileURL in [m_pasteboard fileURLsForDataInteraction])
105         filenames.append(fileURL.path);
106
107     return filenames;
108 }
109
110 String PlatformPasteboard::stringForType(const String& type)
111 {
112     NSArray *values = [m_pasteboard valuesForPasteboardType:type inItemSet:[NSIndexSet indexSetWithIndex:0]];
113     for (id value in values) {
114         if ([value isKindOfClass:[NSURL class]])
115             return [(NSURL *)value absoluteString];
116
117         if ([value isKindOfClass:[NSAttributedString class]])
118             return [(NSAttributedString *)value string];
119
120         if ([value isKindOfClass:[NSString class]])
121             return (NSString *)value;
122     }
123     return String();
124 }
125
126 Color PlatformPasteboard::color()
127 {
128     return Color();
129 }
130
131 URL PlatformPasteboard::url()
132 {
133     return URL();
134 }
135
136 long PlatformPasteboard::copy(const String&)
137 {
138     return 0;
139 }
140
141 long PlatformPasteboard::addTypes(const Vector<String>&)
142 {
143     return 0;
144 }
145
146 long PlatformPasteboard::setTypes(const Vector<String>&)
147 {
148     return 0;
149 }
150
151 long PlatformPasteboard::setBufferForType(SharedBuffer*, const String&)
152 {
153     return 0;
154 }
155
156 long PlatformPasteboard::setPathnamesForType(const Vector<String>&, const String&)
157 {
158     return 0;
159 }
160
161 long PlatformPasteboard::setStringForType(const String&, const String&)
162 {
163     return 0;
164 }
165
166 long PlatformPasteboard::changeCount() const
167 {
168     return [m_pasteboard changeCount];
169 }
170
171 String PlatformPasteboard::uniqueName()
172 {
173     return String();
174 }
175
176 static RetainPtr<NSDictionary> richTextRepresentationsForPasteboardWebContent(const PasteboardWebContent& content)
177 {
178     RetainPtr<NSMutableDictionary> representations = adoptNS([[NSMutableDictionary alloc] init]);
179
180     ASSERT(content.clientTypes.size() == content.clientData.size());
181     for (size_t i = 0, size = content.clientTypes.size(); i < size; ++i)
182         [representations setValue:content.clientData[i]->createNSData().get() forKey:content.clientTypes[i]];
183
184     if (content.dataInWebArchiveFormat) {
185         [representations setValue:(NSData *)content.dataInWebArchiveFormat->createNSData().get() forKey:WebArchivePboardType];
186         // Flag for UIKit to know that this copy contains rich content. This will trigger a two-step paste.
187         NSString *webIOSPastePboardType = @"iOS rich content paste pasteboard type";
188         [representations setValue:webIOSPastePboardType forKey:webIOSPastePboardType];
189     }
190
191     if (content.dataInRTFDFormat)
192         [representations setValue:content.dataInRTFDFormat->createNSData().get() forKey:(NSString *)kUTTypeFlatRTFD];
193     if (content.dataInRTFFormat)
194         [representations setValue:content.dataInRTFFormat->createNSData().get() forKey:(NSString *)kUTTypeRTF];
195
196     return representations;
197 }
198
199 #if ENABLE(DATA_INTERACTION)
200
201 static void addRepresentationsForPlainText(WebItemProviderRegistrationInfoList *itemsToRegister, const String& plainText)
202 {
203     if (plainText.isEmpty())
204         return;
205
206     NSURL *platformURL = [NSURL URLWithString:plainText];
207     if (URL(platformURL).isValid())
208         [itemsToRegister addRepresentingObject:platformURL];
209
210     [itemsToRegister addData:[(NSString *)plainText dataUsingEncoding:NSUTF8StringEncoding] forType:(NSString *)kUTTypeUTF8PlainText];
211 }
212
213 bool PlatformPasteboard::allowReadingURLAtIndex(const URL& url, int index) const
214 {
215     NSItemProvider *itemProvider = (NSUInteger)index < [m_pasteboard itemProviders].count ? [[m_pasteboard itemProviders] objectAtIndex:index] : nil;
216     for (NSString *type in itemProvider.registeredTypeIdentifiers) {
217         if (UTTypeConformsTo((CFStringRef)type, kUTTypeURL))
218             return true;
219     }
220
221     return url.isValid();
222 }
223
224 #else
225
226 bool PlatformPasteboard::allowReadingURLAtIndex(const URL&, int) const
227 {
228     return true;
229 }
230
231 #endif
232
233 void PlatformPasteboard::writeObjectRepresentations(const PasteboardWebContent& content)
234 {
235 #if ENABLE(DATA_INTERACTION)
236     RetainPtr<WebItemProviderRegistrationInfoList> itemsToRegister = adoptNS([[WebItemProviderRegistrationInfoList alloc] init]);
237
238     ASSERT(content.clientTypes.size() == content.clientData.size());
239     for (size_t i = 0, size = content.clientTypes.size(); i < size; ++i)
240         [itemsToRegister addData:content.clientData[i]->createNSData().get() forType:content.clientTypes[i]];
241
242     if (content.dataInWebArchiveFormat)
243         [itemsToRegister addData:content.dataInWebArchiveFormat->createNSData().get() forType:WebArchivePboardType];
244
245     if (content.dataInAttributedStringFormat) {
246         NSAttributedString *attributedString = [NSKeyedUnarchiver unarchiveObjectWithData:content.dataInAttributedStringFormat->createNSData().get()];
247         if (attributedString)
248             [itemsToRegister addRepresentingObject:attributedString];
249     }
250
251     if (content.dataInRTFFormat)
252         [itemsToRegister addData:content.dataInRTFFormat->createNSData().get() forType:(NSString *)kUTTypeRTF];
253
254     if (!content.dataInStringFormat.isEmpty())
255         addRepresentationsForPlainText(itemsToRegister.get(), content.dataInStringFormat);
256
257     [m_pasteboard setItemsUsingRegistrationInfoLists:@[ itemsToRegister.get() ]];
258 #else
259     UNUSED_PARAM(content);
260 #endif
261 }
262
263 void PlatformPasteboard::write(const PasteboardWebContent& content)
264 {
265     if ([m_pasteboard respondsToSelector:@selector(setItemsUsingRegistrationInfoLists:)]) {
266         writeObjectRepresentations(content);
267         return;
268     }
269
270     RetainPtr<NSMutableDictionary> representations = adoptNS([[NSMutableDictionary alloc] init]);
271     [representations addEntriesFromDictionary:richTextRepresentationsForPasteboardWebContent(content).autorelease()];
272
273     NSString *textAsString = content.dataInStringFormat;
274     [representations setValue:[textAsString dataUsingEncoding:NSUTF8StringEncoding] forKey:(NSString *)kUTTypeUTF8PlainText];
275     [representations setValue:[textAsString dataUsingEncoding:NSUTF16StringEncoding] forKey:(NSString *)kUTTypeUTF16PlainText];
276     // FIXME: We vend "public.text" here for backwards compatibility with pre-iOS 11 apps. In the future, we should stop vending this UTI,
277     // and instead set data for concrete plain text types. See <https://bugs.webkit.org/show_bug.cgi?id=173317>.
278     [representations setValue:textAsString forKey:(NSString *)kUTTypeText];
279
280     // Explicitly cast m_pasteboard to UIPasteboard * to work around rdar://problem/33383354.
281     ASSERT([m_pasteboard isKindOfClass:getUIPasteboardClass()]);
282     [(UIPasteboard *)m_pasteboard setItems:@[representations.get()]];
283 }
284
285 void PlatformPasteboard::writeObjectRepresentations(const PasteboardImage& pasteboardImage)
286 {
287 #if ENABLE(DATA_INTERACTION)
288     RetainPtr<WebItemProviderRegistrationInfoList> itemsToRegister = adoptNS([[WebItemProviderRegistrationInfoList alloc] init]);
289
290     auto& types = pasteboardImage.clientTypes;
291     auto& data = pasteboardImage.clientData;
292     ASSERT(types.size() == data.size());
293     for (size_t i = 0, size = types.size(); i < size; ++i)
294         [itemsToRegister addData:data[i]->createNSData().get() forType:types[i]];
295
296     if (pasteboardImage.resourceData && !pasteboardImage.resourceMIMEType.isEmpty()) {
297         auto utiOrMIMEType = pasteboardImage.resourceMIMEType;
298         if (!isDeclaredUTI(utiOrMIMEType))
299             utiOrMIMEType = UTIFromMIMEType(utiOrMIMEType);
300
301         auto imageData = pasteboardImage.resourceData->createNSData();
302         [itemsToRegister addData:imageData.get() forType:(NSString *)utiOrMIMEType];
303         [itemsToRegister setEstimatedDisplayedSize:pasteboardImage.imageSize];
304         [itemsToRegister setSuggestedName:pasteboardImage.suggestedName];
305     }
306
307     if (!pasteboardImage.url.url.isEmpty()) {
308         NSURL *nsURL = pasteboardImage.url.url;
309         if (nsURL)
310             [itemsToRegister addRepresentingObject:nsURL];
311     }
312
313     [m_pasteboard setItemsUsingRegistrationInfoLists:@[ itemsToRegister.get() ]];
314 #else
315     UNUSED_PARAM(pasteboardImage);
316 #endif
317 }
318
319 void PlatformPasteboard::write(const PasteboardImage& pasteboardImage)
320 {
321     if ([m_pasteboard respondsToSelector:@selector(setItemsUsingRegistrationInfoLists:)]) {
322         writeObjectRepresentations(pasteboardImage);
323         return;
324     }
325
326     RetainPtr<NSMutableDictionary> representations = adoptNS([[NSMutableDictionary alloc] init]);
327     if (!pasteboardImage.resourceMIMEType.isNull()) {
328         [representations setObject:pasteboardImage.resourceData->createNSData().get() forKey:pasteboardImage.resourceMIMEType];
329         if (!pasteboardImage.url.url.isNull())
330             [representations setObject:(NSURL *)pasteboardImage.url.url forKey:(NSString *)kUTTypeURL];
331     }
332
333     // Explicitly cast m_pasteboard to UIPasteboard * to work around rdar://problem/33383354.
334     ASSERT([m_pasteboard isKindOfClass:getUIPasteboardClass()]);
335     [(UIPasteboard *)m_pasteboard setItems:@[representations.get()]];
336 }
337
338 void PlatformPasteboard::writeObjectRepresentations(const String& pasteboardType, const String& text)
339 {
340 #if ENABLE(DATA_INTERACTION)
341     RetainPtr<WebItemProviderRegistrationInfoList> itemsToRegister = adoptNS([[WebItemProviderRegistrationInfoList alloc] init]);
342
343     NSString *pasteboardTypeAsNSString = pasteboardType;
344     if (!text.isEmpty() && pasteboardTypeAsNSString.length) {
345         if (UTTypeConformsTo((__bridge CFStringRef)pasteboardTypeAsNSString, kUTTypeURL) || UTTypeConformsTo((__bridge CFStringRef)pasteboardTypeAsNSString, kUTTypeText))
346             addRepresentationsForPlainText(itemsToRegister.get(), text);
347     }
348
349     [m_pasteboard setItemsUsingRegistrationInfoLists:@[ itemsToRegister.get() ]];
350 #else
351     UNUSED_PARAM(pasteboardType);
352     UNUSED_PARAM(text);
353 #endif
354 }
355
356 void PlatformPasteboard::write(const String& pasteboardType, const String& text)
357 {
358     if ([m_pasteboard respondsToSelector:@selector(setItemsUsingRegistrationInfoLists:)]) {
359         writeObjectRepresentations(pasteboardType, text);
360         return;
361     }
362
363     RetainPtr<NSDictionary> representations = adoptNS([[NSMutableDictionary alloc] init]);
364
365     NSString *textAsString = text;
366     if (pasteboardType == String(kUTTypeURL)) {
367         [representations setValue:adoptNS([[NSURL alloc] initWithString:text]).get() forKey:pasteboardType];
368         [representations setValue:textAsString forKey:(NSString *)kUTTypeText];
369     } else if (!pasteboardType.isNull())
370         [representations setValue:textAsString forKey:pasteboardType];
371
372     auto cfPasteboardType = pasteboardType.createCFString();
373     if (UTTypeConformsTo(cfPasteboardType.get(), kUTTypeText) || UTTypeConformsTo(cfPasteboardType.get(), kUTTypeURL)) {
374         [representations setValue:[textAsString dataUsingEncoding:NSUTF8StringEncoding] forKey:(NSString *)kUTTypeUTF8PlainText];
375         [representations setValue:[textAsString dataUsingEncoding:NSUTF16StringEncoding] forKey:(NSString *)kUTTypeUTF16PlainText];
376     }
377
378     // Explicitly cast m_pasteboard to UIPasteboard * to work around rdar://problem/33383354.
379     ASSERT([m_pasteboard isKindOfClass:getUIPasteboardClass()]);
380     [(UIPasteboard *)m_pasteboard setItems:@[representations.get()]];
381 }
382
383 void PlatformPasteboard::writeObjectRepresentations(const PasteboardURL& url)
384 {
385 #if ENABLE(DATA_INTERACTION)
386     RetainPtr<WebItemProviderRegistrationInfoList> itemsToRegister = adoptNS([[WebItemProviderRegistrationInfoList alloc] init]);
387
388     if (NSURL *nsURL = url.url) {
389         [itemsToRegister addRepresentingObject:nsURL];
390         if (!url.title.isEmpty())
391             nsURL._title = url.title;
392     }
393
394     [m_pasteboard setItemsUsingRegistrationInfoLists:@[ itemsToRegister.get() ]];
395 #else
396     UNUSED_PARAM(url);
397 #endif
398 }
399
400 void PlatformPasteboard::write(const PasteboardURL& url)
401 {
402     if ([m_pasteboard respondsToSelector:@selector(setItemsUsingRegistrationInfoLists:)]) {
403         writeObjectRepresentations(url);
404         return;
405     }
406
407     write(kUTTypeURL, url.url.string());
408 }
409
410 int PlatformPasteboard::count()
411 {
412     return [m_pasteboard numberOfItems];
413 }
414
415 RefPtr<SharedBuffer> PlatformPasteboard::readBuffer(int index, const String& type)
416 {
417     NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:index];
418
419     RetainPtr<NSArray> pasteboardItem = [m_pasteboard dataForPasteboardType:type inItemSet:indexSet];
420
421     if (![pasteboardItem count])
422         return nullptr;
423     return SharedBuffer::create([pasteboardItem.get() objectAtIndex:0]);
424 }
425
426 String PlatformPasteboard::readString(int index, const String& type)
427 {
428     NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:index];
429
430     RetainPtr<NSArray> pasteboardItem = [m_pasteboard valuesForPasteboardType:type inItemSet:indexSet];
431
432     if (![pasteboardItem count])
433         return String();
434
435     id value = [pasteboardItem objectAtIndex:0];
436     
437     if (type == String(kUTTypePlainText) || type == String(kUTTypeHTML)) {
438         ASSERT([value isKindOfClass:[NSString class]]);
439         return [value isKindOfClass:[NSString class]] ? value : nil;
440     }
441     if (type == String(kUTTypeText)) {
442         ASSERT([value isKindOfClass:[NSString class]] || [value isKindOfClass:[NSAttributedString class]]);
443         if ([value isKindOfClass:[NSString class]])
444             return value;
445         if ([value isKindOfClass:[NSAttributedString class]])
446             return [(NSAttributedString *)value string];
447     } else if (type == String(kUTTypeURL)) {
448         ASSERT([value isKindOfClass:[NSURL class]]);
449         if ([value isKindOfClass:[NSURL class]] && allowReadingURLAtIndex((NSURL *)value, index))
450             return [(NSURL *)value absoluteString];
451     }
452
453     return String();
454 }
455
456 URL PlatformPasteboard::readURL(int index, const String& type, String& title)
457 {
458     NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:index];
459
460     RetainPtr<NSArray> pasteboardItem = [m_pasteboard valuesForPasteboardType:type inItemSet:indexSet];
461
462     if (![pasteboardItem count])
463         return URL();
464
465     id value = [pasteboardItem objectAtIndex:0];
466     ASSERT([value isKindOfClass:[NSURL class]]);
467     if (![value isKindOfClass:[NSURL class]])
468         return URL();
469
470     if (!allowReadingURLAtIndex((NSURL *)value, index))
471         return { };
472
473 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
474     title = [value _title];
475 #else
476     UNUSED_PARAM(title);
477 #endif
478
479     return (NSURL *)value;
480 }
481
482 void PlatformPasteboard::updateSupportedTypeIdentifiers(const Vector<String>& types)
483 {
484     if (![m_pasteboard respondsToSelector:@selector(updateSupportedTypeIdentifiers:)])
485         return;
486
487     NSMutableArray *typesArray = [NSMutableArray arrayWithCapacity:types.size()];
488     for (auto type : types)
489         [typesArray addObject:(NSString *)type];
490
491     [m_pasteboard updateSupportedTypeIdentifiers:typesArray];
492 }
493
494 }