1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
|
/*
* Copyright (C) 2007, 2008, 2012 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "config.h"
#import "Pasteboard.h"
#import "CachedImage.h"
#import "DOMRangeInternal.h"
#import "Document.h"
#import "DocumentFragment.h"
#import "DocumentLoader.h"
#import "Editor.h"
#import "EditorClient.h"
#import "Frame.h"
#import "FrameLoader.h"
#import "FrameLoaderClient.h"
#import "HTMLElement.h"
#import "HTMLNames.h"
#import "HTMLParserIdioms.h"
#import "KURL.h"
#import "LegacyWebArchive.h"
#import "Page.h"
#import "RenderImage.h"
#import "SoftLinking.h"
#import "Text.h"
#import "htmlediting.h"
#import "markup.h"
#import "WebNSAttributedStringExtras.h"
#import <MobileCoreServices/MobileCoreServices.h>
@interface NSHTMLReader
- (id)initWithDOMRange:(DOMRange *)domRange;
- (NSAttributedString *)attributedString;
@end
@interface NSAttributedString (NSAttributedStringKitAdditions)
- (id)initWithRTF:(NSData *)data documentAttributes:(NSDictionary **)dict;
- (id)initWithRTFD:(NSData *)data documentAttributes:(NSDictionary **)dict;
- (NSData *)RTFFromRange:(NSRange)range documentAttributes:(NSDictionary *)dict;
- (NSData *)RTFDFromRange:(NSRange)range documentAttributes:(NSDictionary *)dict;
- (BOOL)containsAttachments;
@end
SOFT_LINK_PRIVATE_FRAMEWORK(UIFoundation)
SOFT_LINK_CLASS(UIFoundation, NSHTMLReader)
SOFT_LINK_FRAMEWORK(MobileCoreServices)
SOFT_LINK(MobileCoreServices, UTTypeConformsTo, Boolean, (CFStringRef inUTI, CFStringRef inConformsToUTI), (inUTI, inConformsToUTI))
SOFT_LINK(MobileCoreServices, UTTypeCreatePreferredIdentifierForTag, CFStringRef, (CFStringRef inTagClass, CFStringRef inTag, CFStringRef inConformingToUTI), (inTagClass, inTag, inConformingToUTI))
SOFT_LINK(MobileCoreServices, UTTypeCopyPreferredTagWithClass, CFStringRef, (CFStringRef inUTI, CFStringRef inTagClass), (inUTI, inTagClass))
SOFT_LINK_CONSTANT(MobileCoreServices, kUTTypeText, CFStringRef)
SOFT_LINK_CONSTANT(MobileCoreServices, kUTTypePNG, CFStringRef)
SOFT_LINK_CONSTANT(MobileCoreServices, kUTTypeJPEG, CFStringRef)
SOFT_LINK_CONSTANT(MobileCoreServices, kUTTypeURL, CFStringRef)
SOFT_LINK_CONSTANT(MobileCoreServices, kUTTypeTIFF, CFStringRef)
SOFT_LINK_CONSTANT(MobileCoreServices, kUTTypeGIF, CFStringRef)
SOFT_LINK_CONSTANT(MobileCoreServices, kUTTagClassMIMEType, CFStringRef)
SOFT_LINK_CONSTANT(MobileCoreServices, kUTTagClassFilenameExtension, CFStringRef)
SOFT_LINK_CONSTANT(MobileCoreServices, kUTTypeRTFD, CFStringRef)
SOFT_LINK_CONSTANT(MobileCoreServices, kUTTypeRTF, CFStringRef)
#define kUTTypeText getkUTTypeText()
#define kUTTypePNG getkUTTypePNG()
#define kUTTypeJPEG getkUTTypeJPEG()
#define kUTTypeURL getkUTTypeURL()
#define kUTTypeTIFF getkUTTypeTIFF()
#define kUTTypeGIF getkUTTypeGIF()
#define kUTTagClassMIMEType getkUTTagClassMIMEType()
#define kUTTagClassFilenameExtension getkUTTagClassFilenameExtension()
#define kUTTypeRTFD getkUTTypeRTFD()
#define kUTTypeRTF getkUTTypeRTF()
SOFT_LINK_FRAMEWORK(AppSupport)
SOFT_LINK(AppSupport, CPSharedResourcesDirectory, CFStringRef, (void), ())
namespace WebCore {
NSString *WebArchivePboardType = @"Apple Web Archive pasteboard type";
Pasteboard* Pasteboard::generalPasteboard()
{
static Pasteboard* pasteboard = new Pasteboard();
return pasteboard;
}
Pasteboard::Pasteboard()
{
}
void Pasteboard::clear()
{
}
void Pasteboard::writeSelection(Range* selectedRange, bool /*canSmartCopyOrDelete*/, Frame *frame, ShouldSerializeSelectedTextForClipboard shouldSerializeSelectedTextForClipboard)
{
ASSERT(selectedRange);
ASSERT(frame);
// If the selection is at the beginning of content inside an anchor tag
// we move the selection start to include the anchor.
ExceptionCode ec;
Node* commonAncestor = selectedRange->commonAncestorContainer(ec);
ASSERT(commonAncestor);
Node* enclosingAnchor = enclosingNodeWithTag(firstPositionInNode(commonAncestor), HTMLNames::aTag);
if (enclosingAnchor && comparePositions(firstPositionInOrBeforeNode(selectedRange->startPosition().anchorNode()), selectedRange->startPosition()) >= 0)
selectedRange->setStart(enclosingAnchor, 0, ec);
frame->editor().client()->didSetSelectionTypesForPasteboard();
RetainPtr<NSDictionary> representations = adoptNS([[NSMutableDictionary alloc] init]);
// Put WebArchive on the pasteboard.
RefPtr<LegacyWebArchive> archive = LegacyWebArchive::createFromSelection(frame);
RetainPtr<CFDataRef> data = archive ? archive->rawDataRepresentation() : 0;
if (data)
[representations.get() setValue:(NSData *)data.get() forKey:WebArchivePboardType];
RetainPtr<NSHTMLReader> converter = adoptNS([[getNSHTMLReaderClass() alloc] initWithDOMRange:kit(selectedRange)]);
if (converter) {
NSAttributedString *attributedString = [converter.get() attributedString];
NSData* RTFDData = [attributedString RTFDFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil];
if (RTFDData)
[representations.get() setValue:RTFDData forKey:(NSString *)kUTTypeRTFD];
if ([attributedString containsAttachments])
attributedString = attributedStringByStrippingAttachmentCharacters(attributedString);
NSData* RTFData = [attributedString RTFFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil];
if (RTFData)
[representations.get() setValue:RTFData forKey:(NSString *)kUTTypeRTF];
}
// Put plain string on the pasteboard.
String text = shouldSerializeSelectedTextForClipboard == IncludeImageAltTextForClipboard
? frame->editor().selectedTextForClipboard() : frame->editor().selectedText();
text.replace(noBreakSpace, ' ');
[representations.get() setValue:text forKey:(NSString *)kUTTypeText];
frame->editor().client()->writeDataToPasteboard(representations.get());
}
void Pasteboard::writePlainText(const String& text, Frame *frame)
{
ASSERT(frame);
RetainPtr<NSDictionary> representations = adoptNS([[NSMutableDictionary alloc] init]);
[representations.get() setValue:text forKey:(NSString *)kUTTypeText];
frame->editor().client()->writeDataToPasteboard(representations.get());
}
void Pasteboard::writeImage(Node* node, Frame* frame)
{
ASSERT(node);
if (!(node->renderer() && node->renderer()->isImage()))
return;
RenderImage* renderer = toRenderImage(node->renderer());
CachedImage* cachedImage = renderer->cachedImage();
if (!cachedImage || cachedImage->errorOccurred())
return;
Image* image = cachedImage->imageForRenderer(renderer);
ASSERT(image);
RetainPtr<NSData> imageData = image->data()->createNSData();
if (!imageData)
return;
RetainPtr<NSMutableDictionary> dictionary = adoptNS([[NSMutableDictionary alloc] init]);
NSString *mimeType = cachedImage->response().mimeType();
RetainPtr<CFStringRef> uti = adoptCF(UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, (CFStringRef)mimeType, NULL));
if (uti) {
[dictionary.get() setObject:imageData.get() forKey:(NSString *)uti.get()];
[dictionary.get() setObject:(NSString *)node->document()->completeURL(stripLeadingAndTrailingHTMLSpaces(static_cast<HTMLElement*>(node)->getAttribute("src"))) forKey:(NSString *)kUTTypeURL];
}
frame->editor().client()->writeDataToPasteboard(dictionary.get());
}
void Pasteboard::writePlainText(const String&, SmartReplaceOption)
{
}
void Pasteboard::writeClipboard(Clipboard*)
{
}
bool Pasteboard::canSmartReplace()
{
return false;
}
String Pasteboard::plainText(Frame* frame)
{
RetainPtr<NSArray> pasteboardItem = frame->editor().client()->readDataFromPasteboard((NSString *)kUTTypeText, 0);
if ([pasteboardItem.get() count] == 0)
return String();
id value = [pasteboardItem.get() objectAtIndex:0];
if ([value isKindOfClass:[NSString class]])
return String(value);
ASSERT([value isKindOfClass:[NSString class]]);
return String();
}
static NSArray* supportedImageTypes()
{
return [NSArray arrayWithObjects:(id)kUTTypePNG, (id)kUTTypeTIFF, (id)kUTTypeJPEG, (id)kUTTypeGIF, nil];
}
NSArray* Pasteboard::supportedPasteboardTypes()
{
return [NSArray arrayWithObjects:(id)WebArchivePboardType, (id)kUTTypePNG, (id)kUTTypeTIFF, (id)kUTTypeJPEG, (id)kUTTypeGIF, (id)kUTTypeURL, (id)kUTTypeText, (id)kUTTypeRTFD, (id)kUTTypeRTF, nil];
}
#define WebDataProtocolScheme @"webkit-fake-url"
static NSURL* uniqueURLWithRelativePart(NSString *relativePart)
{
CFUUIDRef UUIDRef = CFUUIDCreate(kCFAllocatorDefault);
NSString *UUIDString = (NSString *)CFUUIDCreateString(kCFAllocatorDefault, UUIDRef);
CFRelease(UUIDRef);
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"%@://%@/%@", WebDataProtocolScheme, UUIDString, relativePart]];
CFRelease(UUIDString);
return URL;
}
static PassRefPtr<DocumentFragment> documentFragmentWithImageResource(Frame* frame, PassRefPtr<ArchiveResource> resource)
{
RefPtr<Element> imageElement = frame->document()->createElement(HTMLNames::imgTag, false);
if (DocumentLoader* loader = frame->loader()->documentLoader())
loader->addArchiveResource(resource.get());
NSURL *URL = resource->url();
imageElement->setAttribute(HTMLNames::srcAttr, [URL isFileURL] ? [URL absoluteString] : resource->url());
RefPtr<DocumentFragment> fragment = frame->document()->createDocumentFragment();
fragment->appendChild(imageElement.release());
return fragment.release();
}
static PassRefPtr<DocumentFragment> documentFragmentWithLink(Document* document, const String& urlString)
{
RefPtr<Element> anchorElement = document->createElement(HTMLNames::aTag, false);
anchorElement->setAttribute(HTMLNames::hrefAttr, urlString);
anchorElement->appendChild(document->createTextNode(urlString));
RefPtr<DocumentFragment> fragment = document->createDocumentFragment();
fragment->appendChild(anchorElement.release());
return fragment.release();
}
static PassRefPtr<DocumentFragment> documentFragmentWithRTF(Frame* frame, NSString *pasteboardType, NSData* pasteboardData)
{
if (!frame || !frame->document() || !frame->document()->isHTMLDocument())
return 0;
RetainPtr<NSAttributedString> string;
if ([pasteboardType isEqualToString:(NSString*)kUTTypeRTFD])
string = [[NSAttributedString alloc] initWithRTFD:pasteboardData documentAttributes:NULL];
if (!string)
string = [[NSAttributedString alloc] initWithRTF:pasteboardData documentAttributes:NULL];
if (!string)
return 0;
bool wasDeferringCallbacks = frame->page()->defersLoading();
if (!wasDeferringCallbacks)
frame->page()->setDefersLoading(true);
Vector<RefPtr<ArchiveResource> > resources;
RefPtr<DocumentFragment> fragment = frame->editor().client()->documentFragmentFromAttributedString(string.get(), resources);
size_t size = resources.size();
if (size) {
DocumentLoader* loader = frame->loader()->documentLoader();
for (size_t i = 0; i < size; ++i)
loader->addArchiveResource(resources[i]);
}
if (!wasDeferringCallbacks)
frame->page()->setDefersLoading(false);
return fragment.release();
}
PassRefPtr<DocumentFragment> Pasteboard::documentFragmentForPasteboardItemAtIndex(Frame* frame, int index, bool allowPlainText, bool& chosePlainText)
{
RefPtr<DocumentFragment> fragment = frame->editor().client()->documentFragmentFromDelegate(index);
if (fragment)
return fragment.release();
// First try to ask the client about the supported types. It will return null if the client
// has no selection.
NSArray *supportedTypes = frame->editor().client()->supportedPasteboardTypesForCurrentSelection();
if (!supportedTypes)
supportedTypes = supportedPasteboardTypes();
int numberOfTypes = [supportedTypes count];
for (int i = 0; i < numberOfTypes; i++) {
NSString *type = [supportedTypes objectAtIndex:i];
RetainPtr<NSArray> pasteboardItem = frame->editor().client()->readDataFromPasteboard(type, index);
if ([pasteboardItem.get() count] == 0)
continue;
if ([type isEqualToString:WebArchivePboardType]) {
if (!frame->document())
return 0;
// We put [WebArchive data] on the pasteboard in -copy: instead of the archive itself until there is API to provide the WebArchive.
NSData *data = [pasteboardItem.get() objectAtIndex:0];
RefPtr<LegacyWebArchive> coreArchive = LegacyWebArchive::create(SharedBuffer::wrapNSData(data).get());
if (coreArchive) {
RefPtr<ArchiveResource> mainResource = coreArchive->mainResource();
if (mainResource) {
NSString *MIMEType = mainResource->mimeType();
if (frame->loader()->client()->canShowMIMETypeAsHTML(MIMEType)) {
RetainPtr<NSString> markupString = adoptNS([[NSString alloc] initWithData:[mainResource->data()->createNSData() autorelease] encoding:NSUTF8StringEncoding]);
if (DocumentLoader* loader = frame->loader()->documentLoader())
loader->addAllArchiveResources(coreArchive.get());
fragment = createFragmentFromMarkup(frame->document(), markupString.get(), mainResource->url(), DisallowScriptingContent);
}
}
if (fragment)
return fragment.release();
}
}
if ([type isEqualToString:(NSString *)kUTTypeRTFD])
return documentFragmentWithRTF(frame, (NSString *)kUTTypeRTFD, [pasteboardItem.get() objectAtIndex:0]);
if ([type isEqualToString:(NSString *)kUTTypeRTF])
return documentFragmentWithRTF(frame, (NSString *)kUTTypeRTF, [pasteboardItem.get() objectAtIndex:0]);
if ([supportedImageTypes() containsObject:type]) {
RetainPtr<NSString> filenameExtension = adoptNS((NSString *)UTTypeCopyPreferredTagWithClass((CFStringRef)type, kUTTagClassFilenameExtension));
NSString *relativeURLPart = [@"image" stringByAppendingString:filenameExtension.get()];
RetainPtr<NSString> mimeType = adoptNS((NSString *)UTTypeCopyPreferredTagWithClass((CFStringRef)type, kUTTagClassMIMEType));
NSData *data = [pasteboardItem.get() objectAtIndex:0];
return documentFragmentWithImageResource(frame, ArchiveResource::create(SharedBuffer::wrapNSData([[data copy] autorelease]), uniqueURLWithRelativePart(relativeURLPart), mimeType.get(), "", ""));
}
if ([type isEqualToString:(NSString *)kUTTypeURL]) {
id value = [pasteboardItem.get() objectAtIndex:0];
if (![value isKindOfClass:[NSURL class]]) {
ASSERT([value isKindOfClass:[NSURL class]]);
return 0;
}
NSURL *url = (NSURL *)value;
if (!frame->editor().client()->hasRichlyEditableSelection()) {
fragment = createFragmentFromText(frame->selection()->toNormalizedRange().get(), [url absoluteString]);
if (fragment)
return fragment.release();
}
if ([url isFileURL]) {
NSString *localPath = [url relativePath];
// Only allow url attachments from ~/Media for now.
if (![localPath hasPrefix:[(NSString *)CPSharedResourcesDirectory() stringByAppendingString:@"/Media/DCIM/"]])
continue;
RetainPtr<NSString> fileType = adoptNS((NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (CFStringRef)[localPath pathExtension], NULL));
NSData *data = [NSData dataWithContentsOfFile:localPath];
if (UTTypeConformsTo((CFStringRef)fileType.get(), kUTTypePNG))
return documentFragmentWithImageResource(frame, ArchiveResource::create(SharedBuffer::wrapNSData([[data copy] autorelease]), uniqueURLWithRelativePart(@"image.png"), @"image/png", "", ""));
else if (UTTypeConformsTo((CFStringRef)fileType.get(), kUTTypeJPEG))
return documentFragmentWithImageResource(frame, ArchiveResource::create(SharedBuffer::wrapNSData([[data copy] autorelease]), uniqueURLWithRelativePart(@"image.jpg"), @"image/jpg", "", ""));
} else {
// Create a link with URL text.
return documentFragmentWithLink(frame->document(), [url absoluteString]);
}
}
if (allowPlainText && [type isEqualToString:(NSString *)kUTTypeText]) {
id value = [pasteboardItem.get() objectAtIndex:0];
if (![value isKindOfClass:[NSString class]]) {
ASSERT([value isKindOfClass:[NSString class]]);
return 0;
}
chosePlainText = true;
fragment = createFragmentFromText(frame->selection()->toNormalizedRange().get(), (NSString*)value);
if (fragment)
return fragment.release();
}
}
return 0;
}
PassRefPtr<DocumentFragment> Pasteboard::documentFragment(Frame* frame, PassRefPtr<Range> /*context*/, bool allowPlainText, bool& chosePlainText)
{
chosePlainText = false;
if (!frame)
return 0;
int numberOfItems = frame->editor().client()->getPasteboardItemsCount();
if (!numberOfItems)
return 0;
// In the common case there is just one item on the pasteboard, avoid the expense of transferring the content of
// fragmentForCurrentItem to the main fragment.
RefPtr<DocumentFragment> fragment = documentFragmentForPasteboardItemAtIndex(frame, 0, allowPlainText, chosePlainText);
for (int i = 1; i < numberOfItems; i++) {
RefPtr<DocumentFragment> fragmentForCurrentItem = documentFragmentForPasteboardItemAtIndex(frame, i, allowPlainText, chosePlainText);
if (!fragment)
fragment = fragmentForCurrentItem;
else if (fragmentForCurrentItem && fragmentForCurrentItem->firstChild()) {
ExceptionCode ec;
fragment->appendChild(fragmentForCurrentItem->firstChild(), ec);
}
}
if (fragment)
return fragment.release();
return 0;
}
}
|