a90ec3db9d88be7ab5e3191e94140474645b41aa
[WebKit-https.git] / Source / WebCore / platform / mac / PasteboardMac.mm
1 /*
2  * Copyright (C) 2006, 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 "Pasteboard.h"
28
29 #import "CachedImage.h"
30 #import "Document.h"
31 #import "DocumentFragment.h"
32 #import "DocumentLoader.h"
33 #import "DragData.h"
34 #import "Editing.h"
35 #import "Editor.h"
36 #import "EditorClient.h"
37 #import "Frame.h"
38 #import "FrameLoaderClient.h"
39 #import "FrameView.h"
40 #import "HitTestResult.h"
41 #import "Image.h"
42 #import "LegacyWebArchive.h"
43 #import "LoaderNSURLExtras.h"
44 #import "MIMETypeRegistry.h"
45 #import "PasteboardStrategy.h"
46 #import "PlatformStrategies.h"
47 #import "RenderImage.h"
48 #import "Text.h"
49 #import "URL.h"
50 #import "WebCoreNSStringExtras.h"
51 #import "WebNSAttributedStringExtras.h"
52 #import "markup.h"
53 #import <wtf/RetainPtr.h>
54 #import <wtf/StdLibExtras.h>
55 #import <wtf/text/StringBuilder.h>
56 #import <wtf/unicode/CharacterNames.h>
57
58 namespace WebCore {
59
60 const char* const WebArchivePboardType = "Apple Web Archive pasteboard type";
61 const char* const WebURLNamePboardType = "public.url-name";
62
63 const char WebSmartPastePboardType[] = "NeXT smart paste pasteboard type";
64 const char WebURLPboardType[] = "public.url";
65 const char WebURLsWithTitlesPboardType[] = "WebURLsWithTitlesPboardType";
66
67 // Making this non-inline so that WebKit 2's decoding doesn't have to include SharedBuffer.h.
68 PasteboardWebContent::PasteboardWebContent()
69 {
70 }
71
72 PasteboardWebContent::~PasteboardWebContent()
73 {
74 }
75
76 // Making this non-inline so that WebKit 2's decoding doesn't have to include Image.h.
77 PasteboardImage::PasteboardImage()
78 {
79 }
80
81 PasteboardImage::~PasteboardImage()
82 {
83 }
84
85 static const Vector<String> writableTypesForURL()
86 {
87     Vector<String> types;
88     
89     types.append(WebURLsWithTitlesPboardType);
90     types.append(String(NSURLPboardType));
91     types.append(WebURLPboardType);
92     types.append(WebURLNamePboardType);
93     types.append(String(NSStringPboardType));        
94     return types;
95 }
96
97 static Vector<String> writableTypesForImage()
98 {
99     Vector<String> types;
100     types.append(String(NSTIFFPboardType));
101     types.appendVector(writableTypesForURL());
102     types.append(String(NSRTFDPboardType));
103     return types;
104 }
105
106 Pasteboard::Pasteboard()
107     : m_pasteboardName(emptyString())
108     , m_changeCount(0)
109 {
110 }
111
112 Pasteboard::Pasteboard(const String& pasteboardName)
113     : m_pasteboardName(pasteboardName)
114     , m_changeCount(platformStrategies()->pasteboardStrategy()->changeCount(m_pasteboardName))
115 {
116     ASSERT(pasteboardName);
117 }
118
119 std::unique_ptr<Pasteboard> Pasteboard::createForCopyAndPaste()
120 {
121 #pragma clang diagnostic push
122 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
123     return std::make_unique<Pasteboard>(NSGeneralPboard);
124 #pragma clang diagnostic pop
125 }
126
127 std::unique_ptr<Pasteboard> Pasteboard::createPrivate()
128 {
129     return std::make_unique<Pasteboard>(platformStrategies()->pasteboardStrategy()->uniqueName());
130 }
131
132 #if ENABLE(DRAG_SUPPORT)
133 std::unique_ptr<Pasteboard> Pasteboard::createForDragAndDrop()
134 {
135 #pragma clang diagnostic push
136 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
137     return std::make_unique<Pasteboard>(NSDragPboard);
138 #pragma clang diagnostic pop
139 }
140
141 std::unique_ptr<Pasteboard> Pasteboard::createForDragAndDrop(const DragData& dragData)
142 {
143     return std::make_unique<Pasteboard>(dragData.pasteboardName());
144 }
145 #endif
146
147 void Pasteboard::clear()
148 {
149     m_changeCount = platformStrategies()->pasteboardStrategy()->setTypes(Vector<String>(), m_pasteboardName);
150 }
151
152 void Pasteboard::write(const PasteboardWebContent& content)
153 {
154     Vector<String> types;
155
156     if (content.canSmartCopyOrDelete)
157         types.append(WebSmartPastePboardType);
158     if (content.dataInWebArchiveFormat)
159         types.append(WebArchivePboardType);
160     if (content.dataInRTFDFormat)
161         types.append(String(NSRTFDPboardType));
162     if (content.dataInRTFFormat)
163         types.append(String(NSRTFPboardType));
164     if (!content.dataInHTMLFormat.isNull())
165         types.append(String(NSHTMLPboardType));
166     if (!content.dataInStringFormat.isNull())
167         types.append(String(NSStringPboardType));
168     types.appendVector(content.clientTypes);
169
170     m_changeCount = platformStrategies()->pasteboardStrategy()->setTypes(types, m_pasteboardName);
171
172     ASSERT(content.clientTypes.size() == content.clientData.size());
173     for (size_t i = 0, size = content.clientTypes.size(); i < size; ++i)
174         m_changeCount = platformStrategies()->pasteboardStrategy()->setBufferForType(content.clientData[i].get(), content.clientTypes[i], m_pasteboardName);
175     if (content.canSmartCopyOrDelete)
176         m_changeCount = platformStrategies()->pasteboardStrategy()->setBufferForType(nullptr, WebSmartPastePboardType, m_pasteboardName);
177     if (content.dataInWebArchiveFormat)
178         m_changeCount = platformStrategies()->pasteboardStrategy()->setBufferForType(content.dataInWebArchiveFormat.get(), WebArchivePboardType, m_pasteboardName);
179     if (content.dataInRTFDFormat)
180         m_changeCount = platformStrategies()->pasteboardStrategy()->setBufferForType(content.dataInRTFDFormat.get(), NSRTFDPboardType, m_pasteboardName);
181     if (content.dataInRTFFormat)
182         m_changeCount = platformStrategies()->pasteboardStrategy()->setBufferForType(content.dataInRTFFormat.get(), NSRTFPboardType, m_pasteboardName);
183     if (!content.dataInHTMLFormat.isNull())
184         m_changeCount = platformStrategies()->pasteboardStrategy()->setStringForType(content.dataInHTMLFormat, NSHTMLPboardType, m_pasteboardName);
185     if (!content.dataInStringFormat.isNull())
186         m_changeCount = platformStrategies()->pasteboardStrategy()->setStringForType(content.dataInStringFormat, NSStringPboardType, m_pasteboardName);
187 }
188
189 void Pasteboard::writePlainText(const String& text, SmartReplaceOption smartReplaceOption)
190 {
191     Vector<String> types;
192     types.append(NSStringPboardType);
193     if (smartReplaceOption == CanSmartReplace)
194         types.append(WebSmartPastePboardType);
195
196     platformStrategies()->pasteboardStrategy()->setTypes(types, m_pasteboardName);
197     m_changeCount = platformStrategies()->pasteboardStrategy()->setStringForType(text, NSStringPboardType, m_pasteboardName);
198     if (smartReplaceOption == CanSmartReplace)
199         m_changeCount = platformStrategies()->pasteboardStrategy()->setBufferForType(0, WebSmartPastePboardType, m_pasteboardName);
200 }
201
202 static long writeURLForTypes(const Vector<String>& types, const String& pasteboardName, const PasteboardURL& pasteboardURL)
203 {
204     long newChangeCount = platformStrategies()->pasteboardStrategy()->setTypes(types, pasteboardName);
205     
206     ASSERT(!pasteboardURL.url.isEmpty());
207     
208     NSURL *cocoaURL = pasteboardURL.url;
209     NSString *userVisibleString = pasteboardURL.userVisibleForm;
210     NSString *title = (NSString *)pasteboardURL.title;
211     if (![title length]) {
212         title = [[cocoaURL path] lastPathComponent];
213         if (![title length])
214             title = userVisibleString;
215     }
216
217     if (types.contains(WebURLsWithTitlesPboardType)) {
218         Vector<String> paths;
219         paths.append([cocoaURL absoluteString]);
220         paths.append(pasteboardURL.title.stripWhiteSpace());
221         newChangeCount = platformStrategies()->pasteboardStrategy()->setPathnamesForType(paths, WebURLsWithTitlesPboardType, pasteboardName);
222     }
223     if (types.contains(String(NSURLPboardType)))
224         newChangeCount = platformStrategies()->pasteboardStrategy()->setStringForType([cocoaURL absoluteString], NSURLPboardType, pasteboardName);
225     if (types.contains(WebURLPboardType))
226         newChangeCount = platformStrategies()->pasteboardStrategy()->setStringForType(userVisibleString, WebURLPboardType, pasteboardName);
227     if (types.contains(WebURLNamePboardType))
228         newChangeCount = platformStrategies()->pasteboardStrategy()->setStringForType(title, WebURLNamePboardType, pasteboardName);
229     if (types.contains(String(NSStringPboardType)))
230         newChangeCount = platformStrategies()->pasteboardStrategy()->setStringForType(userVisibleString, NSStringPboardType, pasteboardName);
231
232     return newChangeCount;
233 }
234     
235 void Pasteboard::write(const PasteboardURL& pasteboardURL)
236 {
237     m_changeCount = writeURLForTypes(writableTypesForURL(), m_pasteboardName, pasteboardURL);
238 }
239
240 void Pasteboard::writeTrustworthyWebURLsPboardType(const PasteboardURL& pasteboardURL)
241 {
242     NSURL *cocoaURL = pasteboardURL.url;
243     Vector<String> paths = { [cocoaURL absoluteString], pasteboardURL.title.stripWhiteSpace() };
244     m_changeCount = platformStrategies()->pasteboardStrategy()->setPathnamesForType(paths, WebURLsWithTitlesPboardType, m_pasteboardName);
245 }
246
247 static NSFileWrapper* fileWrapper(const PasteboardImage& pasteboardImage)
248 {
249     NSFileWrapper *wrapper = [[[NSFileWrapper alloc] initRegularFileWithContents:pasteboardImage.resourceData->createNSData().get()] autorelease];
250     [wrapper setPreferredFilename:suggestedFilenameWithMIMEType(pasteboardImage.url.url, pasteboardImage.resourceMIMEType)];
251     return wrapper;
252 }
253
254 static void writeFileWrapperAsRTFDAttachment(NSFileWrapper *wrapper, const String& pasteboardName, long& newChangeCount)
255 {
256     NSTextAttachment *attachment = [[NSTextAttachment alloc] initWithFileWrapper:wrapper];
257     NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attachment];
258     [attachment release];
259
260     NSData *RTFDData = [string RTFDFromRange:NSMakeRange(0, [string length]) documentAttributes:@{ }];
261     if (!RTFDData)
262         return;
263
264     newChangeCount = platformStrategies()->pasteboardStrategy()->setBufferForType(SharedBuffer::wrapNSData(RTFDData).ptr(), NSRTFDPboardType, pasteboardName);
265 }
266
267 void Pasteboard::write(const PasteboardImage& pasteboardImage)
268 {
269     CFDataRef imageData = pasteboardImage.image->tiffRepresentation();
270     if (!imageData)
271         return;
272
273     // FIXME: Why can we assert this? It doesn't seem like it's guaranteed.
274     ASSERT(MIMETypeRegistry::isSupportedImageResourceMIMEType(pasteboardImage.resourceMIMEType));
275
276     auto types = writableTypesForImage();
277     if (pasteboardImage.dataInWebArchiveFormat)
278         types.append(WebArchivePboardType);
279
280     m_changeCount = writeURLForTypes(types, m_pasteboardName, pasteboardImage.url);
281     m_changeCount = platformStrategies()->pasteboardStrategy()->setBufferForType(SharedBuffer::wrapCFData(imageData).ptr(), NSTIFFPboardType, m_pasteboardName);
282     if (pasteboardImage.dataInWebArchiveFormat)
283         m_changeCount = platformStrategies()->pasteboardStrategy()->setBufferForType(pasteboardImage.dataInWebArchiveFormat.get(), WebArchivePboardType, m_pasteboardName);
284     writeFileWrapperAsRTFDAttachment(fileWrapper(pasteboardImage), m_pasteboardName, m_changeCount);
285 }
286
287 void Pasteboard::writePasteboard(const Pasteboard& pasteboard)
288 {
289     m_changeCount = platformStrategies()->pasteboardStrategy()->copy(pasteboard.m_pasteboardName, m_pasteboardName);
290 }
291
292 bool Pasteboard::canSmartReplace()
293 {
294     Vector<String> types;
295     platformStrategies()->pasteboardStrategy()->getTypes(types, m_pasteboardName);
296     return types.contains(WebSmartPastePboardType);
297 }
298
299 void Pasteboard::writeMarkup(const String&)
300 {
301 }
302
303 void Pasteboard::read(PasteboardPlainText& text)
304 {
305     PasteboardStrategy& strategy = *platformStrategies()->pasteboardStrategy();
306
307     Vector<String> types;
308     strategy.getTypes(types, m_pasteboardName);
309
310     if (types.contains(String(NSPasteboardTypeString))) {
311         text.text = strategy.stringForType(NSPasteboardTypeString, m_pasteboardName);
312         text.isURL = false;
313         return;
314     }
315
316     if (types.contains(String(NSStringPboardType))) {
317         text.text = strategy.stringForType(NSStringPboardType, m_pasteboardName);
318         text.isURL = false;
319         return;
320     }
321     
322     if (types.contains(String(NSRTFDPboardType))) {
323         if (RefPtr<SharedBuffer> data = strategy.bufferForType(NSRTFDPboardType, m_pasteboardName)) {
324             if (auto attributedString = adoptNS([[NSAttributedString alloc] initWithRTFD:data->createNSData().get() documentAttributes:NULL])) {
325                 text.text = [attributedString string];
326                 text.isURL = false;
327                 return;
328             }
329         }
330     }
331
332     if (types.contains(String(NSRTFPboardType))) {
333         if (RefPtr<SharedBuffer> data = strategy.bufferForType(NSRTFPboardType, m_pasteboardName)) {
334             if (auto attributedString = adoptNS([[NSAttributedString alloc] initWithRTF:data->createNSData().get() documentAttributes:NULL])) {
335                 text.text = [attributedString string];
336                 text.isURL = false;
337                 return;
338             }
339         }
340     }
341
342     if (types.contains(String(NSFilenamesPboardType))) {
343         Vector<String> pathnames;
344         strategy.getPathnamesForType(pathnames, NSFilenamesPboardType, m_pasteboardName);
345         StringBuilder builder;
346         for (size_t i = 0, size = pathnames.size(); i < size; i++) {
347             if (i)
348                 builder.append('\n');
349             builder.append(pathnames[i]);
350         }
351         text.text = builder.toString();
352         text.isURL = false;
353         return;
354     }
355
356     // FIXME: The code above looks at the types vector first, but this just gets the string without checking. Why the difference?
357     text.text = strategy.stringForType(NSURLPboardType, m_pasteboardName);
358     text.isURL = !text.text.isNull();
359 }
360
361 void Pasteboard::read(PasteboardWebContentReader& reader)
362 {
363     PasteboardStrategy& strategy = *platformStrategies()->pasteboardStrategy();
364
365     Vector<String> types;
366     strategy.getTypes(types, m_pasteboardName);
367
368     if (types.contains(WebArchivePboardType)) {
369         if (RefPtr<SharedBuffer> buffer = strategy.bufferForType(WebArchivePboardType, m_pasteboardName)) {
370             if (reader.readWebArchive(buffer.get()))
371                 return;
372         }
373     }
374
375     if (types.contains(String(NSFilenamesPboardType))) {
376         Vector<String> paths;
377         strategy.getPathnamesForType(paths, NSFilenamesPboardType, m_pasteboardName);
378         if (reader.readFilenames(paths))
379             return;
380     }
381
382     if (types.contains(String(NSHTMLPboardType))) {
383         String string = strategy.stringForType(NSHTMLPboardType, m_pasteboardName);
384         if (!string.isNull() && reader.readHTML(string))
385             return;
386     }
387
388     if (types.contains(String(NSRTFDPboardType))) {
389         if (RefPtr<SharedBuffer> buffer = strategy.bufferForType(NSRTFDPboardType, m_pasteboardName)) {
390             if (reader.readRTFD(*buffer))
391                 return;
392         }
393     }
394
395     if (types.contains(String(NSRTFPboardType))) {
396         if (RefPtr<SharedBuffer> buffer = strategy.bufferForType(NSRTFPboardType, m_pasteboardName)) {
397             if (reader.readRTF(*buffer))
398                 return;
399         }
400     }
401
402     if (types.contains(String(NSTIFFPboardType))) {
403         if (RefPtr<SharedBuffer> buffer = strategy.bufferForType(NSTIFFPboardType, m_pasteboardName)) {
404             if (reader.readImage(buffer.releaseNonNull(), ASCIILiteral("image/tiff")))
405                 return;
406         }
407     }
408
409     if (types.contains(String(NSPDFPboardType))) {
410         if (RefPtr<SharedBuffer> buffer = strategy.bufferForType(NSPDFPboardType, m_pasteboardName)) {
411             if (reader.readImage(buffer.releaseNonNull(), ASCIILiteral("application/pdf")))
412                 return;
413         }
414     }
415
416     if (types.contains(String(kUTTypePNG))) {
417         if (RefPtr<SharedBuffer> buffer = strategy.bufferForType(kUTTypePNG, m_pasteboardName)) {
418             if (reader.readImage(buffer.releaseNonNull(), ASCIILiteral("image/png")))
419                 return;
420         }
421     }
422
423     if (types.contains(String(kUTTypeJPEG))) {
424         if (RefPtr<SharedBuffer> buffer = strategy.bufferForType(kUTTypeJPEG, m_pasteboardName)) {
425             if (reader.readImage(buffer.releaseNonNull(), ASCIILiteral("image/jpeg")))
426                 return;
427         }
428     }
429
430     if (types.contains(String(NSURLPboardType))) {
431         URL url = strategy.url(m_pasteboardName);
432         String title = strategy.stringForType(WebURLNamePboardType, m_pasteboardName);
433         if (!url.isNull() && reader.readURL(url, title))
434             return;
435     }
436
437     if (types.contains(String(NSStringPboardType))) {
438         String string = strategy.stringForType(NSStringPboardType, m_pasteboardName);
439         if (!string.isNull() && reader.readPlainText(string))
440             return;
441     }
442
443     if (types.contains(String(kUTTypeUTF8PlainText))) {
444         String string = strategy.stringForType(kUTTypeUTF8PlainText, m_pasteboardName);
445         if (!string.isNull() && reader.readPlainText(string))
446             return;
447     }
448 }
449
450 bool Pasteboard::hasData()
451 {
452     Vector<String> types;
453     platformStrategies()->pasteboardStrategy()->getTypes(types, m_pasteboardName);
454     return !types.isEmpty();
455 }
456
457 static String cocoaTypeFromHTMLClipboardType(const String& type)
458 {
459     // http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#dom-datatransfer-setdata
460     String lowercasedType = type.convertToASCIILowercase();
461
462     if (lowercasedType == "text")
463         lowercasedType = ASCIILiteral("text/plain");
464     if (lowercasedType == "url")
465         lowercasedType = ASCIILiteral("text/uri-list");
466
467     // Ignore any trailing charset - strings are already UTF-16, and the charset issue has already been dealt with.
468     if (lowercasedType == "text/plain" || lowercasedType.startsWith("text/plain;"))
469         return NSStringPboardType;
470     if (lowercasedType == "text/uri-list") {
471         // Special case because UTI doesn't work with Cocoa's URL type.
472         return NSURLPboardType;
473     }
474
475     // Blacklist types that might contain subframe information.
476     if (lowercasedType == "text/rtf" || lowercasedType == "public.rtf" || lowercasedType == "com.apple.traditional-mac-plain-text")
477         return String();
478
479     if (auto utiType = adoptCF(UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, lowercasedType.createCFString().get(), NULL))) {
480         if (auto pbType = adoptCF(UTTypeCopyPreferredTagWithClass(utiType.get(), kUTTagClassNSPboardType)))
481             return pbType.get();
482     }
483
484     // No mapping, just pass the whole string though
485     return lowercasedType;
486 }
487
488 void Pasteboard::clear(const String& type)
489 {
490     String cocoaType = cocoaTypeFromHTMLClipboardType(type);
491     if (cocoaType.isEmpty())
492         return;
493     m_changeCount = platformStrategies()->pasteboardStrategy()->setStringForType(emptyString(), cocoaType, m_pasteboardName);
494 }
495
496 static Vector<String> absoluteURLsFromPasteboardFilenames(const String& pasteboardName, bool onlyFirstURL = false)
497 {
498     Vector<String> fileList;
499     platformStrategies()->pasteboardStrategy()->getPathnamesForType(fileList, String(NSFilenamesPboardType), pasteboardName);
500
501     if (fileList.isEmpty())
502         return fileList;
503
504     size_t count = onlyFirstURL ? 1 : fileList.size();
505     Vector<String> urls;
506     for (size_t i = 0; i < count; i++) {
507         NSURL *url = [NSURL fileURLWithPath:fileList[i]];
508         urls.append(String([url absoluteString]));
509     }
510     return urls;
511 }
512
513 static Vector<String> absoluteURLsFromPasteboard(const String& pasteboardName, bool onlyFirstURL = false)
514 {
515     // NOTE: We must always check [availableTypes containsObject:] before accessing pasteboard data
516     // or CoreFoundation will printf when there is not data of the corresponding type.
517     Vector<String> availableTypes;
518     Vector<String> absoluteURLs;
519     platformStrategies()->pasteboardStrategy()->getTypes(availableTypes, pasteboardName);
520
521     // Try NSFilenamesPboardType because it contains a list
522     if (availableTypes.contains(String(NSFilenamesPboardType))) {
523         absoluteURLs = absoluteURLsFromPasteboardFilenames(pasteboardName, onlyFirstURL);
524         if (!absoluteURLs.isEmpty())
525             return absoluteURLs;
526     }
527
528     // Fallback to NSURLPboardType (which is a single URL)
529     if (availableTypes.contains(String(NSURLPboardType))) {
530         absoluteURLs.append(platformStrategies()->pasteboardStrategy()->stringForType(String(NSURLPboardType), pasteboardName));
531         return absoluteURLs;
532     }
533
534     // No file paths on the pasteboard, return nil
535     return Vector<String>();
536 }
537
538 String Pasteboard::readString(const String& type)
539 {
540     const String& cocoaType = cocoaTypeFromHTMLClipboardType(type);
541     String cocoaValue;
542
543     // Grab the value off the pasteboard corresponding to the cocoaType
544     if (cocoaType == String(NSURLPboardType)) {
545         // "url" and "text/url-list" both map to NSURLPboardType in cocoaTypeFromHTMLClipboardType(), "url" only wants the first URL
546         bool onlyFirstURL = equalLettersIgnoringASCIICase(type, "url");
547         Vector<String> absoluteURLs = absoluteURLsFromPasteboard(m_pasteboardName, onlyFirstURL);
548         for (size_t i = 0; i < absoluteURLs.size(); i++)
549             cocoaValue = i ? "\n" + absoluteURLs[i]: absoluteURLs[i];
550     } else if (cocoaType == String(NSStringPboardType))
551         cocoaValue = [platformStrategies()->pasteboardStrategy()->stringForType(cocoaType, m_pasteboardName) precomposedStringWithCanonicalMapping];
552     else if (!cocoaType.isEmpty())
553         cocoaValue = platformStrategies()->pasteboardStrategy()->stringForType(cocoaType, m_pasteboardName);
554
555     // Enforce changeCount ourselves for security.  We check after reading instead of before to be
556     // sure it doesn't change between our testing the change count and accessing the data.
557     if (!cocoaValue.isEmpty() && m_changeCount == platformStrategies()->pasteboardStrategy()->changeCount(m_pasteboardName))
558         return cocoaValue;
559
560     return String();
561 }
562
563 static String utiTypeFromCocoaType(const String& type)
564 {
565     if (RetainPtr<CFStringRef> utiType = adoptCF(UTTypeCreatePreferredIdentifierForTag(kUTTagClassNSPboardType, type.createCFString().get(), 0))) {
566         if (RetainPtr<CFStringRef> mimeType = adoptCF(UTTypeCopyPreferredTagWithClass(utiType.get(), kUTTagClassMIMEType)))
567             return String(mimeType.get());
568     }
569     return String();
570 }
571
572 static void addHTMLClipboardTypesForCocoaType(ListHashSet<String>& resultTypes, const String& cocoaType, const String& pasteboardName)
573 {
574     // UTI may not do these right, so make sure we get the right, predictable result
575     if (cocoaType == String(NSStringPboardType) || cocoaType == String(NSPasteboardTypeString)) {
576         resultTypes.add(ASCIILiteral("text/plain"));
577         return;
578     }
579     if (cocoaType == String(NSURLPboardType)) {
580         resultTypes.add(ASCIILiteral("text/uri-list"));
581         return;
582     }
583     if (cocoaType == String(NSFilenamesPboardType)) {
584         // If file list is empty, add nothing.
585         // Note that there is a chance that the file list count could have changed since we grabbed the types array.
586         // However, this is not really an issue for us doing a sanity check here.
587         Vector<String> fileList;
588         platformStrategies()->pasteboardStrategy()->getPathnamesForType(fileList, String(NSFilenamesPboardType), pasteboardName);
589         if (!fileList.isEmpty()) {
590             // It is unknown if NSFilenamesPboardType always implies NSURLPboardType in Cocoa,
591             // but NSFilenamesPboardType should imply both 'text/uri-list' and 'Files'
592             resultTypes.add(ASCIILiteral("text/uri-list"));
593             resultTypes.add(ASCIILiteral("Files"));
594         }
595         return;
596     }
597     String utiType = utiTypeFromCocoaType(cocoaType);
598     if (!utiType.isEmpty()) {
599         resultTypes.add(utiType);
600         return;
601     }
602     // No mapping, just pass the whole string through.
603     resultTypes.add(cocoaType);
604 }
605
606 void Pasteboard::writeString(const String& type, const String& data)
607 {
608     const String& cocoaType = cocoaTypeFromHTMLClipboardType(type);
609     String cocoaData = data;
610
611     if (cocoaType == String(NSURLPboardType) || cocoaType == String(kUTTypeFileURL)) {
612         NSURL *url = [NSURL URLWithString:cocoaData];
613         if ([url isFileURL])
614             return;
615
616         Vector<String> types;
617         types.append(cocoaType);
618         platformStrategies()->pasteboardStrategy()->setTypes(types, m_pasteboardName);
619         m_changeCount = platformStrategies()->pasteboardStrategy()->setStringForType(cocoaData, cocoaType, m_pasteboardName);
620
621         return;
622     }
623
624     if (!cocoaType.isEmpty()) {
625         // everything else we know of goes on the pboard as a string
626         Vector<String> types;
627         types.append(cocoaType);
628         platformStrategies()->pasteboardStrategy()->addTypes(types, m_pasteboardName);
629         m_changeCount = platformStrategies()->pasteboardStrategy()->setStringForType(cocoaData, cocoaType, m_pasteboardName);
630     }
631 }
632
633 Vector<String> Pasteboard::types()
634 {
635     Vector<String> types;
636     platformStrategies()->pasteboardStrategy()->getTypes(types, m_pasteboardName);
637
638     // Enforce changeCount ourselves for security. We check after reading instead of before to be
639     // sure it doesn't change between our testing the change count and accessing the data.
640     if (m_changeCount != platformStrategies()->pasteboardStrategy()->changeCount(m_pasteboardName))
641         return Vector<String>();
642
643     ListHashSet<String> result;
644     // FIXME: This loop could be split into two stages. One which adds all the HTML5 specified types
645     // and a second which adds all the extra types from the cocoa clipboard (which is Mac-only behavior).
646     for (size_t i = 0; i < types.size(); i++) {
647         if (types[i] == "NeXT plain ascii pasteboard type")
648             continue;   // skip this ancient type that gets auto-supplied by some system conversion
649
650         addHTMLClipboardTypesForCocoaType(result, types[i], m_pasteboardName);
651     }
652
653     copyToVector(result, types);
654     return types;
655 }
656
657 Vector<String> Pasteboard::readFilenames()
658 {
659     // FIXME: Seems silly to convert paths to URLs and then back to paths. Does that do anything helpful?
660     Vector<String> absoluteURLs = absoluteURLsFromPasteboardFilenames(m_pasteboardName);
661     Vector<String> paths;
662     paths.reserveCapacity(absoluteURLs.size());
663     for (size_t i = 0; i < absoluteURLs.size(); i++) {
664         NSURL *absoluteURL = [NSURL URLWithString:absoluteURLs[i]];
665         ASSERT([absoluteURL isFileURL]);
666         paths.uncheckedAppend([absoluteURL path]);
667     }
668     return paths;
669 }
670
671 #if ENABLE(DRAG_SUPPORT)
672 void Pasteboard::setDragImage(DragImage image, const IntPoint& location)
673 {
674     // Don't allow setting the drag image if someone kept a pasteboard and is trying to set the image too late.
675     if (m_changeCount != platformStrategies()->pasteboardStrategy()->changeCount(m_pasteboardName))
676         return;
677
678     // Dashboard wants to be able to set the drag image during dragging, but Cocoa does not allow this.
679     // Instead we must drop down to the CoreGraphics API.
680     wkSetDragImage(image.get().get(), location);
681
682     // Hack: We must post an event to wake up the NSDragManager, which is sitting in a nextEvent call
683     // up the stack from us because the CoreFoundation drag manager does not use the run loop by itself.
684     // This is the most innocuous event to use, per Kristen Forster.
685     NSEvent* event = [NSEvent mouseEventWithType:NSEventTypeMouseMoved location:NSZeroPoint
686         modifierFlags:0 timestamp:0 windowNumber:0 context:nil eventNumber:0 clickCount:0 pressure:0];
687     [NSApp postEvent:event atStart:YES];
688 }
689 #endif
690
691 }