2 * Copyright (C) 2006, 2007, 2008, 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 COMPUTER, 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 COMPUTER, 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.
29 #import "CachedResourceLoader.h"
32 #import "DOMRangeInternal.h"
33 #import "DocumentFragment.h"
34 #import "DocumentLoader.h"
36 #import "EditorClient.h"
39 #import "FrameLoaderClient.h"
41 #import "HTMLConverter.h"
42 #import "HTMLElement.h"
44 #import "LegacyWebArchive.h"
45 #import "MIMETypeRegistry.h"
46 #import "NodeTraversal.h"
48 #import "Pasteboard.h"
49 #import "PasteboardStrategy.h"
50 #import "PlatformStrategies.h"
52 #import "RenderBlock.h"
53 #import "RenderImage.h"
54 #import "ResourceBuffer.h"
55 #import "RuntimeApplicationChecks.h"
57 #import "StyleProperties.h"
59 #import "TypingCommand.h"
61 #import "WebNSAttributedStringExtras.h"
62 #import "htmlediting.h"
67 using namespace HTMLNames;
69 void Editor::showFontPanel()
71 [[NSFontManager sharedFontManager] orderFrontFontPanel:nil];
74 void Editor::showStylesPanel()
76 [[NSFontManager sharedFontManager] orderFrontStylesPanel:nil];
79 void Editor::showColorPanel()
81 [[NSApplication sharedApplication] orderFrontColorPanel:nil];
84 void Editor::pasteWithPasteboard(Pasteboard* pasteboard, bool allowPlainText)
86 RefPtr<Range> range = selectedRange();
88 // FIXME: How can this hard-coded pasteboard name be right, given that the passed-in pasteboard has a name?
89 client()->setInsertionPasteboard(NSGeneralPboard);
92 RefPtr<DocumentFragment> fragment = webContentFromPasteboard(*pasteboard, *range, allowPlainText, chosePlainText);
94 if (fragment && shouldInsertFragment(fragment, range, EditorInsertActionPasted))
95 pasteAsFragment(fragment, canSmartReplaceWithPasteboard(*pasteboard), false);
97 client()->setInsertionPasteboard(String());
100 bool Editor::insertParagraphSeparatorInQuotedContent()
102 // FIXME: Why is this missing calls to canEdit, canEditRichly, etc.?
103 TypingCommand::insertParagraphSeparatorInQuotedContent(document());
104 revealSelectionAfterEditingOperation();
108 static RenderStyle* styleForSelectionStart(Frame* frame, Node *&nodeToRemove)
112 if (frame->selection().isNone())
115 Position position = frame->selection().selection().visibleStart().deepEquivalent();
116 if (!position.isCandidate() || position.isNull())
119 RefPtr<EditingStyle> typingStyle = frame->selection().typingStyle();
120 if (!typingStyle || !typingStyle->style())
121 return &position.deprecatedNode()->renderer()->style();
123 RefPtr<Element> styleElement = frame->document()->createElement(spanTag, false);
125 String styleText = typingStyle->style()->asText() + " display: inline";
126 styleElement->setAttribute(styleAttr, styleText);
128 styleElement->appendChild(frame->document()->createEditingTextNode(""), ASSERT_NO_EXCEPTION);
130 position.deprecatedNode()->parentNode()->appendChild(styleElement, ASSERT_NO_EXCEPTION);
132 nodeToRemove = styleElement.get();
133 return styleElement->renderer() ? &styleElement->renderer()->style() : 0;
136 const SimpleFontData* Editor::fontForSelection(bool& hasMultipleFonts) const
138 hasMultipleFonts = false;
140 if (!m_frame.selection().isRange()) {
142 RenderStyle* style = styleForSelectionStart(&m_frame, nodeToRemove); // sets nodeToRemove
144 const SimpleFontData* result = 0;
146 result = style->font().primaryFont();
149 nodeToRemove->remove(ASSERT_NO_EXCEPTION);
154 const SimpleFontData* font = 0;
155 RefPtr<Range> range = m_frame.selection().toNormalizedRange();
156 Node* startNode = adjustedSelectionStartForStyleComputation(m_frame.selection().selection()).deprecatedNode();
157 if (range && startNode) {
158 Node* pastEnd = range->pastLastNode();
159 // In the loop below, n should eventually match pastEnd and not become nil, but we've seen at least one
160 // unreproducible case where this didn't happen, so check for null also.
161 for (Node* node = startNode; node && node != pastEnd; node = NodeTraversal::next(node)) {
162 auto renderer = node->renderer();
165 // FIXME: Are there any node types that have renderers, but that we should be skipping?
166 const SimpleFontData* primaryFont = renderer->style().font().primaryFont();
169 else if (font != primaryFont) {
170 hasMultipleFonts = true;
179 NSDictionary* Editor::fontAttributesForSelectionStart() const
182 RenderStyle* style = styleForSelectionStart(&m_frame, nodeToRemove);
186 NSMutableDictionary* result = [NSMutableDictionary dictionary];
188 if (style->visitedDependentColor(CSSPropertyBackgroundColor).isValid() && style->visitedDependentColor(CSSPropertyBackgroundColor).alpha() != 0)
189 [result setObject:nsColor(style->visitedDependentColor(CSSPropertyBackgroundColor)) forKey:NSBackgroundColorAttributeName];
191 if (style->font().primaryFont()->getNSFont())
192 [result setObject:style->font().primaryFont()->getNSFont() forKey:NSFontAttributeName];
194 if (style->visitedDependentColor(CSSPropertyColor).isValid() && style->visitedDependentColor(CSSPropertyColor) != Color::black)
195 [result setObject:nsColor(style->visitedDependentColor(CSSPropertyColor)) forKey:NSForegroundColorAttributeName];
197 const ShadowData* shadow = style->textShadow();
199 RetainPtr<NSShadow> s = adoptNS([[NSShadow alloc] init]);
200 [s.get() setShadowOffset:NSMakeSize(shadow->x(), shadow->y())];
201 [s.get() setShadowBlurRadius:shadow->radius()];
202 [s.get() setShadowColor:nsColor(shadow->color())];
203 [result setObject:s.get() forKey:NSShadowAttributeName];
206 int decoration = style->textDecorationsInEffect();
207 if (decoration & TextDecorationLineThrough)
208 [result setObject:[NSNumber numberWithInt:NSUnderlineStyleSingle] forKey:NSStrikethroughStyleAttributeName];
210 int superscriptInt = 0;
211 switch (style->verticalAlign()) {
214 case BASELINE_MIDDLE:
229 [result setObject:[NSNumber numberWithInt:superscriptInt] forKey:NSSuperscriptAttributeName];
231 if (decoration & TextDecorationUnderline)
232 [result setObject:[NSNumber numberWithInt:NSUnderlineStyleSingle] forKey:NSUnderlineStyleAttributeName];
235 nodeToRemove->remove(ASSERT_NO_EXCEPTION);
240 bool Editor::canCopyExcludingStandaloneImages()
242 FrameSelection& selection = m_frame.selection();
243 return selection.isRange() && !selection.isInPasswordField();
246 void Editor::takeFindStringFromSelection()
248 if (!canCopyExcludingStandaloneImages()) {
253 Vector<String> types;
254 types.append(String(NSStringPboardType));
255 platformStrategies()->pasteboardStrategy()->setTypes(types, NSFindPboard);
256 platformStrategies()->pasteboardStrategy()->setStringForType(m_frame.displayStringModifiedByEncoding(selectedTextForClipboard()), NSStringPboardType, NSFindPboard);
259 void Editor::readSelectionFromPasteboard(const String& pasteboardName)
261 Pasteboard pasteboard(pasteboardName);
262 if (m_frame.selection().isContentRichlyEditable())
263 pasteWithPasteboard(&pasteboard, true);
265 pasteAsPlainTextWithPasteboard(pasteboard);
268 // FIXME: Makes no sense that selectedTextForClipboard always includes alt text, but stringSelectionForPasteboard does not.
269 // This was left in a bad state when selectedTextForClipboard was added. Need to look over clients and fix this.
270 String Editor::stringSelectionForPasteboard()
272 String text = selectedText();
273 text.replace(noBreakSpace, ' ');
277 String Editor::stringSelectionForPasteboardWithImageAltText()
279 String text = selectedTextForClipboard();
280 text.replace(noBreakSpace, ' ');
284 PassRefPtr<SharedBuffer> Editor::selectionInWebArchiveFormat()
286 RefPtr<LegacyWebArchive> archive = LegacyWebArchive::createFromSelection(&m_frame);
287 return archive ? SharedBuffer::wrapCFData(archive->rawDataRepresentation().get()) : 0;
290 PassRefPtr<Range> Editor::adjustedSelectionRange()
292 // FIXME: Why do we need to adjust the selection to include the anchor tag it's in?
293 // Whoever wrote this code originally forgot to leave us a comment explaining the rationale.
294 RefPtr<Range> range = selectedRange();
295 Node* commonAncestor = range->commonAncestorContainer(IGNORE_EXCEPTION);
296 ASSERT(commonAncestor);
297 Node* enclosingAnchor = enclosingNodeWithTag(firstPositionInNode(commonAncestor), HTMLNames::aTag);
298 if (enclosingAnchor && comparePositions(firstPositionInOrBeforeNode(range->startPosition().anchorNode()), range->startPosition()) >= 0)
299 range->setStart(enclosingAnchor, 0, IGNORE_EXCEPTION);
303 static NSAttributedString *attributedStringForRange(Range& range)
305 return [adoptNS([[WebHTMLConverter alloc] initWithDOMRange:kit(&range)]) attributedString];
308 static PassRefPtr<SharedBuffer> dataInRTFDFormat(NSAttributedString *string)
310 NSUInteger length = [string length];
311 return length ? SharedBuffer::wrapNSData([string RTFDFromRange:NSMakeRange(0, length) documentAttributes:nil]) : 0;
314 static PassRefPtr<SharedBuffer> dataInRTFFormat(NSAttributedString *string)
316 NSUInteger length = [string length];
317 return length ? SharedBuffer::wrapNSData([string RTFFromRange:NSMakeRange(0, length) documentAttributes:nil]) : 0;
320 PassRefPtr<SharedBuffer> Editor::dataSelectionForPasteboard(const String& pasteboardType)
322 // FIXME: The interface to this function is awkward. We'd probably be better off with three separate functions.
323 // As of this writing, this is only used in WebKit2 to implement the method -[WKView writeSelectionToPasteboard:types:],
324 // which is only used to support OS X services.
326 // FIXME: Does this function really need to use adjustedSelectionRange()? Because writeSelectionToPasteboard() just uses selectedRange().
328 if (pasteboardType == WebArchivePboardType)
329 return selectionInWebArchiveFormat();
331 if (pasteboardType == String(NSRTFDPboardType))
332 return dataInRTFDFormat(attributedStringForRange(*adjustedSelectionRange()));
334 if (pasteboardType == String(NSRTFPboardType)) {
335 NSAttributedString* attributedString = attributedStringForRange(*adjustedSelectionRange());
336 // FIXME: Why is this attachment character stripping needed here, but not needed in writeSelectionToPasteboard?
337 if ([attributedString containsAttachments])
338 attributedString = attributedStringByStrippingAttachmentCharacters(attributedString);
339 return dataInRTFFormat(attributedString);
345 void Editor::writeSelectionToPasteboard(Pasteboard& pasteboard)
347 NSAttributedString *attributedString = attributedStringForRange(*selectedRange());
349 PasteboardWebContent content;
350 content.canSmartCopyOrDelete = canSmartCopyOrDelete();
351 content.dataInWebArchiveFormat = selectionInWebArchiveFormat();
352 content.dataInRTFDFormat = [attributedString containsAttachments] ? dataInRTFDFormat(attributedString) : 0;
353 content.dataInRTFFormat = dataInRTFFormat(attributedString);
354 content.dataInStringFormat = stringSelectionForPasteboardWithImageAltText();
355 client()->getClientPasteboardDataForRange(selectedRange().get(), content.clientTypes, content.clientData);
357 pasteboard.write(content);
360 static void getImage(Element& imageElement, RefPtr<Image>& image, CachedImage*& cachedImage)
362 auto renderer = imageElement.renderer();
363 if (!renderer || !renderer->isImage())
366 CachedImage* tentativeCachedImage = toRenderImage(renderer)->cachedImage();
367 if (!tentativeCachedImage || tentativeCachedImage->errorOccurred()) {
368 tentativeCachedImage = 0;
372 image = tentativeCachedImage->imageForRenderer(renderer);
376 cachedImage = tentativeCachedImage;
379 void Editor::fillInUserVisibleForm(PasteboardURL& pasteboardURL)
381 pasteboardURL.userVisibleForm = client()->userVisibleString(pasteboardURL.url);
384 String Editor::plainTextFromPasteboard(const PasteboardPlainText& text)
386 String string = text.text;
388 // FIXME: It's not clear this is 100% correct since we know -[NSURL URLWithString:] does not handle
389 // all the same cases we handle well in the URL code for creating an NSURL.
391 string = client()->userVisibleString([NSURL URLWithString:string]);
393 // FIXME: WTF should offer a non-Mac-specific way to convert string to precomposed form so we can do it for all platforms.
394 return [(NSString *)string precomposedStringWithCanonicalMapping];
397 void Editor::writeImageToPasteboard(Pasteboard& pasteboard, Element& imageElement, const URL& url, const String& title)
399 PasteboardImage pasteboardImage;
401 CachedImage* cachedImage;
402 getImage(imageElement, pasteboardImage.image, cachedImage);
403 if (!pasteboardImage.image)
407 pasteboardImage.url.url = url;
408 pasteboardImage.url.title = title;
409 pasteboardImage.url.userVisibleForm = client()->userVisibleString(pasteboardImage.url.url);
410 pasteboardImage.resourceData = cachedImage->resourceBuffer()->sharedBuffer();
411 pasteboardImage.resourceMIMEType = cachedImage->response().mimeType();
413 pasteboard.write(pasteboardImage);
416 class Editor::WebContentReader FINAL : public PasteboardWebContentReader {
420 const bool allowPlainText;
422 RefPtr<DocumentFragment> fragment;
423 bool madeFragmentFromPlainText;
425 WebContentReader(Frame& frame, Range& context, bool allowPlainText)
428 , allowPlainText(allowPlainText)
429 , madeFragmentFromPlainText(false)
434 virtual bool readWebArchive(PassRefPtr<SharedBuffer>) override;
435 virtual bool readFilenames(const Vector<String>&) override;
436 virtual bool readHTML(const String&) override;
437 virtual bool readRTFD(PassRefPtr<SharedBuffer>) override;
438 virtual bool readRTF(PassRefPtr<SharedBuffer>) override;
439 virtual bool readImage(PassRefPtr<SharedBuffer>, const String& type) override;
440 virtual bool readURL(const URL&, const String& title) override;
441 virtual bool readPlainText(const String&) override;
444 bool Editor::WebContentReader::readWebArchive(PassRefPtr<SharedBuffer> buffer)
446 if (!frame.document())
449 RefPtr<LegacyWebArchive> archive = LegacyWebArchive::create(URL(), buffer.get());
453 RefPtr<ArchiveResource> mainResource = archive->mainResource();
457 const String& type = mainResource->mimeType();
459 if (frame.loader().client().canShowMIMETypeAsHTML(type)) {
460 // FIXME: The code in createFragmentAndAddResources calls setDefersLoading(true). Don't we need that here?
461 if (DocumentLoader* loader = frame.loader().documentLoader())
462 loader->addAllArchiveResources(archive.get());
464 String markupString = String::fromUTF8(mainResource->data()->data(), mainResource->data()->size());
465 fragment = createFragmentFromMarkup(*frame.document(), markupString, mainResource->url(), DisallowScriptingAndPluginContent);
469 if (MIMETypeRegistry::isSupportedImageMIMEType(type)) {
470 fragment = frame.editor().createFragmentForImageResourceAndAddResource(mainResource.release());
477 bool Editor::WebContentReader::readFilenames(const Vector<String>& paths)
479 size_t size = paths.size();
483 if (!frame.document())
485 Document& document = *frame.document();
487 fragment = document.createDocumentFragment();
489 for (size_t i = 0; i < size; i++) {
490 String text = paths[i];
491 text = frame.editor().client()->userVisibleString([NSURL fileURLWithPath:text]);
493 RefPtr<HTMLElement> paragraph = createDefaultParagraphElement(document);
494 paragraph->appendChild(document.createTextNode(text));
495 fragment->appendChild(paragraph.release());
501 bool Editor::WebContentReader::readHTML(const String& string)
503 String stringOmittingMicrosoftPrefix = string;
505 // This code was added to make HTML paste from Microsoft Word on Mac work, back in 2004.
506 // It's a simple-minded way to ignore the CF_HTML clipboard format, just skipping over the
507 // description part and parsing the entire context plus fragment.
508 if (string.startsWith("Version:")) {
509 size_t location = string.findIgnoringCase("<html");
510 if (location != notFound)
511 stringOmittingMicrosoftPrefix = string.substring(location);
514 if (stringOmittingMicrosoftPrefix.isEmpty())
517 if (!frame.document())
519 Document& document = *frame.document();
521 fragment = createFragmentFromMarkup(document, stringOmittingMicrosoftPrefix, emptyString(), DisallowScriptingAndPluginContent);
525 bool Editor::WebContentReader::readRTFD(PassRefPtr<SharedBuffer> buffer)
527 fragment = frame.editor().createFragmentAndAddResources(adoptNS([[NSAttributedString alloc] initWithRTFD:buffer->createNSData().get() documentAttributes:nullptr]).get());
531 bool Editor::WebContentReader::readRTF(PassRefPtr<SharedBuffer> buffer)
533 fragment = frame.editor().createFragmentAndAddResources(adoptNS([[NSAttributedString alloc] initWithRTF:buffer->createNSData().get() documentAttributes:nullptr]).get());
537 bool Editor::WebContentReader::readImage(PassRefPtr<SharedBuffer> buffer, const String& type)
539 ASSERT(type.contains('/'));
540 String typeAsFilenameWithExtension = type;
541 typeAsFilenameWithExtension.replace('/', '.');
542 URL imageURL = URL(URL(), "webkit-fake-url://" + createCanonicalUUIDString() + '/' + typeAsFilenameWithExtension);
544 fragment = frame.editor().createFragmentForImageResourceAndAddResource(ArchiveResource::create(buffer, imageURL, type, emptyString(), emptyString()));
548 bool Editor::WebContentReader::readURL(const URL& url, const String& title)
550 if (url.string().isEmpty())
553 RefPtr<Element> anchor = frame.document()->createElement(HTMLNames::aTag, false);
554 anchor->setAttribute(HTMLNames::hrefAttr, url.string());
555 anchor->appendChild(frame.document()->createTextNode([title precomposedStringWithCanonicalMapping]));
557 fragment = frame.document()->createDocumentFragment();
558 fragment->appendChild(anchor.release());
562 bool Editor::WebContentReader::readPlainText(const String& text)
567 fragment = createFragmentFromText(context, [text precomposedStringWithCanonicalMapping]);
571 madeFragmentFromPlainText = true;
575 // FIXME: Should give this function a name that makes it clear it adds resources to the document loader as a side effect.
576 // Or refactor so it does not do that.
577 PassRefPtr<DocumentFragment> Editor::webContentFromPasteboard(Pasteboard& pasteboard, Range& context, bool allowPlainText, bool& chosePlainText)
579 WebContentReader reader(m_frame, context, allowPlainText);
580 pasteboard.read(reader);
581 chosePlainText = reader.madeFragmentFromPlainText;
582 return reader.fragment.release();
585 PassRefPtr<DocumentFragment> Editor::createFragmentForImageResourceAndAddResource(PassRefPtr<ArchiveResource> resource)
590 RefPtr<Element> imageElement = document().createElement(HTMLNames::imgTag, false);
591 imageElement->setAttribute(HTMLNames::srcAttr, resource->url().string());
593 RefPtr<DocumentFragment> fragment = document().createDocumentFragment();
594 fragment->appendChild(imageElement.release());
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 return fragment.release();
603 PassRefPtr<DocumentFragment> Editor::createFragmentAndAddResources(NSAttributedString *string)
605 if (!m_frame.page() || !document().isHTMLDocument())
611 bool wasDeferringCallbacks = m_frame.page()->defersLoading();
612 if (!wasDeferringCallbacks)
613 m_frame.page()->setDefersLoading(true);
615 Vector<RefPtr<ArchiveResource>> resources;
616 RefPtr<DocumentFragment> fragment = client()->documentFragmentFromAttributedString(string, resources);
618 if (DocumentLoader* loader = m_frame.loader().documentLoader()) {
619 for (size_t i = 0, size = resources.size(); i < size; ++i)
620 loader->addArchiveResource(resources[i]);
623 if (!wasDeferringCallbacks)
624 m_frame.page()->setDefersLoading(false);
626 return fragment.release();
629 } // namespace WebCore