6cef489959b495d076990153bb95a1c2f09faf04
[WebKit-https.git] / Source / WebCore / editing / mac / EditorMac.mm
1 /*
2  * Copyright (C) 2006, 2007, 2008, 2013, 2015 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 "Editor.h"
28
29 #import "BlockExceptions.h"
30 #import "CSSPrimitiveValueMappings.h"
31 #import "CSSValuePool.h"
32 #import "CachedResourceLoader.h"
33 #import "ColorMac.h"
34 #import "DOMRangeInternal.h"
35 #import "DataTransfer.h"
36 #import "DocumentFragment.h"
37 #import "DocumentLoader.h"
38 #import "Editor.h"
39 #import "EditorClient.h"
40 #import "File.h"
41 #import "FontCascade.h"
42 #import "Frame.h"
43 #import "FrameLoaderClient.h"
44 #import "FrameView.h"
45 #import "HTMLAttachmentElement.h"
46 #import "HTMLConverter.h"
47 #import "HTMLElement.h"
48 #import "HTMLNames.h"
49 #import "LegacyWebArchive.h"
50 #import "MIMETypeRegistry.h"
51 #import "NodeTraversal.h"
52 #import "Page.h"
53 #import "Pasteboard.h"
54 #import "PasteboardStrategy.h"
55 #import "PlatformStrategies.h"
56 #import "Range.h"
57 #import "RenderBlock.h"
58 #import "RenderImage.h"
59 #import "RuntimeApplicationChecks.h"
60 #import "Sound.h"
61 #import "StyleProperties.h"
62 #import "Text.h"
63 #import "TypingCommand.h"
64 #import "UUID.h"
65 #import "WebNSAttributedStringExtras.h"
66 #import "htmlediting.h"
67 #import "markup.h"
68
69 namespace WebCore {
70
71 using namespace HTMLNames;
72
73 void Editor::showFontPanel()
74 {
75     [[NSFontManager sharedFontManager] orderFrontFontPanel:nil];
76 }
77
78 void Editor::showStylesPanel()
79 {
80     [[NSFontManager sharedFontManager] orderFrontStylesPanel:nil];
81 }
82
83 void Editor::showColorPanel()
84 {
85     [[NSApplication sharedApplication] orderFrontColorPanel:nil];
86 }
87
88 void Editor::pasteWithPasteboard(Pasteboard* pasteboard, bool allowPlainText, MailBlockquoteHandling mailBlockquoteHandling)
89 {
90     RefPtr<Range> range = selectedRange();
91
92     // FIXME: How can this hard-coded pasteboard name be right, given that the passed-in pasteboard has a name?
93     client()->setInsertionPasteboard(NSGeneralPboard);
94
95     bool chosePlainText;
96     RefPtr<DocumentFragment> fragment = webContentFromPasteboard(*pasteboard, *range, allowPlainText, chosePlainText);
97
98     if (fragment && shouldInsertFragment(fragment, range, EditorInsertActionPasted))
99         pasteAsFragment(fragment, canSmartReplaceWithPasteboard(*pasteboard), false, mailBlockquoteHandling);
100
101     client()->setInsertionPasteboard(String());
102 }
103
104 bool Editor::insertParagraphSeparatorInQuotedContent()
105 {
106     // FIXME: Why is this missing calls to canEdit, canEditRichly, etc.?
107     TypingCommand::insertParagraphSeparatorInQuotedContent(document());
108     revealSelectionAfterEditingOperation();
109     return true;
110 }
111
112 const Font* Editor::fontForSelection(bool& hasMultipleFonts) const
113 {
114     hasMultipleFonts = false;
115
116     if (!m_frame.selection().isRange()) {
117         Node* nodeToRemove;
118         RenderStyle* style = styleForSelectionStart(&m_frame, nodeToRemove); // sets nodeToRemove
119
120         const Font* result = nullptr;
121         if (style)
122             result = &style->fontCascade().primaryFont();
123
124         if (nodeToRemove)
125             nodeToRemove->remove(ASSERT_NO_EXCEPTION);
126
127         return result;
128     }
129
130     const Font* font = 0;
131     RefPtr<Range> range = m_frame.selection().toNormalizedRange();
132     Node* startNode = adjustedSelectionStartForStyleComputation(m_frame.selection().selection()).deprecatedNode();
133     if (range && startNode) {
134         Node* pastEnd = range->pastLastNode();
135         // In the loop below, n should eventually match pastEnd and not become nil, but we've seen at least one
136         // unreproducible case where this didn't happen, so check for null also.
137         for (Node* node = startNode; node && node != pastEnd; node = NodeTraversal::next(*node)) {
138             auto renderer = node->renderer();
139             if (!renderer)
140                 continue;
141             // FIXME: Are there any node types that have renderers, but that we should be skipping?
142             const Font& primaryFont = renderer->style().fontCascade().primaryFont();
143             if (!font)
144                 font = &primaryFont;
145             else if (font != &primaryFont) {
146                 hasMultipleFonts = true;
147                 break;
148             }
149         }
150     }
151
152     return font;
153 }
154
155 NSDictionary* Editor::fontAttributesForSelectionStart() const
156 {
157     Node* nodeToRemove;
158     RenderStyle* style = styleForSelectionStart(&m_frame, nodeToRemove);
159     if (!style)
160         return nil;
161
162     NSMutableDictionary* result = [NSMutableDictionary dictionary];
163
164     if (style->visitedDependentColor(CSSPropertyBackgroundColor).isValid() && style->visitedDependentColor(CSSPropertyBackgroundColor).alpha() != 0)
165         [result setObject:nsColor(style->visitedDependentColor(CSSPropertyBackgroundColor)) forKey:NSBackgroundColorAttributeName];
166
167     if (style->fontCascade().primaryFont().getNSFont())
168         [result setObject:style->fontCascade().primaryFont().getNSFont() forKey:NSFontAttributeName];
169
170     if (style->visitedDependentColor(CSSPropertyColor).isValid() && style->visitedDependentColor(CSSPropertyColor) != Color::black)
171         [result setObject:nsColor(style->visitedDependentColor(CSSPropertyColor)) forKey:NSForegroundColorAttributeName];
172
173     const ShadowData* shadow = style->textShadow();
174     if (shadow) {
175         RetainPtr<NSShadow> s = adoptNS([[NSShadow alloc] init]);
176         [s.get() setShadowOffset:NSMakeSize(shadow->x(), shadow->y())];
177         [s.get() setShadowBlurRadius:shadow->radius()];
178         [s.get() setShadowColor:nsColor(shadow->color())];
179         [result setObject:s.get() forKey:NSShadowAttributeName];
180     }
181
182     int superscriptInt = 0;
183     switch (style->verticalAlign()) {
184         case BASELINE:
185         case BOTTOM:
186         case BASELINE_MIDDLE:
187         case LENGTH:
188         case MIDDLE:
189         case TEXT_BOTTOM:
190         case TEXT_TOP:
191         case TOP:
192             break;
193         case SUB:
194             superscriptInt = -1;
195             break;
196         case SUPER:
197             superscriptInt = 1;
198             break;
199     }
200     if (superscriptInt)
201         [result setObject:[NSNumber numberWithInt:superscriptInt] forKey:NSSuperscriptAttributeName];
202
203     getTextDecorationAttributesRespectingTypingStyle(*style, result);
204
205     if (nodeToRemove)
206         nodeToRemove->remove(ASSERT_NO_EXCEPTION);
207
208     return result;
209 }
210
211 bool Editor::canCopyExcludingStandaloneImages()
212 {
213     const VisibleSelection& selection = m_frame.selection().selection();
214     return selection.isRange() && !selection.isInPasswordField();
215 }
216
217 void Editor::takeFindStringFromSelection()
218 {
219     if (!canCopyExcludingStandaloneImages()) {
220         systemBeep();
221         return;
222     }
223
224     Vector<String> types;
225     types.append(String(NSStringPboardType));
226     platformStrategies()->pasteboardStrategy()->setTypes(types, NSFindPboard);
227     platformStrategies()->pasteboardStrategy()->setStringForType(m_frame.displayStringModifiedByEncoding(selectedTextForDataTransfer()), NSStringPboardType, NSFindPboard);
228 }
229
230 void Editor::readSelectionFromPasteboard(const String& pasteboardName, MailBlockquoteHandling mailBlockquoteHandling)
231 {
232     Pasteboard pasteboard(pasteboardName);
233     if (m_frame.selection().selection().isContentRichlyEditable())
234         pasteWithPasteboard(&pasteboard, true, mailBlockquoteHandling);
235     else
236         pasteAsPlainTextWithPasteboard(pasteboard);
237 }
238
239 static void maybeCopyNodeAttributesToFragment(const Node& node, DocumentFragment& fragment)
240 {
241     // This is only supported for single-Node fragments.
242     Node* firstChild = fragment.firstChild();
243     if (!firstChild || firstChild != fragment.lastChild())
244         return;
245
246     // And only supported for HTML elements.
247     if (!node.isHTMLElement() || !firstChild->isHTMLElement())
248         return;
249
250     // And only if the source Element and destination Element have the same HTML tag name.
251     const HTMLElement& oldElement = downcast<HTMLElement>(node);
252     HTMLElement& newElement = downcast<HTMLElement>(*firstChild);
253     if (oldElement.localName() != newElement.localName())
254         return;
255
256     for (const Attribute& attribute : oldElement.attributesIterator()) {
257         if (newElement.hasAttribute(attribute.name()))
258             continue;
259         newElement.setAttribute(attribute.name(), attribute.value());
260     }
261 }
262
263 void Editor::replaceNodeFromPasteboard(Node* node, const String& pasteboardName)
264 {
265     ASSERT(node);
266
267     if (&node->document() != m_frame.document())
268         return;
269
270     RefPtr<Range> range = Range::create(node->document(), Position(node, Position::PositionIsBeforeAnchor), Position(node, Position::PositionIsAfterAnchor));
271     m_frame.selection().setSelection(VisibleSelection(*range), FrameSelection::DoNotSetFocus);
272
273     Pasteboard pasteboard(pasteboardName);
274
275     if (!m_frame.selection().selection().isContentRichlyEditable()) {
276         pasteAsPlainTextWithPasteboard(pasteboard);
277         return;
278     }
279
280     // FIXME: How can this hard-coded pasteboard name be right, given that the passed-in pasteboard has a name?
281     client()->setInsertionPasteboard(NSGeneralPboard);
282
283     bool chosePlainText;
284     if (RefPtr<DocumentFragment> fragment = webContentFromPasteboard(pasteboard, *range, true, chosePlainText)) {
285         maybeCopyNodeAttributesToFragment(*node, *fragment);
286         if (shouldInsertFragment(fragment, range, EditorInsertActionPasted))
287             pasteAsFragment(fragment.release(), canSmartReplaceWithPasteboard(pasteboard), false, MailBlockquoteHandling::IgnoreBlockquote);
288     }
289
290     client()->setInsertionPasteboard(String());
291 }
292
293 // FIXME: Makes no sense that selectedTextForDataTransfer always includes alt text, but stringSelectionForPasteboard does not.
294 // This was left in a bad state when selectedTextForDataTransfer was added. Need to look over clients and fix this.
295 String Editor::stringSelectionForPasteboard()
296 {
297     if (!canCopy())
298         return "";
299     String text = selectedText();
300     text.replace(noBreakSpace, ' ');
301     return text;
302 }
303
304 String Editor::stringSelectionForPasteboardWithImageAltText()
305 {
306     if (!canCopy())
307         return "";
308     String text = selectedTextForDataTransfer();
309     text.replace(noBreakSpace, ' ');
310     return text;
311 }
312
313 PassRefPtr<SharedBuffer> Editor::selectionInWebArchiveFormat()
314 {
315     RefPtr<LegacyWebArchive> archive = LegacyWebArchive::createFromSelection(&m_frame);
316     return archive ? SharedBuffer::wrapCFData(archive->rawDataRepresentation().get()) : 0;
317 }
318
319 PassRefPtr<Range> Editor::adjustedSelectionRange()
320 {
321     // FIXME: Why do we need to adjust the selection to include the anchor tag it's in?
322     // Whoever wrote this code originally forgot to leave us a comment explaining the rationale.
323     RefPtr<Range> range = selectedRange();
324     Node* commonAncestor = range->commonAncestorContainer();
325     ASSERT(commonAncestor);
326     auto* enclosingAnchor = enclosingElementWithTag(firstPositionInNode(commonAncestor), HTMLNames::aTag);
327     if (enclosingAnchor && comparePositions(firstPositionInOrBeforeNode(range->startPosition().anchorNode()), range->startPosition()) >= 0)
328         range->setStart(enclosingAnchor, 0, IGNORE_EXCEPTION);
329     return range;
330 }
331     
332 static PassRefPtr<SharedBuffer> dataInRTFDFormat(NSAttributedString *string)
333 {
334     NSUInteger length = string.length;
335     if (!length)
336         return nullptr;
337
338     BEGIN_BLOCK_OBJC_EXCEPTIONS;
339     return SharedBuffer::wrapNSData([string RTFDFromRange:NSMakeRange(0, length) documentAttributes:@{ }]);
340     END_BLOCK_OBJC_EXCEPTIONS;
341
342     return nullptr;
343 }
344
345 static PassRefPtr<SharedBuffer> dataInRTFFormat(NSAttributedString *string)
346 {
347     NSUInteger length = string.length;
348     if (!length)
349         return nullptr;
350
351     BEGIN_BLOCK_OBJC_EXCEPTIONS;
352     return SharedBuffer::wrapNSData([string RTFFromRange:NSMakeRange(0, length) documentAttributes:@{ }]);
353     END_BLOCK_OBJC_EXCEPTIONS;
354
355     return nullptr;
356 }
357
358 PassRefPtr<SharedBuffer> Editor::dataSelectionForPasteboard(const String& pasteboardType)
359 {
360     // FIXME: The interface to this function is awkward. We'd probably be better off with three separate functions.
361     // As of this writing, this is only used in WebKit2 to implement the method -[WKView writeSelectionToPasteboard:types:],
362     // which is only used to support OS X services.
363
364     // FIXME: Does this function really need to use adjustedSelectionRange()? Because writeSelectionToPasteboard() just uses selectedRange().
365     if (!canCopy())
366         return nullptr;
367
368     if (pasteboardType == WebArchivePboardType)
369         return selectionInWebArchiveFormat();
370
371     if (pasteboardType == String(NSRTFDPboardType))
372        return dataInRTFDFormat(attributedStringFromRange(*adjustedSelectionRange()));
373
374     if (pasteboardType == String(NSRTFPboardType)) {
375         NSAttributedString* attributedString = attributedStringFromRange(*adjustedSelectionRange());
376         // FIXME: Why is this attachment character stripping needed here, but not needed in writeSelectionToPasteboard?
377         if ([attributedString containsAttachments])
378             attributedString = attributedStringByStrippingAttachmentCharacters(attributedString);
379         return dataInRTFFormat(attributedString);
380     }
381
382     return 0;
383 }
384
385 void Editor::writeSelectionToPasteboard(Pasteboard& pasteboard)
386 {
387     NSAttributedString *attributedString = attributedStringFromRange(*selectedRange());
388
389     PasteboardWebContent content;
390     content.canSmartCopyOrDelete = canSmartCopyOrDelete();
391     content.dataInWebArchiveFormat = selectionInWebArchiveFormat();
392     content.dataInRTFDFormat = [attributedString containsAttachments] ? dataInRTFDFormat(attributedString) : 0;
393     content.dataInRTFFormat = dataInRTFFormat(attributedString);
394     content.dataInStringFormat = stringSelectionForPasteboardWithImageAltText();
395     client()->getClientPasteboardDataForRange(selectedRange().get(), content.clientTypes, content.clientData);
396
397     pasteboard.write(content);
398 }
399
400 static void getImage(Element& imageElement, RefPtr<Image>& image, CachedImage*& cachedImage)
401 {
402     auto* renderer = imageElement.renderer();
403     if (!is<RenderImage>(renderer))
404         return;
405
406     CachedImage* tentativeCachedImage = downcast<RenderImage>(*renderer).cachedImage();
407     if (!tentativeCachedImage || tentativeCachedImage->errorOccurred())
408         return;
409
410     image = tentativeCachedImage->imageForRenderer(renderer);
411     if (!image)
412         return;
413
414     cachedImage = tentativeCachedImage;
415 }
416
417 void Editor::fillInUserVisibleForm(PasteboardURL& pasteboardURL)
418 {
419     pasteboardURL.userVisibleForm = client()->userVisibleString(pasteboardURL.url);
420 }
421
422 String Editor::plainTextFromPasteboard(const PasteboardPlainText& text)
423 {
424     String string = text.text;
425
426     // FIXME: It's not clear this is 100% correct since we know -[NSURL URLWithString:] does not handle
427     // all the same cases we handle well in the URL code for creating an NSURL.
428     if (text.isURL)
429         string = client()->userVisibleString([NSURL URLWithString:string]);
430
431     // FIXME: WTF should offer a non-Mac-specific way to convert string to precomposed form so we can do it for all platforms.
432     return [(NSString *)string precomposedStringWithCanonicalMapping];
433 }
434
435 void Editor::writeImageToPasteboard(Pasteboard& pasteboard, Element& imageElement, const URL& url, const String& title)
436 {
437     PasteboardImage pasteboardImage;
438
439     CachedImage* cachedImage;
440     getImage(imageElement, pasteboardImage.image, cachedImage);
441     if (!pasteboardImage.image)
442         return;
443     ASSERT(cachedImage);
444
445     pasteboardImage.url.url = url;
446     pasteboardImage.url.title = title;
447     pasteboardImage.url.userVisibleForm = client()->userVisibleString(pasteboardImage.url.url);
448     pasteboardImage.resourceData = cachedImage->resourceBuffer();
449     pasteboardImage.resourceMIMEType = cachedImage->response().mimeType();
450
451     pasteboard.write(pasteboardImage);
452 }
453
454 class Editor::WebContentReader final : public PasteboardWebContentReader {
455 public:
456     Frame& frame;
457     Range& context;
458     const bool allowPlainText;
459
460     RefPtr<DocumentFragment> fragment;
461     bool madeFragmentFromPlainText;
462
463     WebContentReader(Frame& frame, Range& context, bool allowPlainText)
464         : frame(frame)
465         , context(context)
466         , allowPlainText(allowPlainText)
467         , madeFragmentFromPlainText(false)
468     {
469     }
470
471 private:
472     virtual bool readWebArchive(PassRefPtr<SharedBuffer>) override;
473     virtual bool readFilenames(const Vector<String>&) override;
474     virtual bool readHTML(const String&) override;
475     virtual bool readRTFD(PassRefPtr<SharedBuffer>) override;
476     virtual bool readRTF(PassRefPtr<SharedBuffer>) override;
477     virtual bool readImage(PassRefPtr<SharedBuffer>, const String& type) override;
478     virtual bool readURL(const URL&, const String& title) override;
479     virtual bool readPlainText(const String&) override;
480 };
481
482 bool Editor::WebContentReader::readWebArchive(PassRefPtr<SharedBuffer> buffer)
483 {
484     if (!frame.document())
485         return false;
486
487     RefPtr<LegacyWebArchive> archive = LegacyWebArchive::create(URL(), buffer.get());
488     if (!archive)
489         return false;
490
491     RefPtr<ArchiveResource> mainResource = archive->mainResource();
492     if (!mainResource)
493         return false;
494
495     const String& type = mainResource->mimeType();
496
497     if (frame.loader().client().canShowMIMETypeAsHTML(type)) {
498         // FIXME: The code in createFragmentAndAddResources calls setDefersLoading(true). Don't we need that here?
499         if (DocumentLoader* loader = frame.loader().documentLoader())
500             loader->addAllArchiveResources(archive.get());
501
502         String markupString = String::fromUTF8(mainResource->data()->data(), mainResource->data()->size());
503         fragment = createFragmentFromMarkup(*frame.document(), markupString, mainResource->url(), DisallowScriptingAndPluginContent);
504         return true;
505     }
506
507     if (MIMETypeRegistry::isSupportedImageMIMEType(type)) {
508         fragment = frame.editor().createFragmentForImageResourceAndAddResource(mainResource.release());
509         return true;
510     }
511
512     return false;
513 }
514
515 bool Editor::WebContentReader::readFilenames(const Vector<String>& paths)
516 {
517     size_t size = paths.size();
518     if (!size)
519         return false;
520
521     if (!frame.document())
522         return false;
523     Document& document = *frame.document();
524
525     fragment = document.createDocumentFragment();
526
527     for (size_t i = 0; i < size; i++) {
528         String text = paths[i];
529 #if ENABLE(ATTACHMENT_ELEMENT)
530         RefPtr<HTMLAttachmentElement> attachment = HTMLAttachmentElement::create(attachmentTag, document);
531         attachment->setFile(File::create([[NSURL fileURLWithPath:text] path]).ptr());
532         fragment->appendChild(attachment.release());
533 #else
534         text = frame.editor().client()->userVisibleString([NSURL fileURLWithPath:text]);
535
536         RefPtr<HTMLElement> paragraph = createDefaultParagraphElement(document);
537         paragraph->appendChild(document.createTextNode(text));
538         fragment->appendChild(paragraph.release());
539 #endif
540     }
541
542     return true;
543 }
544
545 bool Editor::WebContentReader::readHTML(const String& string)
546 {
547     String stringOmittingMicrosoftPrefix = string;
548
549     // This code was added to make HTML paste from Microsoft Word on Mac work, back in 2004.
550     // It's a simple-minded way to ignore the CF_HTML clipboard format, just skipping over the
551     // description part and parsing the entire context plus fragment.
552     if (string.startsWith("Version:")) {
553         size_t location = string.findIgnoringCase("<html");
554         if (location != notFound)
555             stringOmittingMicrosoftPrefix = string.substring(location);
556     }
557
558     if (stringOmittingMicrosoftPrefix.isEmpty())
559         return false;
560
561     if (!frame.document())
562         return false;
563     Document& document = *frame.document();
564
565     fragment = createFragmentFromMarkup(document, stringOmittingMicrosoftPrefix, emptyString(), DisallowScriptingAndPluginContent);
566     return fragment;
567 }
568
569 bool Editor::WebContentReader::readRTFD(PassRefPtr<SharedBuffer> buffer)
570 {
571     fragment = frame.editor().createFragmentAndAddResources(adoptNS([[NSAttributedString alloc] initWithRTFD:buffer->createNSData().get() documentAttributes:nullptr]).get());
572     return fragment;
573 }
574
575 bool Editor::WebContentReader::readRTF(PassRefPtr<SharedBuffer> buffer)
576 {
577     fragment = frame.editor().createFragmentAndAddResources(adoptNS([[NSAttributedString alloc] initWithRTF:buffer->createNSData().get() documentAttributes:nullptr]).get());
578     return fragment;
579 }
580
581 bool Editor::WebContentReader::readImage(PassRefPtr<SharedBuffer> buffer, const String& type)
582 {
583     ASSERT(type.contains('/'));
584     String typeAsFilenameWithExtension = type;
585     typeAsFilenameWithExtension.replace('/', '.');
586     URL imageURL = URL::fakeURLWithRelativePart(typeAsFilenameWithExtension);
587
588     fragment = frame.editor().createFragmentForImageResourceAndAddResource(ArchiveResource::create(buffer, imageURL, type, emptyString(), emptyString()));
589     return fragment;
590 }
591
592 bool Editor::WebContentReader::readURL(const URL& url, const String& title)
593 {
594     if (url.string().isEmpty())
595         return false;
596
597     RefPtr<Element> anchor = frame.document()->createElement(HTMLNames::aTag, false);
598     anchor->setAttribute(HTMLNames::hrefAttr, url.string());
599     anchor->appendChild(frame.document()->createTextNode([title precomposedStringWithCanonicalMapping]));
600
601     fragment = frame.document()->createDocumentFragment();
602     fragment->appendChild(anchor.release());
603     return true;
604 }
605
606 bool Editor::WebContentReader::readPlainText(const String& text)
607 {
608     if (!allowPlainText)
609         return false;
610
611     fragment = createFragmentFromText(context, [text precomposedStringWithCanonicalMapping]);
612     if (!fragment)
613         return false;
614
615     madeFragmentFromPlainText = true;
616     return true;
617 }
618
619 // FIXME: Should give this function a name that makes it clear it adds resources to the document loader as a side effect.
620 // Or refactor so it does not do that.
621 PassRefPtr<DocumentFragment> Editor::webContentFromPasteboard(Pasteboard& pasteboard, Range& context, bool allowPlainText, bool& chosePlainText)
622 {
623     WebContentReader reader(m_frame, context, allowPlainText);
624     pasteboard.read(reader);
625     chosePlainText = reader.madeFragmentFromPlainText;
626     return reader.fragment.release();
627 }
628
629 PassRefPtr<DocumentFragment> Editor::createFragmentForImageResourceAndAddResource(PassRefPtr<ArchiveResource> resource)
630 {
631     if (!resource)
632         return nullptr;
633
634     // FIXME: The code in createFragmentAndAddResources calls setDefersLoading(true). Don't we need that here?
635     if (DocumentLoader* loader = m_frame.loader().documentLoader())
636         loader->addArchiveResource(resource.get());
637
638     RefPtr<Element> imageElement = document().createElement(HTMLNames::imgTag, false);
639     imageElement->setAttribute(HTMLNames::srcAttr, resource->url().string());
640
641     RefPtr<DocumentFragment> fragment = document().createDocumentFragment();
642     fragment->appendChild(imageElement.release());
643
644     return fragment.release();
645 }
646
647 PassRefPtr<DocumentFragment> Editor::createFragmentAndAddResources(NSAttributedString *string)
648 {
649     if (!m_frame.page() || !document().isHTMLDocument())
650         return nullptr;
651
652     if (!string)
653         return nullptr;
654
655     bool wasDeferringCallbacks = m_frame.page()->defersLoading();
656     if (!wasDeferringCallbacks)
657         m_frame.page()->setDefersLoading(true);
658
659     Vector<RefPtr<ArchiveResource>> resources;
660     RefPtr<DocumentFragment> fragment = client()->documentFragmentFromAttributedString(string, resources);
661
662     if (DocumentLoader* loader = m_frame.loader().documentLoader()) {
663         for (size_t i = 0, size = resources.size(); i < size; ++i)
664             loader->addArchiveResource(resources[i]);
665     }
666
667     if (!wasDeferringCallbacks)
668         m_frame.page()->setDefersLoading(false);
669
670     return fragment.release();
671 }
672
673 void Editor::replaceSelectionWithAttributedString(NSAttributedString *attributedString, MailBlockquoteHandling mailBlockquoteHandling)
674 {
675     if (m_frame.selection().isNone())
676         return;
677
678     if (m_frame.selection().selection().isContentRichlyEditable()) {
679         RefPtr<DocumentFragment> fragment = createFragmentAndAddResources(attributedString);
680         if (fragment && shouldInsertFragment(fragment, selectedRange(), EditorInsertActionPasted))
681             pasteAsFragment(fragment, false, false, mailBlockquoteHandling);
682     } else {
683         String text = [attributedString string];
684         if (shouldInsertText(text, selectedRange().get(), EditorInsertActionPasted))
685             pasteAsPlainText(text, false);
686     }
687 }
688
689 void Editor::applyFontStyles(const String& fontFamily, double fontSize, unsigned fontTraits)
690 {
691     auto& cssValuePool = CSSValuePool::singleton();
692     Ref<MutableStyleProperties> style = MutableStyleProperties::create();
693     style->setProperty(CSSPropertyFontFamily, cssValuePool.createFontFamilyValue(fontFamily));
694     style->setProperty(CSSPropertyFontStyle, (fontTraits & NSFontItalicTrait) ? CSSValueItalic : CSSValueNormal);
695     style->setProperty(CSSPropertyFontWeight, cssValuePool.createValue(fontTraits & NSFontBoldTrait ? FontWeightBold : FontWeightNormal));
696     style->setProperty(CSSPropertyFontSize, cssValuePool.createValue(fontSize, CSSPrimitiveValue::CSS_PX));
697     applyStyleToSelection(style.ptr(), EditActionSetFont);
698 }
699
700 } // namespace WebCore