b60d5c1ecf593c83710a68273ec640cb422c1026
[WebKit-https.git] / Source / WebCore / editing / mac / EditorMac.mm
1 /*
2  * Copyright (C) 2006, 2007, 2008, 2013 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 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. 
24  */
25
26 #import "config.h"
27 #import "Editor.h"
28
29 #import "CachedResourceLoader.h"
30 #import "Clipboard.h"
31 #import "ColorMac.h"
32 #import "DOMRangeInternal.h"
33 #import "DocumentFragment.h"
34 #import "DocumentLoader.h"
35 #import "Editor.h"
36 #import "EditorClient.h"
37 #import "Font.h"
38 #import "Frame.h"
39 #import "FrameLoaderClient.h"
40 #import "FrameView.h"
41 #import "HTMLConverter.h"
42 #import "HTMLElement.h"
43 #import "HTMLNames.h"
44 #import "LegacyWebArchive.h"
45 #import "MIMETypeRegistry.h"
46 #import "NodeTraversal.h"
47 #import "Page.h"
48 #import "Pasteboard.h"
49 #import "PasteboardStrategy.h"
50 #import "PlatformStrategies.h"
51 #import "Range.h"
52 #import "RenderBlock.h"
53 #import "RenderImage.h"
54 #import "ResourceBuffer.h"
55 #import "RuntimeApplicationChecks.h"
56 #import "Sound.h"
57 #import "StyleProperties.h"
58 #import "Text.h"
59 #import "TypingCommand.h"
60 #import "UUID.h"
61 #import "WebNSAttributedStringExtras.h"
62 #import "htmlediting.h"
63 #import "markup.h"
64
65 namespace WebCore {
66
67 using namespace HTMLNames;
68
69 void Editor::showFontPanel()
70 {
71     [[NSFontManager sharedFontManager] orderFrontFontPanel:nil];
72 }
73
74 void Editor::showStylesPanel()
75 {
76     [[NSFontManager sharedFontManager] orderFrontStylesPanel:nil];
77 }
78
79 void Editor::showColorPanel()
80 {
81     [[NSApplication sharedApplication] orderFrontColorPanel:nil];
82 }
83
84 void Editor::pasteWithPasteboard(Pasteboard* pasteboard, bool allowPlainText)
85 {
86     RefPtr<Range> range = selectedRange();
87
88     // FIXME: How can this hard-coded pasteboard name be right, given that the passed-in pasteboard has a name?
89     client()->setInsertionPasteboard(NSGeneralPboard);
90
91     bool chosePlainText;
92     RefPtr<DocumentFragment> fragment = webContentFromPasteboard(*pasteboard, *range, allowPlainText, chosePlainText);
93
94     if (fragment && shouldInsertFragment(fragment, range, EditorInsertActionPasted))
95         pasteAsFragment(fragment, canSmartReplaceWithPasteboard(*pasteboard), false);
96
97     client()->setInsertionPasteboard(String());
98 }
99
100 bool Editor::insertParagraphSeparatorInQuotedContent()
101 {
102     // FIXME: Why is this missing calls to canEdit, canEditRichly, etc.?
103     TypingCommand::insertParagraphSeparatorInQuotedContent(document());
104     revealSelectionAfterEditingOperation();
105     return true;
106 }
107
108 static RenderStyle* styleForSelectionStart(Frame* frame, Node *&nodeToRemove)
109 {
110     nodeToRemove = 0;
111
112     if (frame->selection().isNone())
113         return 0;
114
115     Position position = frame->selection().selection().visibleStart().deepEquivalent();
116     if (!position.isCandidate() || position.isNull())
117         return 0;
118
119     RefPtr<EditingStyle> typingStyle = frame->selection().typingStyle();
120     if (!typingStyle || !typingStyle->style())
121         return &position.deprecatedNode()->renderer()->style();
122
123     RefPtr<Element> styleElement = frame->document()->createElement(spanTag, false);
124
125     String styleText = typingStyle->style()->asText() + " display: inline";
126     styleElement->setAttribute(styleAttr, styleText);
127
128     styleElement->appendChild(frame->document()->createEditingTextNode(""), ASSERT_NO_EXCEPTION);
129
130     position.deprecatedNode()->parentNode()->appendChild(styleElement, ASSERT_NO_EXCEPTION);
131
132     nodeToRemove = styleElement.get();
133     return styleElement->renderer() ? &styleElement->renderer()->style() : 0;
134 }
135
136 const SimpleFontData* Editor::fontForSelection(bool& hasMultipleFonts) const
137 {
138     hasMultipleFonts = false;
139
140     if (!m_frame.selection().isRange()) {
141         Node* nodeToRemove;
142         RenderStyle* style = styleForSelectionStart(&m_frame, nodeToRemove); // sets nodeToRemove
143
144         const SimpleFontData* result = 0;
145         if (style)
146             result = style->font().primaryFont();
147
148         if (nodeToRemove)
149             nodeToRemove->remove(ASSERT_NO_EXCEPTION);
150
151         return result;
152     }
153
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();
163             if (!renderer)
164                 continue;
165             // FIXME: Are there any node types that have renderers, but that we should be skipping?
166             const SimpleFontData* primaryFont = renderer->style().font().primaryFont();
167             if (!font)
168                 font = primaryFont;
169             else if (font != primaryFont) {
170                 hasMultipleFonts = true;
171                 break;
172             }
173         }
174     }
175
176     return font;
177 }
178
179 NSDictionary* Editor::fontAttributesForSelectionStart() const
180 {
181     Node* nodeToRemove;
182     RenderStyle* style = styleForSelectionStart(&m_frame, nodeToRemove);
183     if (!style)
184         return nil;
185
186     NSMutableDictionary* result = [NSMutableDictionary dictionary];
187
188     if (style->visitedDependentColor(CSSPropertyBackgroundColor).isValid() && style->visitedDependentColor(CSSPropertyBackgroundColor).alpha() != 0)
189         [result setObject:nsColor(style->visitedDependentColor(CSSPropertyBackgroundColor)) forKey:NSBackgroundColorAttributeName];
190
191     if (style->font().primaryFont()->getNSFont())
192         [result setObject:style->font().primaryFont()->getNSFont() forKey:NSFontAttributeName];
193
194     if (style->visitedDependentColor(CSSPropertyColor).isValid() && style->visitedDependentColor(CSSPropertyColor) != Color::black)
195         [result setObject:nsColor(style->visitedDependentColor(CSSPropertyColor)) forKey:NSForegroundColorAttributeName];
196
197     const ShadowData* shadow = style->textShadow();
198     if (shadow) {
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];
204     }
205
206     int decoration = style->textDecorationsInEffect();
207     if (decoration & TextDecorationLineThrough)
208         [result setObject:[NSNumber numberWithInt:NSUnderlineStyleSingle] forKey:NSStrikethroughStyleAttributeName];
209
210     int superscriptInt = 0;
211     switch (style->verticalAlign()) {
212         case BASELINE:
213         case BOTTOM:
214         case BASELINE_MIDDLE:
215         case LENGTH:
216         case MIDDLE:
217         case TEXT_BOTTOM:
218         case TEXT_TOP:
219         case TOP:
220             break;
221         case SUB:
222             superscriptInt = -1;
223             break;
224         case SUPER:
225             superscriptInt = 1;
226             break;
227     }
228     if (superscriptInt)
229         [result setObject:[NSNumber numberWithInt:superscriptInt] forKey:NSSuperscriptAttributeName];
230
231     if (decoration & TextDecorationUnderline)
232         [result setObject:[NSNumber numberWithInt:NSUnderlineStyleSingle] forKey:NSUnderlineStyleAttributeName];
233
234     if (nodeToRemove)
235         nodeToRemove->remove(ASSERT_NO_EXCEPTION);
236
237     return result;
238 }
239
240 bool Editor::canCopyExcludingStandaloneImages()
241 {
242     FrameSelection& selection = m_frame.selection();
243     return selection.isRange() && !selection.isInPasswordField();
244 }
245
246 void Editor::takeFindStringFromSelection()
247 {
248     if (!canCopyExcludingStandaloneImages()) {
249         systemBeep();
250         return;
251     }
252
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);
257 }
258
259 void Editor::readSelectionFromPasteboard(const String& pasteboardName)
260 {
261     Pasteboard pasteboard(pasteboardName);
262     if (m_frame.selection().isContentRichlyEditable())
263         pasteWithPasteboard(&pasteboard, true);
264     else
265         pasteAsPlainTextWithPasteboard(pasteboard);
266 }
267
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()
271 {
272     String text = selectedText();
273     text.replace(noBreakSpace, ' ');
274     return text;
275 }
276
277 String Editor::stringSelectionForPasteboardWithImageAltText()
278 {
279     String text = selectedTextForClipboard();
280     text.replace(noBreakSpace, ' ');
281     return text;
282 }
283
284 PassRefPtr<SharedBuffer> Editor::selectionInWebArchiveFormat()
285 {
286     RefPtr<LegacyWebArchive> archive = LegacyWebArchive::createFromSelection(&m_frame);
287     return archive ? SharedBuffer::wrapCFData(archive->rawDataRepresentation().get()) : 0;
288 }
289
290 PassRefPtr<Range> Editor::adjustedSelectionRange()
291 {
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);
300     return range;
301 }
302
303 static NSAttributedString *attributedStringForRange(Range& range)
304 {
305     return [adoptNS([[WebHTMLConverter alloc] initWithDOMRange:kit(&range)]) attributedString];
306 }
307
308 static PassRefPtr<SharedBuffer> dataInRTFDFormat(NSAttributedString *string)
309 {
310     NSUInteger length = [string length];
311     return length ? SharedBuffer::wrapNSData([string RTFDFromRange:NSMakeRange(0, length) documentAttributes:nil]) : 0;
312 }
313
314 static PassRefPtr<SharedBuffer> dataInRTFFormat(NSAttributedString *string)
315 {
316     NSUInteger length = [string length];
317     return length ? SharedBuffer::wrapNSData([string RTFFromRange:NSMakeRange(0, length) documentAttributes:nil]) : 0;
318 }
319
320 PassRefPtr<SharedBuffer> Editor::dataSelectionForPasteboard(const String& pasteboardType)
321 {
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.
325
326     // FIXME: Does this function really need to use adjustedSelectionRange()? Because writeSelectionToPasteboard() just uses selectedRange().
327
328     if (pasteboardType == WebArchivePboardType)
329         return selectionInWebArchiveFormat();
330
331     if (pasteboardType == String(NSRTFDPboardType))
332        return dataInRTFDFormat(attributedStringForRange(*adjustedSelectionRange()));
333
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);
340     }
341
342     return 0;
343 }
344
345 void Editor::writeSelectionToPasteboard(Pasteboard& pasteboard)
346 {
347     NSAttributedString *attributedString = attributedStringForRange(*selectedRange());
348
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);
356
357     pasteboard.write(content);
358 }
359
360 static void getImage(Element& imageElement, RefPtr<Image>& image, CachedImage*& cachedImage)
361 {
362     auto renderer = imageElement.renderer();
363     if (!renderer || !renderer->isImage())
364         return;
365
366     CachedImage* tentativeCachedImage = toRenderImage(renderer)->cachedImage();
367     if (!tentativeCachedImage || tentativeCachedImage->errorOccurred()) {
368         tentativeCachedImage = 0;
369         return;
370     }
371
372     image = tentativeCachedImage->imageForRenderer(renderer);
373     if (!image)
374         return;
375
376     cachedImage = tentativeCachedImage;
377 }
378
379 void Editor::fillInUserVisibleForm(PasteboardURL& pasteboardURL)
380 {
381     pasteboardURL.userVisibleForm = client()->userVisibleString(pasteboardURL.url);
382 }
383
384 String Editor::plainTextFromPasteboard(const PasteboardPlainText& text)
385 {
386     String string = text.text;
387
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.
390     if (text.isURL)
391         string = client()->userVisibleString([NSURL URLWithString:string]);
392
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];
395 }
396
397 void Editor::writeImageToPasteboard(Pasteboard& pasteboard, Element& imageElement, const URL& url, const String& title)
398 {
399     PasteboardImage pasteboardImage;
400
401     CachedImage* cachedImage;
402     getImage(imageElement, pasteboardImage.image, cachedImage);
403     if (!pasteboardImage.image)
404         return;
405     ASSERT(cachedImage);
406
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();
412
413     pasteboard.write(pasteboardImage);
414 }
415
416 class Editor::WebContentReader FINAL : public PasteboardWebContentReader {
417 public:
418     Frame& frame;
419     Range& context;
420     const bool allowPlainText;
421
422     RefPtr<DocumentFragment> fragment;
423     bool madeFragmentFromPlainText;
424
425     WebContentReader(Frame& frame, Range& context, bool allowPlainText)
426         : frame(frame)
427         , context(context)
428         , allowPlainText(allowPlainText)
429         , madeFragmentFromPlainText(false)
430     {
431     }
432
433 private:
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;
442 };
443
444 bool Editor::WebContentReader::readWebArchive(PassRefPtr<SharedBuffer> buffer)
445 {
446     if (!frame.document())
447         return false;
448
449     RefPtr<LegacyWebArchive> archive = LegacyWebArchive::create(URL(), buffer.get());
450     if (!archive)
451         return false;
452
453     RefPtr<ArchiveResource> mainResource = archive->mainResource();
454     if (!mainResource)
455         return false;
456
457     const String& type = mainResource->mimeType();
458
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());
463
464         String markupString = String::fromUTF8(mainResource->data()->data(), mainResource->data()->size());
465         fragment = createFragmentFromMarkup(*frame.document(), markupString, mainResource->url(), DisallowScriptingAndPluginContent);
466         return true;
467     }
468
469     if (MIMETypeRegistry::isSupportedImageMIMEType(type)) {
470         fragment = frame.editor().createFragmentForImageResourceAndAddResource(mainResource.release());
471         return true;
472     }
473
474     return false;
475 }
476
477 bool Editor::WebContentReader::readFilenames(const Vector<String>& paths)
478 {
479     size_t size = paths.size();
480     if (!size)
481         return false;
482
483     if (!frame.document())
484         return false;
485     Document& document = *frame.document();
486
487     fragment = document.createDocumentFragment();
488
489     for (size_t i = 0; i < size; i++) {
490         String text = paths[i];
491         text = frame.editor().client()->userVisibleString([NSURL fileURLWithPath:text]);
492
493         RefPtr<HTMLElement> paragraph = createDefaultParagraphElement(document);
494         paragraph->appendChild(document.createTextNode(text));
495         fragment->appendChild(paragraph.release());
496     }
497
498     return true;
499 }
500
501 bool Editor::WebContentReader::readHTML(const String& string)
502 {
503     String stringOmittingMicrosoftPrefix = string;
504
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);
512     }
513
514     if (stringOmittingMicrosoftPrefix.isEmpty())
515         return false;
516
517     if (!frame.document())
518         return false;
519     Document& document = *frame.document();
520
521     fragment = createFragmentFromMarkup(document, stringOmittingMicrosoftPrefix, emptyString(), DisallowScriptingAndPluginContent);
522     return fragment;
523 }
524
525 bool Editor::WebContentReader::readRTFD(PassRefPtr<SharedBuffer> buffer)
526 {
527     fragment = frame.editor().createFragmentAndAddResources(adoptNS([[NSAttributedString alloc] initWithRTFD:buffer->createNSData().get() documentAttributes:nullptr]).get());
528     return fragment;
529 }
530
531 bool Editor::WebContentReader::readRTF(PassRefPtr<SharedBuffer> buffer)
532 {
533     fragment = frame.editor().createFragmentAndAddResources(adoptNS([[NSAttributedString alloc] initWithRTF:buffer->createNSData().get() documentAttributes:nullptr]).get());
534     return fragment;
535 }
536
537 bool Editor::WebContentReader::readImage(PassRefPtr<SharedBuffer> buffer, const String& type)
538 {
539     ASSERT(type.contains('/'));
540     String typeAsFilenameWithExtension = type;
541     typeAsFilenameWithExtension.replace('/', '.');
542     URL imageURL = URL(URL(), "webkit-fake-url://" + createCanonicalUUIDString() + '/' + typeAsFilenameWithExtension);
543
544     fragment = frame.editor().createFragmentForImageResourceAndAddResource(ArchiveResource::create(buffer, imageURL, type, emptyString(), emptyString()));
545     return fragment;
546 }
547
548 bool Editor::WebContentReader::readURL(const URL& url, const String& title)
549 {
550     if (url.string().isEmpty())
551         return false;
552
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]));
556
557     fragment = frame.document()->createDocumentFragment();
558     fragment->appendChild(anchor.release());
559     return true;
560 }
561
562 bool Editor::WebContentReader::readPlainText(const String& text)
563 {
564     if (!allowPlainText)
565         return false;
566
567     fragment = createFragmentFromText(context, [text precomposedStringWithCanonicalMapping]);
568     if (!fragment)
569         return false;
570
571     madeFragmentFromPlainText = true;
572     return true;
573 }
574
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)
578 {
579     WebContentReader reader(m_frame, context, allowPlainText);
580     pasteboard.read(reader);
581     chosePlainText = reader.madeFragmentFromPlainText;
582     return reader.fragment.release();
583 }
584
585 PassRefPtr<DocumentFragment> Editor::createFragmentForImageResourceAndAddResource(PassRefPtr<ArchiveResource> resource)
586 {
587     if (!resource)
588         return nullptr;
589
590     RefPtr<Element> imageElement = document().createElement(HTMLNames::imgTag, false);
591     imageElement->setAttribute(HTMLNames::srcAttr, resource->url().string());
592
593     RefPtr<DocumentFragment> fragment = document().createDocumentFragment();
594     fragment->appendChild(imageElement.release());
595
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());
599
600     return fragment.release();
601 }
602
603 PassRefPtr<DocumentFragment> Editor::createFragmentAndAddResources(NSAttributedString *string)
604 {
605     if (!m_frame.page() || !document().isHTMLDocument())
606         return nullptr;
607
608     if (!string)
609         return nullptr;
610
611     bool wasDeferringCallbacks = m_frame.page()->defersLoading();
612     if (!wasDeferringCallbacks)
613         m_frame.page()->setDefersLoading(true);
614
615     Vector<RefPtr<ArchiveResource>> resources;
616     RefPtr<DocumentFragment> fragment = client()->documentFragmentFromAttributedString(string, resources);
617
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]);
621     }
622
623     if (!wasDeferringCallbacks)
624         m_frame.page()->setDefersLoading(false);
625
626     return fragment.release();
627 }
628
629 } // namespace WebCore