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