2 * Copyright (C) 2006, 2007, 2013 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23 * THE POSSIBILITY OF SUCH DAMAGE.
29 #include "CachedImage.h"
30 #include "Clipboard.h"
31 #include "CSSComputedStyleDeclaration.h"
32 #include "CSSPrimitiveValueMappings.h"
33 #include "DOMRangeInternal.h"
34 #include "DocumentFragment.h"
35 #include "DocumentLoader.h"
36 #include "EditorClient.h"
39 #include "FrameLoaderClient.h"
40 #include "HTMLConverter.h"
41 #include "HTMLInputElement.h"
42 #include "HTMLNames.h"
43 #include "HTMLParserIdioms.h"
44 #include "HTMLTextAreaElement.h"
45 #include "LegacyWebArchive.h"
46 #include "NodeTraversal.h"
48 #include "Pasteboard.h"
49 #include "RenderBlock.h"
50 #include "RenderImage.h"
51 #include "SharedBuffer.h"
52 #include "SoftLinking.h"
53 #include "StyleProperties.h"
55 #include "TypingCommand.h"
56 #include "WAKAppKitStubs.h"
57 #include "htmlediting.h"
62 SOFT_LINK_FRAMEWORK(AppSupport)
63 SOFT_LINK(AppSupport, CPSharedResourcesDirectory, CFStringRef, (void), ())
65 SOFT_LINK_FRAMEWORK(MobileCoreServices)
67 SOFT_LINK(MobileCoreServices, UTTypeConformsTo, Boolean, (CFStringRef inUTI, CFStringRef inConformsToUTI), (inUTI, inConformsToUTI))
68 SOFT_LINK(MobileCoreServices, UTTypeCreatePreferredIdentifierForTag, CFStringRef, (CFStringRef inTagClass, CFStringRef inTag, CFStringRef inConformingToUTI), (inTagClass, inTag, inConformingToUTI))
69 SOFT_LINK(MobileCoreServices, UTTypeCopyPreferredTagWithClass, CFStringRef, (CFStringRef inUTI, CFStringRef inTagClass), (inUTI, inTagClass))
71 SOFT_LINK_CONSTANT(MobileCoreServices, kUTTypePNG, CFStringRef)
72 SOFT_LINK_CONSTANT(MobileCoreServices, kUTTypeJPEG, CFStringRef)
73 SOFT_LINK_CONSTANT(MobileCoreServices, kUTTagClassFilenameExtension, CFStringRef)
74 SOFT_LINK_CONSTANT(MobileCoreServices, kUTTagClassMIMEType, CFStringRef)
76 #define kUTTypePNG getkUTTypePNG()
77 #define kUTTypeJPEG getkUTTypeJPEG()
78 #define kUTTagClassFilenameExtension getkUTTagClassFilenameExtension()
79 #define kUTTagClassMIMEType getkUTTagClassMIMEType()
81 @interface NSAttributedString (NSAttributedStringKitAdditions)
82 - (id)initWithRTF:(NSData *)data documentAttributes:(NSDictionary **)dict;
83 - (id)initWithRTFD:(NSData *)data documentAttributes:(NSDictionary **)dict;
84 - (NSData *)RTFFromRange:(NSRange)range documentAttributes:(NSDictionary *)dict;
85 - (NSData *)RTFDFromRange:(NSRange)range documentAttributes:(NSDictionary *)dict;
86 - (BOOL)containsAttachments;
91 using namespace HTMLNames;
93 void Editor::showFontPanel()
97 void Editor::showStylesPanel()
101 void Editor::showColorPanel()
105 void Editor::setTextAlignmentForChangedBaseWritingDirection(WritingDirection direction)
107 // Note that the passed-in argument is the direction that has been changed to by
108 // some code or user interaction outside the scope of this function. The former
109 // direction is not known, nor is it required for the kind of text alignment
110 // changes done by this function.
113 // When text has no explicit alignment, set to alignment to match the writing direction.
114 // If the text has left or right alignment, flip left->right and right->left.
115 // Otherwise, do nothing.
117 RefPtr<EditingStyle> selectionStyle = EditingStyle::styleAtSelectionStart(m_frame.selection().selection());
118 if (!selectionStyle || !selectionStyle->style())
121 RefPtr<CSSPrimitiveValue> value = static_pointer_cast<CSSPrimitiveValue>(selectionStyle->style()->getPropertyCSSValue(CSSPropertyTextAlign));
125 const char *newValue = NULL;
126 ETextAlign textAlign = *value;
132 case NaturalWritingDirection:
135 case LeftToRightWritingDirection:
138 case RightToLeftWritingDirection:
162 Element* focusedElement = m_frame.document()->focusedElement();
163 if (focusedElement && (focusedElement->hasTagName(textareaTag) || (focusedElement->hasTagName(inputTag) &&
164 (toHTMLInputElement(focusedElement)->isTextField() ||
165 toHTMLInputElement(focusedElement)->isSearchField())))) {
166 if (direction == NaturalWritingDirection)
168 toHTMLElement(focusedElement)->setAttribute(alignAttr, newValue);
169 m_frame.document()->updateStyleIfNeeded();
173 RefPtr<MutableStyleProperties> style = MutableStyleProperties::create();
174 style->setProperty(CSSPropertyTextAlign, newValue);
175 applyParagraphStyle(style.get());
178 bool Editor::insertParagraphSeparatorInQuotedContent()
180 // FIXME: Why is this missing calls to canEdit, canEditRichly, etc...
181 TypingCommand::insertParagraphSeparatorInQuotedContent(*m_frame.document());
182 revealSelectionAfterEditingOperation();
186 // FIXME: Copied from EditorMac. This should be shared between the two so that
187 // the implementation does not differ.
188 static RenderStyle* styleForSelectionStart(Frame* frame, Node *&nodeToRemove)
192 if (frame->selection().isNone())
195 Position position = frame->selection().selection().visibleStart().deepEquivalent();
196 if (!position.isCandidate() || position.isNull())
199 RefPtr<EditingStyle> typingStyle = frame->selection().typingStyle();
200 if (!typingStyle || !typingStyle->style())
201 return &position.deprecatedNode()->renderer()->style();
203 RefPtr<Element> styleElement = frame->document()->createElement(spanTag, false);
205 String styleText = typingStyle->style()->asText() + " display: inline";
206 styleElement->setAttribute(styleAttr, styleText.impl());
208 ExceptionCode ec = 0;
209 styleElement->appendChild(frame->document()->createEditingTextNode(""), ec);
212 position.deprecatedNode()->parentNode()->appendChild(styleElement, ec);
215 nodeToRemove = styleElement.get();
216 return styleElement->renderer() ? &styleElement->renderer()->style() : 0;
219 const SimpleFontData* Editor::fontForSelection(bool& hasMultipleFonts) const
221 hasMultipleFonts = false;
223 if (!m_frame.selection().isRange()) {
225 RenderStyle* style = styleForSelectionStart(&m_frame, nodeToRemove); // sets nodeToRemove
227 const SimpleFontData* result = 0;
229 result = style->font().primaryFont();
233 nodeToRemove->remove(ec);
240 const SimpleFontData* font = 0;
241 RefPtr<Range> range = m_frame.selection().toNormalizedRange();
242 if (Node* startNode = adjustedSelectionStartForStyleComputation(m_frame.selection().selection()).deprecatedNode()) {
243 Node* pastEnd = range->pastLastNode();
244 // In the loop below, n should eventually match pastEnd and not become nil, but we've seen at least one
245 // unreproducible case where this didn't happen, so check for null also.
246 for (Node* node = startNode; node && node != pastEnd; node = NodeTraversal::next(node)) {
247 auto renderer = node->renderer();
250 // FIXME: Are there any node types that have renderers, but that we should be skipping?
251 const SimpleFontData* primaryFont = renderer->style().font().primaryFont();
254 else if (font != primaryFont) {
255 hasMultipleFonts = true;
264 NSDictionary* Editor::fontAttributesForSelectionStart() const
267 RenderStyle* style = styleForSelectionStart(&m_frame, nodeToRemove);
271 NSMutableDictionary* result = [NSMutableDictionary dictionary];
275 void Editor::removeUnchangeableStyles()
277 // This function removes styles that the user cannot modify by applying their default values.
279 RefPtr<EditingStyle> editingStyle = EditingStyle::create(m_frame.document()->body());
280 RefPtr<MutableStyleProperties> defaultStyle = editingStyle.get()->style()->mutableCopy();
282 // Text widgets implement background color via the UIView property. Their body element will not have one.
283 defaultStyle->setProperty(CSSPropertyBackgroundColor, "rgba(255, 255, 255, 0.0)");
285 // Remove properties that the user can modify, like font-weight.
286 // Also remove font-family, per HI spec.
287 // FIXME: it'd be nice if knowledge about which styles were unchangeable was not hard-coded here.
288 defaultStyle->removeProperty(CSSPropertyFontWeight);
289 defaultStyle->removeProperty(CSSPropertyFontStyle);
290 defaultStyle->removeProperty(CSSPropertyFontVariant);
291 // FIXME: we should handle also pasted quoted text, strikethrough, etc. <rdar://problem/9255115>
292 defaultStyle->removeProperty(CSSPropertyTextDecoration);
293 defaultStyle->removeProperty(CSSPropertyWebkitTextDecorationsInEffect); // implements underline
295 // FIXME add EditActionMatchStlye <rdar://problem/9156507> Undo rich text's paste & match style should say "Undo Match Style"
296 applyStyleToSelection(defaultStyle.get(), EditActionChangeAttributes);
299 // FIXME: the following fuctions should be shared between Mac and iOS.
300 static NSAttributedString *attributedStringForRange(Range& range)
302 return [adoptNS([[WebHTMLConverter alloc] initWithDOMRange:kit(&range)]) attributedString];
305 static PassRefPtr<SharedBuffer> dataInRTFDFormat(NSAttributedString *string)
307 NSUInteger length = [string length];
308 return length ? SharedBuffer::wrapNSData([string RTFDFromRange:NSMakeRange(0, length) documentAttributes:nil]) : nullptr;
311 static PassRefPtr<SharedBuffer> dataInRTFFormat(NSAttributedString *string)
313 NSUInteger length = [string length];
314 return length ? SharedBuffer::wrapNSData([string RTFFromRange:NSMakeRange(0, length) documentAttributes:nil]) : nullptr;
317 String Editor::stringSelectionForPasteboardWithImageAltText()
319 String text = selectedTextForClipboard();
320 text.replace(noBreakSpace, ' ');
324 PassRefPtr<SharedBuffer> Editor::selectionInWebArchiveFormat()
326 RefPtr<LegacyWebArchive> archive = LegacyWebArchive::createFromSelection(&m_frame);
327 return archive ? SharedBuffer::wrapCFData(archive->rawDataRepresentation().get()) : nullptr;
330 void Editor::writeSelectionToPasteboard(Pasteboard& pasteboard)
332 NSAttributedString *attributedString = attributedStringForRange(*selectedRange());
334 PasteboardWebContent content;
335 content.canSmartCopyOrDelete = canSmartCopyOrDelete();
336 content.dataInWebArchiveFormat = selectionInWebArchiveFormat();
337 content.dataInRTFDFormat = [attributedString containsAttachments] ? dataInRTFDFormat(attributedString) : 0;
338 content.dataInRTFFormat = dataInRTFFormat(attributedString);
339 content.dataInStringFormat = stringSelectionForPasteboardWithImageAltText();
340 client()->getClientPasteboardDataForRange(selectedRange().get(), content.clientTypes, content.clientData);
342 pasteboard.write(content);
345 static void getImage(Element& imageElement, RefPtr<Image>& image, CachedImage*& cachedImage)
347 auto renderer = imageElement.renderer();
348 if (!renderer || !renderer->isImage())
351 CachedImage* tentativeCachedImage = toRenderImage(renderer)->cachedImage();
352 if (!tentativeCachedImage || tentativeCachedImage->errorOccurred()) {
353 tentativeCachedImage = 0;
357 image = tentativeCachedImage->imageForRenderer(renderer);
361 cachedImage = tentativeCachedImage;
364 void Editor::writeImageToPasteboard(Pasteboard& pasteboard, Element& imageElement, const URL&, const String& title)
366 PasteboardImage pasteboardImage;
368 CachedImage* cachedImage;
369 getImage(imageElement, pasteboardImage.image, cachedImage);
370 if (!pasteboardImage.image)
374 pasteboardImage.url.url = imageElement.document().completeURL(stripLeadingAndTrailingHTMLSpaces(imageElement.imageSourceURL()));
375 pasteboardImage.url.title = title;
376 pasteboardImage.resourceMIMEType = pasteboard.resourceMIMEType(cachedImage->response().mimeType());
378 pasteboard.write(pasteboardImage);
381 class Editor::WebContentReader FINAL : public PasteboardWebContentReader {
383 WebContentReader(Frame& frame, Range& context, bool allowPlainText)
386 , allowPlainText(allowPlainText)
387 , madeFragmentFromPlainText(false)
393 const bool allowPlainText;
395 RefPtr<DocumentFragment> fragment;
396 bool madeFragmentFromPlainText;
399 virtual bool readWebArchive(PassRefPtr<SharedBuffer>) OVERRIDE;
400 virtual bool readFilenames(const Vector<String>&) OVERRIDE;
401 virtual bool readHTML(const String&) OVERRIDE;
402 virtual bool readRTFD(PassRefPtr<SharedBuffer>) OVERRIDE;
403 virtual bool readRTF(PassRefPtr<SharedBuffer>) OVERRIDE;
404 virtual bool readImage(PassRefPtr<SharedBuffer>, const String& type) OVERRIDE;
405 virtual bool readURL(const URL&, const String& title) OVERRIDE;
406 virtual bool readPlainText(const String&) OVERRIDE;
407 void addFragment(PassRefPtr<DocumentFragment>);
410 void Editor::WebContentReader::addFragment(PassRefPtr<DocumentFragment> newFragment)
413 if (newFragment && newFragment->firstChild()) {
415 fragment->appendChild(newFragment->firstChild(), ec);
418 fragment = newFragment;
421 bool Editor::WebContentReader::readWebArchive(PassRefPtr<SharedBuffer> buffer)
423 if (!frame.document())
426 RefPtr<LegacyWebArchive> archive = LegacyWebArchive::create(URL(), buffer.get());
430 RefPtr<ArchiveResource> mainResource = archive->mainResource();
434 const String& type = mainResource->mimeType();
436 if (frame.loader().client().canShowMIMETypeAsHTML(type)) {
437 // FIXME: The code in createFragmentAndAddResources calls setDefersLoading(true). Don't we need that here?
438 if (DocumentLoader* loader = frame.loader().documentLoader())
439 loader->addAllArchiveResources(archive.get());
441 String markupString = String::fromUTF8(mainResource->data()->data(), mainResource->data()->size());
442 addFragment(createFragmentFromMarkup(*frame.document(), markupString, mainResource->url(), DisallowScriptingAndPluginContent));
449 bool Editor::WebContentReader::readFilenames(const Vector<String>&)
454 bool Editor::WebContentReader::readHTML(const String&)
459 bool Editor::WebContentReader::readRTFD(PassRefPtr<SharedBuffer> buffer)
461 addFragment(frame.editor().createFragmentAndAddResources(adoptNS([[NSAttributedString alloc] initWithRTFD:buffer->createNSData().get() documentAttributes:nullptr]).get()));
465 bool Editor::WebContentReader::readRTF(PassRefPtr<SharedBuffer> buffer)
467 addFragment(frame.editor().createFragmentAndAddResources(adoptNS([[NSAttributedString alloc] initWithRTF:buffer->createNSData().get() documentAttributes:nullptr]).get()));
471 static NSURL* uniqueURLWithRelativePart(NSString *relativePart)
473 RetainPtr<CFUUIDRef> UUIDRef = adoptCF(CFUUIDCreate(kCFAllocatorDefault));
474 RetainPtr<NSString> UUIDString = adoptNS((NSString *)CFUUIDCreateString(kCFAllocatorDefault, UUIDRef.get()));
476 return [NSURL URLWithString:[NSString stringWithFormat:@"%@://%@/%@", @"webkit-fake-url", UUIDString.get(), relativePart]];
479 bool Editor::WebContentReader::readImage(PassRefPtr<SharedBuffer> buffer, const String& type)
481 RetainPtr<CFStringRef> stringType = type.createCFString();
482 RetainPtr<NSString> filenameExtension = adoptNS((NSString *)UTTypeCopyPreferredTagWithClass(stringType.get(), kUTTagClassFilenameExtension));
483 NSString *relativeURLPart = [@"image" stringByAppendingString:filenameExtension.get()];
484 RetainPtr<NSString> mimeType = adoptNS((NSString *)UTTypeCopyPreferredTagWithClass(stringType.get(), kUTTagClassMIMEType));
486 addFragment(frame.editor().createFragmentForImageResourceAndAddResource(ArchiveResource::create(buffer, uniqueURLWithRelativePart(relativeURLPart), mimeType.get(), emptyString(), emptyString())));
490 bool Editor::WebContentReader::readURL(const URL& url, const String&)
495 if (!frame.editor().client()->hasRichlyEditableSelection()) {
496 if (readPlainText([(NSURL *)url absoluteString]))
500 if ([(NSURL *)url isFileURL]) {
501 NSString *localPath = [(NSURL *)url relativePath];
502 // Only allow url attachments from ~/Media for now.
503 if (![localPath hasPrefix:[(NSString *)CPSharedResourcesDirectory() stringByAppendingString:@"/Media/DCIM/"]])
506 RetainPtr<NSString> fileType = adoptNS((NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (CFStringRef)[localPath pathExtension], NULL));
507 NSData *data = [NSData dataWithContentsOfFile:localPath];
508 if (UTTypeConformsTo((CFStringRef)fileType.get(), kUTTypePNG)) {
509 addFragment(frame.editor().createFragmentForImageResourceAndAddResource(ArchiveResource::create(SharedBuffer::wrapNSData([[data copy] autorelease]), uniqueURLWithRelativePart(@"image.png"), @"image/png", emptyString(), emptyString())));
511 } else if (UTTypeConformsTo((CFStringRef)fileType.get(), kUTTypeJPEG)) {
512 addFragment(frame.editor().createFragmentForImageResourceAndAddResource(ArchiveResource::create(SharedBuffer::wrapNSData([[data copy] autorelease]), uniqueURLWithRelativePart(@"image.jpg"), @"image/jpg", emptyString(), emptyString())));
516 RefPtr<Element> anchor = frame.document()->createElement(HTMLNames::aTag, false);
517 anchor->setAttribute(HTMLNames::hrefAttr, url.string());
518 anchor->appendChild(frame.document()->createTextNode([[(NSURL *)url absoluteString] precomposedStringWithCanonicalMapping]));
520 RefPtr<DocumentFragment> newFragment = frame.document()->createDocumentFragment();
521 newFragment->appendChild(anchor.release());
522 addFragment(newFragment);
528 bool Editor::WebContentReader::readPlainText(const String& text)
533 addFragment(createFragmentFromText(context, [text precomposedStringWithCanonicalMapping]));
537 madeFragmentFromPlainText = true;
541 // FIXME: Should give this function a name that makes it clear it adds resources to the document loader as a side effect.
542 // Or refactor so it does not do that.
543 PassRefPtr<DocumentFragment> Editor::webContentFromPasteboard(Pasteboard& pasteboard, Range& context, bool allowPlainText, bool& chosePlainText)
545 WebContentReader reader(m_frame, context, allowPlainText);
546 pasteboard.read(reader);
547 chosePlainText = reader.madeFragmentFromPlainText;
548 return reader.fragment.release();
551 void Editor::pasteWithPasteboard(Pasteboard* pasteboard, bool allowPlainText)
553 RefPtr<Range> range = selectedRange();
556 RefPtr<DocumentFragment> fragment = client()->documentFragmentFromDelegate(0);
558 fragment = webContentFromPasteboard(*pasteboard, *range, allowPlainText, chosePlainText);
560 if (fragment && shouldInsertFragment(fragment, range, EditorInsertActionPasted))
561 pasteAsFragment(fragment, canSmartReplaceWithPasteboard(*pasteboard), false);
564 PassRefPtr<DocumentFragment> Editor::createFragmentAndAddResources(NSAttributedString *string)
566 if (!m_frame.page() || !m_frame.document() || !m_frame.document()->isHTMLDocument())
572 bool wasDeferringCallbacks = m_frame.page()->defersLoading();
573 if (!wasDeferringCallbacks)
574 m_frame.page()->setDefersLoading(true);
576 Vector<RefPtr<ArchiveResource>> resources;
577 RefPtr<DocumentFragment> fragment = client()->documentFragmentFromAttributedString(string, resources);
579 if (DocumentLoader* loader = m_frame.loader().documentLoader()) {
580 for (size_t i = 0, size = resources.size(); i < size; ++i)
581 loader->addArchiveResource(resources[i]);
584 if (!wasDeferringCallbacks)
585 m_frame.page()->setDefersLoading(false);
587 return fragment.release();
590 PassRefPtr<DocumentFragment> Editor::createFragmentForImageResourceAndAddResource(PassRefPtr<ArchiveResource> resource)
595 RefPtr<Element> imageElement = m_frame.document()->createElement(HTMLNames::imgTag, false);
596 // FIXME: The code in createFragmentAndAddResources calls setDefersLoading(true). Don't we need that here?
597 if (DocumentLoader* loader = m_frame.loader().documentLoader())
598 loader->addArchiveResource(resource.get());
600 NSURL *URL = resource->url();
601 imageElement->setAttribute(HTMLNames::srcAttr, [URL isFileURL] ? [URL absoluteString] : resource->url());
603 RefPtr<DocumentFragment> fragment = m_frame.document()->createDocumentFragment();
604 fragment->appendChild(imageElement.release());
606 return fragment.release();
609 } // namespace WebCore
611 #endif // PLATFORM(IOS)