[Mac] Teach WebCore::Pasteboard about file promise drags
[WebKit-https.git] / Source / WebCore / platform / mac / PasteboardMac.mm
1 /*
2  * Copyright (C) 2006-2018 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 #if PLATFORM(MAC)
30
31 #import "DragData.h"
32 #import "Image.h"
33 #import "LegacyNSPasteboardTypes.h"
34 #import "LoaderNSURLExtras.h"
35 #import "MIMETypeRegistry.h"
36 #import "PasteboardStrategy.h"
37 #import "PlatformPasteboard.h"
38 #import "PlatformStrategies.h"
39 #import "SharedBuffer.h"
40 #import "URL.h"
41 #import "UTIUtilities.h"
42 #import "WebNSAttributedStringExtras.h"
43 #import <pal/spi/cg/CoreGraphicsSPI.h>
44 #import <pal/spi/mac/HIServicesSPI.h>
45 #import <wtf/RetainPtr.h>
46 #import <wtf/StdLibExtras.h>
47 #import <wtf/text/StringBuilder.h>
48 #import <wtf/unicode/CharacterNames.h>
49
50 namespace WebCore {
51
52 const char* const WebArchivePboardType = "Apple Web Archive pasteboard type";
53 const char* const WebURLNamePboardType = "public.url-name";
54
55 const char WebSmartPastePboardType[] = "NeXT smart paste pasteboard type";
56 const char WebURLPboardType[] = "public.url";
57 const char WebURLsWithTitlesPboardType[] = "WebURLsWithTitlesPboardType";
58
59 static const Vector<String> writableTypesForURL()
60 {
61     Vector<String> types;
62     
63     types.append(WebURLsWithTitlesPboardType);
64     types.append(String(legacyURLPasteboardType()));
65     types.append(WebURLPboardType);
66     types.append(WebURLNamePboardType);
67     types.append(String(legacyStringPasteboardType()));
68     return types;
69 }
70
71 static Vector<String> writableTypesForImage()
72 {
73     Vector<String> types;
74     types.append(String(legacyTIFFPasteboardType()));
75     types.appendVector(writableTypesForURL());
76     types.append(String(legacyRTFDPasteboardType()));
77     return types;
78 }
79
80 NSArray *Pasteboard::supportedFileUploadPasteboardTypes()
81 {
82     return @[ (NSString *)legacyFilesPromisePasteboardType(), (NSString *)legacyFilenamesPasteboardType() ];
83 }
84
85 Pasteboard::Pasteboard()
86     : m_pasteboardName(emptyString())
87     , m_changeCount(0)
88 {
89 }
90
91 Pasteboard::Pasteboard(const String& pasteboardName, const Vector<String>& promisedFilePaths)
92     : m_pasteboardName(pasteboardName)
93     , m_changeCount(platformStrategies()->pasteboardStrategy()->changeCount(m_pasteboardName))
94     , m_promisedFilePaths(promisedFilePaths)
95 {
96     ASSERT(pasteboardName);
97 }
98
99 std::unique_ptr<Pasteboard> Pasteboard::createForCopyAndPaste()
100 {
101 #pragma clang diagnostic push
102 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
103     return std::make_unique<Pasteboard>(NSGeneralPboard);
104 #pragma clang diagnostic pop
105 }
106
107 #if ENABLE(DRAG_SUPPORT)
108 std::unique_ptr<Pasteboard> Pasteboard::createForDragAndDrop()
109 {
110 #pragma clang diagnostic push
111 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
112     return std::make_unique<Pasteboard>(NSDragPboard);
113 #pragma clang diagnostic pop
114 }
115
116 std::unique_ptr<Pasteboard> Pasteboard::createForDragAndDrop(const DragData& dragData)
117 {
118     return std::make_unique<Pasteboard>(dragData.pasteboardName(), dragData.fileNames());
119 }
120 #endif
121
122 void Pasteboard::clear()
123 {
124     m_changeCount = platformStrategies()->pasteboardStrategy()->setTypes(Vector<String>(), m_pasteboardName);
125 }
126
127 void Pasteboard::write(const PasteboardWebContent& content)
128 {
129     Vector<String> types;
130
131     if (content.canSmartCopyOrDelete)
132         types.append(WebSmartPastePboardType);
133     if (content.dataInWebArchiveFormat)
134         types.append(WebArchivePboardType);
135     if (content.dataInRTFDFormat)
136         types.append(String(legacyRTFDPasteboardType()));
137     if (content.dataInRTFFormat)
138         types.append(String(legacyRTFPasteboardType()));
139     if (!content.dataInHTMLFormat.isNull())
140         types.append(String(legacyHTMLPasteboardType()));
141     if (!content.dataInStringFormat.isNull())
142         types.append(String(legacyStringPasteboardType()));
143     types.appendVector(content.clientTypes);
144     types.append(PasteboardCustomData::cocoaType());
145
146     m_changeCount = platformStrategies()->pasteboardStrategy()->setTypes(types, m_pasteboardName);
147
148     ASSERT(content.clientTypes.size() == content.clientData.size());
149     for (size_t i = 0, size = content.clientTypes.size(); i < size; ++i)
150         m_changeCount = platformStrategies()->pasteboardStrategy()->setBufferForType(content.clientData[i].get(), content.clientTypes[i], m_pasteboardName);
151     if (content.canSmartCopyOrDelete)
152         m_changeCount = platformStrategies()->pasteboardStrategy()->setBufferForType(nullptr, WebSmartPastePboardType, m_pasteboardName);
153     if (content.dataInWebArchiveFormat)
154         m_changeCount = platformStrategies()->pasteboardStrategy()->setBufferForType(content.dataInWebArchiveFormat.get(), WebArchivePboardType, m_pasteboardName);
155     if (content.dataInRTFDFormat)
156         m_changeCount = platformStrategies()->pasteboardStrategy()->setBufferForType(content.dataInRTFDFormat.get(), legacyRTFDPasteboardType(), m_pasteboardName);
157     if (content.dataInRTFFormat)
158         m_changeCount = platformStrategies()->pasteboardStrategy()->setBufferForType(content.dataInRTFFormat.get(), legacyRTFPasteboardType(), m_pasteboardName);
159     if (!content.dataInHTMLFormat.isNull())
160         m_changeCount = platformStrategies()->pasteboardStrategy()->setStringForType(content.dataInHTMLFormat, legacyHTMLPasteboardType(), m_pasteboardName);
161     if (!content.dataInStringFormat.isNull())
162         m_changeCount = platformStrategies()->pasteboardStrategy()->setStringForType(content.dataInStringFormat, legacyStringPasteboardType(), m_pasteboardName);
163
164     PasteboardCustomData data;
165     data.origin = content.contentOrigin;
166     m_changeCount = platformStrategies()->pasteboardStrategy()->setBufferForType(data.createSharedBuffer().ptr(), PasteboardCustomData::cocoaType(), m_pasteboardName);
167
168 }
169
170 void Pasteboard::writePlainText(const String& text, SmartReplaceOption smartReplaceOption)
171 {
172     Vector<String> types;
173     types.append(legacyStringPasteboardType());
174     if (smartReplaceOption == CanSmartReplace)
175         types.append(WebSmartPastePboardType);
176
177     platformStrategies()->pasteboardStrategy()->setTypes(types, m_pasteboardName);
178     m_changeCount = platformStrategies()->pasteboardStrategy()->setStringForType(text, legacyStringPasteboardType(), m_pasteboardName);
179     if (smartReplaceOption == CanSmartReplace)
180         m_changeCount = platformStrategies()->pasteboardStrategy()->setBufferForType(0, WebSmartPastePboardType, m_pasteboardName);
181 }
182
183 static long writeURLForTypes(const Vector<String>& types, const String& pasteboardName, const PasteboardURL& pasteboardURL)
184 {
185     long newChangeCount = platformStrategies()->pasteboardStrategy()->setTypes(types, pasteboardName);
186     
187     ASSERT(!pasteboardURL.url.isEmpty());
188     
189     NSURL *cocoaURL = pasteboardURL.url;
190     NSString *userVisibleString = pasteboardURL.userVisibleForm;
191     NSString *title = (NSString *)pasteboardURL.title;
192     if (![title length]) {
193         title = [[cocoaURL path] lastPathComponent];
194         if (![title length])
195             title = userVisibleString;
196     }
197
198     if (types.contains(WebURLsWithTitlesPboardType)) {
199         Vector<String> paths;
200         paths.append([cocoaURL absoluteString]);
201         paths.append(pasteboardURL.title.stripWhiteSpace());
202         newChangeCount = platformStrategies()->pasteboardStrategy()->setPathnamesForType(paths, WebURLsWithTitlesPboardType, pasteboardName);
203     }
204     if (types.contains(String(legacyURLPasteboardType())))
205         newChangeCount = platformStrategies()->pasteboardStrategy()->setStringForType([cocoaURL absoluteString], legacyURLPasteboardType(), pasteboardName);
206     if (types.contains(WebURLPboardType))
207         newChangeCount = platformStrategies()->pasteboardStrategy()->setStringForType(userVisibleString, WebURLPboardType, pasteboardName);
208     if (types.contains(WebURLNamePboardType))
209         newChangeCount = platformStrategies()->pasteboardStrategy()->setStringForType(title, WebURLNamePboardType, pasteboardName);
210     if (types.contains(String(legacyStringPasteboardType())))
211         newChangeCount = platformStrategies()->pasteboardStrategy()->setStringForType(userVisibleString, legacyStringPasteboardType(), pasteboardName);
212
213     return newChangeCount;
214 }
215     
216 void Pasteboard::write(const PasteboardURL& pasteboardURL)
217 {
218     m_changeCount = writeURLForTypes(writableTypesForURL(), m_pasteboardName, pasteboardURL);
219 }
220
221 void Pasteboard::writeTrustworthyWebURLsPboardType(const PasteboardURL& pasteboardURL)
222 {
223     NSURL *cocoaURL = pasteboardURL.url;
224     Vector<String> paths = { [cocoaURL absoluteString], pasteboardURL.title.stripWhiteSpace() };
225     m_changeCount = platformStrategies()->pasteboardStrategy()->setPathnamesForType(paths, WebURLsWithTitlesPboardType, m_pasteboardName);
226 }
227
228 static NSFileWrapper* fileWrapper(const PasteboardImage& pasteboardImage)
229 {
230     NSFileWrapper *wrapper = [[[NSFileWrapper alloc] initRegularFileWithContents:pasteboardImage.resourceData->createNSData().get()] autorelease];
231     [wrapper setPreferredFilename:suggestedFilenameWithMIMEType(pasteboardImage.url.url, pasteboardImage.resourceMIMEType)];
232     return wrapper;
233 }
234
235 static void writeFileWrapperAsRTFDAttachment(NSFileWrapper *wrapper, const String& pasteboardName, long& newChangeCount)
236 {
237     NSTextAttachment *attachment = [[NSTextAttachment alloc] initWithFileWrapper:wrapper];
238     NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attachment];
239     [attachment release];
240
241     NSData *RTFDData = [string RTFDFromRange:NSMakeRange(0, [string length]) documentAttributes:@{ }];
242     if (!RTFDData)
243         return;
244
245     newChangeCount = platformStrategies()->pasteboardStrategy()->setBufferForType(SharedBuffer::create(RTFDData).ptr(), legacyRTFDPasteboardType(), pasteboardName);
246 }
247
248 void Pasteboard::write(const PasteboardImage& pasteboardImage)
249 {
250     CFDataRef imageData = pasteboardImage.image->tiffRepresentation();
251     if (!imageData)
252         return;
253
254     // FIXME: Why can we assert this? It doesn't seem like it's guaranteed.
255     ASSERT(MIMETypeRegistry::isSupportedImageResourceMIMEType(pasteboardImage.resourceMIMEType));
256
257     auto types = writableTypesForImage();
258     if (pasteboardImage.dataInWebArchiveFormat)
259         types.append(WebArchivePboardType);
260
261     m_changeCount = writeURLForTypes(types, m_pasteboardName, pasteboardImage.url);
262     m_changeCount = platformStrategies()->pasteboardStrategy()->setBufferForType(SharedBuffer::create(imageData).ptr(), legacyTIFFPasteboardType(), m_pasteboardName);
263     if (pasteboardImage.dataInWebArchiveFormat)
264         m_changeCount = platformStrategies()->pasteboardStrategy()->setBufferForType(pasteboardImage.dataInWebArchiveFormat.get(), WebArchivePboardType, m_pasteboardName);
265     writeFileWrapperAsRTFDAttachment(fileWrapper(pasteboardImage), m_pasteboardName, m_changeCount);
266 }
267
268 bool Pasteboard::canSmartReplace()
269 {
270     Vector<String> types;
271     platformStrategies()->pasteboardStrategy()->getTypes(types, m_pasteboardName);
272     return types.contains(WebSmartPastePboardType);
273 }
274
275 void Pasteboard::writeMarkup(const String&)
276 {
277 }
278
279 // FIXME: This should be a general utility function for Vectors of Strings (or things that can be
280 // converted to Strings). It could also be faster by computing the total length and reserving that
281 // capacity in the StringBuilder.
282 static String joinPathnames(const Vector<String>& pathnames)
283 {
284     StringBuilder builder;
285     for (auto& path : pathnames) {
286         if (!builder.isEmpty())
287             builder.append('\n');
288         builder.append(path);
289     }
290     return builder.toString();
291 }
292
293 void Pasteboard::read(PasteboardPlainText& text)
294 {
295     PasteboardStrategy& strategy = *platformStrategies()->pasteboardStrategy();
296
297     Vector<String> types;
298     strategy.getTypes(types, m_pasteboardName);
299
300     if (types.contains(String(NSPasteboardTypeString))) {
301         text.text = strategy.stringForType(NSPasteboardTypeString, m_pasteboardName);
302         text.isURL = false;
303         return;
304     }
305
306     if (types.contains(String(legacyStringPasteboardType()))) {
307         text.text = strategy.stringForType(legacyStringPasteboardType(), m_pasteboardName);
308         text.isURL = false;
309         return;
310     }
311     
312     if (types.contains(String(legacyRTFDPasteboardType()))) {
313         if (RefPtr<SharedBuffer> data = strategy.bufferForType(legacyRTFDPasteboardType(), m_pasteboardName)) {
314             if (auto attributedString = adoptNS([[NSAttributedString alloc] initWithRTFD: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(legacyRTFPasteboardType()))) {
323         if (RefPtr<SharedBuffer> data = strategy.bufferForType(legacyRTFPasteboardType(), m_pasteboardName)) {
324             if (auto attributedString = adoptNS([[NSAttributedString alloc] initWithRTF: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(legacyFilenamesPasteboardType()))) {
333         Vector<String> pathnames;
334         strategy.getPathnamesForType(pathnames, legacyFilenamesPasteboardType(), m_pasteboardName);
335         text.text = joinPathnames(pathnames);
336         text.isURL = false;
337         return;
338     }
339
340     if (types.contains(String(legacyFilesPromisePasteboardType()))) {
341         text.text = joinPathnames(m_promisedFilePaths);
342         text.isURL = false;
343         return;
344     }
345
346     // FIXME: The code above looks at the types vector first, but this just gets the string without checking. Why the difference?
347     text.text = strategy.stringForType(legacyURLPasteboardType(), m_pasteboardName);
348     text.isURL = !text.text.isNull();
349 }
350
351 void Pasteboard::read(PasteboardWebContentReader& reader, WebContentReadingPolicy policy)
352 {
353     PasteboardStrategy& strategy = *platformStrategies()->pasteboardStrategy();
354
355     Vector<String> types;
356     strategy.getTypes(types, m_pasteboardName);
357
358     reader.contentOrigin = readOrigin();
359
360     if (types.contains(WebArchivePboardType)) {
361         if (auto buffer = strategy.bufferForType(WebArchivePboardType, m_pasteboardName)) {
362             if (m_changeCount != changeCount() || reader.readWebArchive(*buffer))
363                 return;
364         }
365     }
366
367     if (policy == WebContentReadingPolicy::AnyType && types.contains(String(legacyFilenamesPasteboardType()))) {
368         Vector<String> paths;
369         strategy.getPathnamesForType(paths, legacyFilenamesPasteboardType(), m_pasteboardName);
370         if (m_changeCount != changeCount() || reader.readFilePaths(paths))
371             return;
372     }
373
374     if (policy == WebContentReadingPolicy::AnyType && types.contains(String(legacyFilesPromisePasteboardType()))) {
375         if (m_changeCount != changeCount() || reader.readFilePaths(m_promisedFilePaths))
376             return;
377     }
378
379     if (types.contains(String(legacyHTMLPasteboardType()))) {
380         String string = strategy.stringForType(legacyHTMLPasteboardType(), m_pasteboardName);
381         if (m_changeCount != changeCount() || (!string.isNull() && reader.readHTML(string)))
382             return;
383     }
384
385     if (types.contains(String(legacyRTFDPasteboardType()))) {
386         if (RefPtr<SharedBuffer> buffer = strategy.bufferForType(legacyRTFDPasteboardType(), m_pasteboardName)) {
387             if (m_changeCount != changeCount() || reader.readRTFD(*buffer))
388                 return;
389         }
390     }
391
392     if (types.contains(String(legacyRTFPasteboardType()))) {
393         if (RefPtr<SharedBuffer> buffer = strategy.bufferForType(legacyRTFPasteboardType(), m_pasteboardName)) {
394             if (m_changeCount != changeCount() || reader.readRTF(*buffer))
395                 return;
396         }
397     }
398
399     if (policy == WebContentReadingPolicy::OnlyRichTextTypes)
400         return;
401
402     if (types.contains(String(legacyTIFFPasteboardType()))) {
403         if (RefPtr<SharedBuffer> buffer = strategy.bufferForType(legacyTIFFPasteboardType(), m_pasteboardName)) {
404             if (m_changeCount != changeCount() || reader.readImage(buffer.releaseNonNull(), ASCIILiteral("image/tiff")))
405                 return;
406         }
407     }
408
409     if (types.contains(String(legacyPDFPasteboardType()))) {
410         if (RefPtr<SharedBuffer> buffer = strategy.bufferForType(legacyPDFPasteboardType(), m_pasteboardName)) {
411             if (m_changeCount != changeCount() || 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 (m_changeCount != changeCount() || 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 (m_changeCount != changeCount() || reader.readImage(buffer.releaseNonNull(), ASCIILiteral("image/jpeg")))
426                 return;
427         }
428     }
429
430     if (types.contains(String(legacyURLPasteboardType()))) {
431         URL url = strategy.url(m_pasteboardName);
432         String title = strategy.stringForType(WebURLNamePboardType, m_pasteboardName);
433         if (m_changeCount != changeCount() || (!url.isNull() && reader.readURL(url, title)))
434             return;
435     }
436
437     if (types.contains(String(legacyStringPasteboardType()))) {
438         String string = strategy.stringForType(legacyStringPasteboardType(), m_pasteboardName);
439         if (m_changeCount != changeCount() || (!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 (m_changeCount != changeCount() || (!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     if (NSString *platformType = PlatformPasteboard::platformPasteboardTypeForSafeTypeForDOMToReadAndWrite(type)) {
460         if (platformType.length)
461             return platformType;
462     }
463
464     // Blacklist types that might contain subframe information.
465     if (type == "text/rtf" || type == "public.rtf" || type == "com.apple.traditional-mac-plain-text")
466         return String();
467
468     auto utiType = UTIFromMIMEType(type);
469     if (!utiType.isEmpty()) {
470         if (auto pbType = adoptCF(UTTypeCopyPreferredTagWithClass(utiType.createCFString().get(), kUTTagClassNSPboardType)))
471             return pbType.get();
472     }
473
474     // No mapping, just pass the whole string though
475     return type;
476 }
477
478 void Pasteboard::clear(const String& type)
479 {
480     String cocoaType = cocoaTypeFromHTMLClipboardType(type);
481     if (cocoaType.isEmpty())
482         return;
483     m_changeCount = platformStrategies()->pasteboardStrategy()->setStringForType(emptyString(), cocoaType, m_pasteboardName);
484 }
485
486 String Pasteboard::readPlatformValueAsString(const String& domType, long changeCount, const String& pasteboardName)
487 {
488     const String& cocoaType = cocoaTypeFromHTMLClipboardType(domType);
489     String cocoaValue;
490
491     if (cocoaType == String(legacyStringPasteboardType()))
492         cocoaValue = [platformStrategies()->pasteboardStrategy()->stringForType(cocoaType, pasteboardName) precomposedStringWithCanonicalMapping];
493     else if (!cocoaType.isEmpty())
494         cocoaValue = platformStrategies()->pasteboardStrategy()->stringForType(cocoaType, pasteboardName);
495
496     // Enforce changeCount ourselves for security.  We check after reading instead of before to be
497     // sure it doesn't change between our testing the change count and accessing the data.
498     if (!cocoaValue.isEmpty() && changeCount == platformStrategies()->pasteboardStrategy()->changeCount(pasteboardName))
499         return cocoaValue;
500
501     return String();
502 }
503
504 static String utiTypeFromCocoaType(const String& type)
505 {
506     if (RetainPtr<CFStringRef> utiType = adoptCF(UTTypeCreatePreferredIdentifierForTag(kUTTagClassNSPboardType, type.createCFString().get(), 0))) {
507         if (RetainPtr<CFStringRef> mimeType = adoptCF(UTTypeCopyPreferredTagWithClass(utiType.get(), kUTTagClassMIMEType)))
508             return String(mimeType.get());
509     }
510     return String();
511 }
512
513 void Pasteboard::addHTMLClipboardTypesForCocoaType(ListHashSet<String>& resultTypes, const String& cocoaType)
514 {
515     if (cocoaType == "NeXT plain ascii pasteboard type")
516         return; // Skip this ancient type that gets auto-supplied by some system conversion.
517
518     // UTI may not do these right, so make sure we get the right, predictable result
519     if (cocoaType == String(legacyStringPasteboardType()) || cocoaType == String(NSPasteboardTypeString)) {
520         resultTypes.add(ASCIILiteral("text/plain"));
521         return;
522     }
523     if (cocoaType == String(legacyURLPasteboardType())) {
524         resultTypes.add(ASCIILiteral("text/uri-list"));
525         return;
526     }
527     if (cocoaType == String(legacyFilenamesPasteboardType()) || Pasteboard::shouldTreatCocoaTypeAsFile(cocoaType))
528         return;
529     String utiType = utiTypeFromCocoaType(cocoaType);
530     if (!utiType.isEmpty()) {
531         resultTypes.add(utiType);
532         return;
533     }
534     // No mapping, just pass the whole string through.
535     resultTypes.add(cocoaType);
536 }
537
538 void Pasteboard::writeString(const String& type, const String& data)
539 {
540     const String& cocoaType = cocoaTypeFromHTMLClipboardType(type);
541     String cocoaData = data;
542
543     if (cocoaType == String(legacyURLPasteboardType()) || cocoaType == String(kUTTypeFileURL)) {
544         NSURL *url = [NSURL URLWithString:cocoaData];
545         if ([url isFileURL])
546             return;
547
548         Vector<String> types;
549         types.append(cocoaType);
550         platformStrategies()->pasteboardStrategy()->setTypes(types, m_pasteboardName);
551         m_changeCount = platformStrategies()->pasteboardStrategy()->setStringForType(cocoaData, cocoaType, m_pasteboardName);
552
553         return;
554     }
555
556     if (!cocoaType.isEmpty()) {
557         // everything else we know of goes on the pboard as a string
558         Vector<String> types;
559         types.append(cocoaType);
560         platformStrategies()->pasteboardStrategy()->addTypes(types, m_pasteboardName);
561         m_changeCount = platformStrategies()->pasteboardStrategy()->setStringForType(cocoaData, cocoaType, m_pasteboardName);
562     }
563 }
564
565 Vector<String> Pasteboard::readFilePaths()
566 {
567     auto& strategy = *platformStrategies()->pasteboardStrategy();
568
569     Vector<String> types;
570     strategy.getTypes(types, m_pasteboardName);
571
572     if (types.contains(String(legacyFilenamesPasteboardType()))) {
573         Vector<String> filePaths;
574         strategy.getPathnamesForType(filePaths, legacyFilenamesPasteboardType(), m_pasteboardName);
575         return filePaths;
576     }
577
578     if (types.contains(String(legacyFilesPromisePasteboardType())))
579         return m_promisedFilePaths;
580     
581     return { };
582 }
583
584 #if ENABLE(DRAG_SUPPORT)
585 static void flipImageSpec(CoreDragImageSpec* imageSpec)
586 {
587     unsigned char* tempRow = (unsigned char*)fastMalloc(imageSpec->bytesPerRow);
588     int planes = imageSpec->isPlanar ? imageSpec->samplesPerPixel : 1;
589
590     for (int p = 0; p < planes; ++p) {
591         unsigned char* topRow = const_cast<unsigned char*>(imageSpec->data[p]);
592         unsigned char* botRow = topRow + (imageSpec->pixelsHigh - 1) * imageSpec->bytesPerRow;
593         for (int i = 0; i < imageSpec->pixelsHigh / 2; ++i, topRow += imageSpec->bytesPerRow, botRow -= imageSpec->bytesPerRow) {
594             bcopy(topRow, tempRow, imageSpec->bytesPerRow);
595             bcopy(botRow, topRow, imageSpec->bytesPerRow);
596             bcopy(tempRow, botRow, imageSpec->bytesPerRow);
597         }
598     }
599
600     fastFree(tempRow);
601 }
602
603 static void setDragImageImpl(NSImage *image, NSPoint offset)
604 {
605     bool flipImage;
606     NSSize imageSize = image.size;
607     CGRect imageRect = CGRectMake(0, 0, imageSize.width, imageSize.height);
608     NSImageRep *imageRep = [image bestRepresentationForRect:NSRectFromCGRect(imageRect) context:nil hints:nil];
609     RetainPtr<NSBitmapImageRep> bitmapImage;
610     if (!imageRep || ![imageRep isKindOfClass:[NSBitmapImageRep class]] || !NSEqualSizes(imageRep.size, imageSize)) {
611         [image lockFocus];
612 #pragma clang diagnostic push
613 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
614         bitmapImage = adoptNS([[NSBitmapImageRep alloc] initWithFocusedViewRect:*(NSRect*)&imageRect]);
615 #pragma clang diagnostic pop
616         [image unlockFocus];
617         
618         // we may have to flip the bits we just read if the image was flipped since it means the cache was also
619         // and CoreDragSetImage can't take a transform for rendering.
620 #pragma clang diagnostic push
621 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
622         flipImage = image.isFlipped;
623 #pragma clang diagnostic pop
624     } else {
625         flipImage = false;
626         bitmapImage = (NSBitmapImageRep *)imageRep;
627     }
628     ASSERT(bitmapImage);
629
630     CoreDragImageSpec imageSpec;
631     imageSpec.version = kCoreDragImageSpecVersionOne;
632     imageSpec.pixelsWide = [bitmapImage pixelsWide];
633     imageSpec.pixelsHigh = [bitmapImage pixelsHigh];
634     imageSpec.bitsPerSample = [bitmapImage bitsPerSample];
635     imageSpec.samplesPerPixel = [bitmapImage samplesPerPixel];
636     imageSpec.bitsPerPixel = [bitmapImage bitsPerPixel];
637     imageSpec.bytesPerRow = [bitmapImage bytesPerRow];
638     imageSpec.isPlanar = [bitmapImage isPlanar];
639     imageSpec.hasAlpha = [bitmapImage hasAlpha];
640     [bitmapImage getBitmapDataPlanes:const_cast<unsigned char**>(imageSpec.data)];
641
642     // if image was flipped, we have an upside down bitmap since the cache is rendered flipped
643     if (flipImage)
644         flipImageSpec(&imageSpec);
645
646     CGSRegionObj imageShape;
647     OSStatus error = CGSNewRegionWithRect(&imageRect, &imageShape);
648     ASSERT(error == kCGErrorSuccess);
649     if (error != kCGErrorSuccess)
650         return;
651
652     // make sure image has integer offset
653     CGPoint imageOffset = { -offset.x, -(imageSize.height - offset.y) };
654     imageOffset.x = floor(imageOffset.x + 0.5);
655     imageOffset.y = floor(imageOffset.y + 0.5);
656
657     error = CoreDragSetImage(CoreDragGetCurrentDrag(), imageOffset, &imageSpec, imageShape, 1.0);
658     CGSReleaseRegion(imageShape);
659     ASSERT(error == kCGErrorSuccess);
660 }
661
662 void Pasteboard::setDragImage(DragImage image, const IntPoint& location)
663 {
664     // Don't allow setting the drag image if someone kept a pasteboard and is trying to set the image too late.
665     if (m_changeCount != platformStrategies()->pasteboardStrategy()->changeCount(m_pasteboardName))
666         return;
667
668     // Dashboard wants to be able to set the drag image during dragging, but Cocoa does not allow this.
669     // Instead we must drop down to the CoreGraphics API.
670     setDragImageImpl(image.get().get(), location);
671
672     // Hack: We must post an event to wake up the NSDragManager, which is sitting in a nextEvent call
673     // up the stack from us because the CoreFoundation drag manager does not use the run loop by itself.
674     // This is the most innocuous event to use, per Kristin Forster.
675     // This is only relevant in WK1. Do not execute in the WebContent process, since it is now using
676     // NSRunLoop, and not the NSApplication run loop.
677     if ([NSApp isRunning]) {
678         NSEvent* event = [NSEvent mouseEventWithType:NSEventTypeMouseMoved location:NSZeroPoint
679             modifierFlags:0 timestamp:0 windowNumber:0 context:nil eventNumber:0 clickCount:0 pressure:0];
680         [NSApp postEvent:event atStart:YES];
681     }
682 }
683 #endif
684
685 }
686
687 #endif // PLATFORM(MAC)