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