REGRESSION (r160908): Unable to unset bold while entering text
[WebKit-https.git] / Source / WebCore / editing / ios / EditorIOS.mm
1 /*
2  * Copyright (C) 2006, 2007, 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 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.
24  */
25
26 #include "config.h"
27 #include "Editor.h"
28
29 #include "BlockExceptions.h"
30 #include "CachedImage.h"
31 #include "CSSComputedStyleDeclaration.h"
32 #include "CSSPrimitiveValueMappings.h"
33 #include "DOMRangeInternal.h"
34 #include "DataTransfer.h"
35 #include "DocumentFragment.h"
36 #include "DocumentLoader.h"
37 #include "EditorClient.h"
38 #include "Font.h"
39 #include "Frame.h"
40 #include "FrameLoaderClient.h"
41 #include "HTMLConverter.h"
42 #include "HTMLInputElement.h"
43 #include "HTMLNames.h"
44 #include "HTMLParserIdioms.h"
45 #include "HTMLTextAreaElement.h"
46 #include "LegacyWebArchive.h"
47 #include "NodeTraversal.h"
48 #include "Page.h"
49 #include "Pasteboard.h"
50 #include "RenderBlock.h"
51 #include "RenderImage.h"
52 #include "ResourceBuffer.h"
53 #include "SharedBuffer.h"
54 #include "SoftLinking.h"
55 #include "StyleProperties.h"
56 #include "Text.h"
57 #include "TypingCommand.h"
58 #include "WAKAppKitStubs.h"
59 #include "htmlediting.h"
60 #include "markup.h"
61
62 #if PLATFORM(IOS)
63
64 SOFT_LINK_FRAMEWORK(AppSupport)
65 SOFT_LINK(AppSupport, CPSharedResourcesDirectory, CFStringRef, (void), ())
66
67 SOFT_LINK_FRAMEWORK(MobileCoreServices)
68
69 SOFT_LINK(MobileCoreServices, UTTypeConformsTo, Boolean, (CFStringRef inUTI, CFStringRef inConformsToUTI), (inUTI, inConformsToUTI))
70 SOFT_LINK(MobileCoreServices, UTTypeCreatePreferredIdentifierForTag, CFStringRef, (CFStringRef inTagClass, CFStringRef inTag, CFStringRef inConformingToUTI), (inTagClass, inTag, inConformingToUTI))
71 SOFT_LINK(MobileCoreServices, UTTypeCopyPreferredTagWithClass, CFStringRef, (CFStringRef inUTI, CFStringRef inTagClass), (inUTI, inTagClass))
72
73 SOFT_LINK_CONSTANT(MobileCoreServices, kUTTypePNG, CFStringRef)
74 SOFT_LINK_CONSTANT(MobileCoreServices, kUTTypeJPEG, CFStringRef)
75 SOFT_LINK_CONSTANT(MobileCoreServices, kUTTagClassFilenameExtension, CFStringRef)
76 SOFT_LINK_CONSTANT(MobileCoreServices, kUTTagClassMIMEType, CFStringRef)
77
78 #define kUTTypePNG  getkUTTypePNG()
79 #define kUTTypeJPEG getkUTTypeJPEG()
80 #define kUTTagClassFilenameExtension getkUTTagClassFilenameExtension()
81 #define kUTTagClassMIMEType getkUTTagClassMIMEType()
82
83 @interface NSAttributedString (NSAttributedStringKitAdditions)
84 - (id)initWithRTF:(NSData *)data documentAttributes:(NSDictionary **)dict;
85 - (id)initWithRTFD:(NSData *)data documentAttributes:(NSDictionary **)dict;
86 - (NSData *)RTFFromRange:(NSRange)range documentAttributes:(NSDictionary *)dict;
87 - (NSData *)RTFDFromRange:(NSRange)range documentAttributes:(NSDictionary *)dict;
88 - (BOOL)containsAttachments;
89 @end
90
91 namespace WebCore {
92
93 using namespace HTMLNames;
94
95 void Editor::showFontPanel()
96 {
97 }
98
99 void Editor::showStylesPanel()
100 {
101 }
102
103 void Editor::showColorPanel()
104 {
105 }
106
107 void Editor::setTextAlignmentForChangedBaseWritingDirection(WritingDirection direction)
108 {
109     // Note that the passed-in argument is the direction that has been changed to by
110     // some code or user interaction outside the scope of this function. The former
111     // direction is not known, nor is it required for the kind of text alignment
112     // changes done by this function.
113     //
114     // Rules:
115     // When text has no explicit alignment, set to alignment to match the writing direction.
116     // If the text has left or right alignment, flip left->right and right->left. 
117     // Otherwise, do nothing.
118
119     RefPtr<EditingStyle> selectionStyle = EditingStyle::styleAtSelectionStart(m_frame.selection().selection());
120     if (!selectionStyle || !selectionStyle->style())
121          return;
122
123     RefPtr<CSSPrimitiveValue> value = static_pointer_cast<CSSPrimitiveValue>(selectionStyle->style()->getPropertyCSSValue(CSSPropertyTextAlign));
124     if (!value)
125         return;
126         
127     const char *newValue = NULL;
128     ETextAlign textAlign = *value;
129     switch (textAlign) {
130         case TASTART:
131         case TAEND:
132         {
133             switch (direction) {
134                 case NaturalWritingDirection:
135                     // no-op
136                     break;
137                 case LeftToRightWritingDirection:
138                     newValue = "left";
139                     break;
140                 case RightToLeftWritingDirection:
141                     newValue = "right";
142                     break;
143             }
144             break;
145         }
146         case LEFT:
147         case WEBKIT_LEFT:
148             newValue = "right";
149             break;
150         case RIGHT:
151         case WEBKIT_RIGHT:
152             newValue = "left";
153             break;
154         case CENTER:
155         case WEBKIT_CENTER:
156         case JUSTIFY:
157             // no-op
158             break;
159     }
160
161     if (!newValue)
162         return;
163
164     Element* focusedElement = m_frame.document()->focusedElement();
165     if (focusedElement && (focusedElement->hasTagName(textareaTag) || (focusedElement->hasTagName(inputTag) &&
166         (toHTMLInputElement(focusedElement)->isTextField() ||
167          toHTMLInputElement(focusedElement)->isSearchField())))) {
168         if (direction == NaturalWritingDirection)
169             return;
170         toHTMLElement(focusedElement)->setAttribute(alignAttr, newValue);
171         m_frame.document()->updateStyleIfNeeded();
172         return;
173     }
174
175     RefPtr<MutableStyleProperties> style = MutableStyleProperties::create();
176     style->setProperty(CSSPropertyTextAlign, newValue);
177     applyParagraphStyle(style.get());
178 }
179
180 bool Editor::insertParagraphSeparatorInQuotedContent()
181 {
182     // FIXME: Why is this missing calls to canEdit, canEditRichly, etc...
183     TypingCommand::insertParagraphSeparatorInQuotedContent(*m_frame.document());
184     revealSelectionAfterEditingOperation();
185     return true;
186 }
187
188 const SimpleFontData* Editor::fontForSelection(bool& hasMultipleFonts) const
189 {
190     hasMultipleFonts = false;
191
192     if (!m_frame.selection().isRange()) {
193         Node* nodeToRemove;
194         RenderStyle* style = styleForSelectionStart(&m_frame, nodeToRemove); // sets nodeToRemove
195
196         const SimpleFontData* result = 0;
197         if (style)
198             result = style->font().primaryFont();
199
200         if (nodeToRemove) {
201             ExceptionCode ec;
202             nodeToRemove->remove(ec);
203             ASSERT(!ec);
204         }
205
206         return result;
207     }
208
209     const SimpleFontData* font = 0;
210     RefPtr<Range> range = m_frame.selection().toNormalizedRange();
211     if (Node* startNode = adjustedSelectionStartForStyleComputation(m_frame.selection().selection()).deprecatedNode()) {
212         Node* pastEnd = range->pastLastNode();
213         // In the loop below, n should eventually match pastEnd and not become nil, but we've seen at least one
214         // unreproducible case where this didn't happen, so check for null also.
215         for (Node* node = startNode; node && node != pastEnd; node = NodeTraversal::next(node)) {
216             auto renderer = node->renderer();
217             if (!renderer)
218                 continue;
219             // FIXME: Are there any node types that have renderers, but that we should be skipping?
220             const SimpleFontData* primaryFont = renderer->style().font().primaryFont();
221             if (!font)
222                 font = primaryFont;
223             else if (font != primaryFont) {
224                 hasMultipleFonts = true;
225                 break;
226             }
227         }
228     }
229
230     return font;
231 }
232
233 NSDictionary* Editor::fontAttributesForSelectionStart() const
234 {
235     Node* nodeToRemove;
236     RenderStyle* style = styleForSelectionStart(&m_frame, nodeToRemove);
237     if (!style)
238         return nil;
239
240     NSMutableDictionary* result = [NSMutableDictionary dictionary];
241     return result;
242 }
243
244 void Editor::removeUnchangeableStyles()
245 {
246     // This function removes styles that the user cannot modify by applying their default values.
247     
248     RefPtr<EditingStyle> editingStyle = EditingStyle::create(m_frame.document()->body());
249     RefPtr<MutableStyleProperties> defaultStyle = editingStyle.get()->style()->mutableCopy();
250     
251     // Text widgets implement background color via the UIView property. Their body element will not have one.
252     defaultStyle->setProperty(CSSPropertyBackgroundColor, "rgba(255, 255, 255, 0.0)");
253     
254     // Remove properties that the user can modify, like font-weight. 
255     // Also remove font-family, per HI spec.
256     // FIXME: it'd be nice if knowledge about which styles were unchangeable was not hard-coded here.
257     defaultStyle->removeProperty(CSSPropertyFontWeight);
258     defaultStyle->removeProperty(CSSPropertyFontStyle);
259     defaultStyle->removeProperty(CSSPropertyFontVariant);
260     // FIXME: we should handle also pasted quoted text, strikethrough, etc. <rdar://problem/9255115>
261     defaultStyle->removeProperty(CSSPropertyTextDecoration);
262     defaultStyle->removeProperty(CSSPropertyWebkitTextDecorationsInEffect); // implements underline
263
264     // FIXME add EditActionMatchStlye <rdar://problem/9156507> Undo rich text's paste & match style should say "Undo Match Style"
265     applyStyleToSelection(defaultStyle.get(), EditActionChangeAttributes);
266 }
267
268 static PassRefPtr<SharedBuffer> dataInRTFDFormat(NSAttributedString *string)
269 {
270     NSUInteger length = string.length;
271     if (!length)
272         return nullptr;
273
274     BEGIN_BLOCK_OBJC_EXCEPTIONS;
275     return SharedBuffer::wrapNSData([string RTFDFromRange:NSMakeRange(0, length) documentAttributes:nil]);
276     END_BLOCK_OBJC_EXCEPTIONS;
277
278     return nullptr;
279 }
280
281 static PassRefPtr<SharedBuffer> dataInRTFFormat(NSAttributedString *string)
282 {
283     NSUInteger length = string.length;
284     if (!length)
285         return nullptr;
286
287     BEGIN_BLOCK_OBJC_EXCEPTIONS;
288     return SharedBuffer::wrapNSData([string RTFFromRange:NSMakeRange(0, length) documentAttributes:nil]);
289     END_BLOCK_OBJC_EXCEPTIONS;
290
291     return nullptr;
292 }
293
294 String Editor::stringSelectionForPasteboardWithImageAltText()
295 {
296     String text = selectedTextForDataTransfer();
297     text.replace(noBreakSpace, ' ');
298     return text;
299 }
300
301 PassRefPtr<SharedBuffer> Editor::selectionInWebArchiveFormat()
302 {
303     RefPtr<LegacyWebArchive> archive = LegacyWebArchive::createFromSelection(&m_frame);
304     return archive ? SharedBuffer::wrapCFData(archive->rawDataRepresentation().get()) : nullptr;
305 }
306
307 void Editor::writeSelectionToPasteboard(Pasteboard& pasteboard)
308 {
309     NSAttributedString *attributedString = attributedStringFromRange(*selectedRange());
310
311     PasteboardWebContent content;
312     content.canSmartCopyOrDelete = canSmartCopyOrDelete();
313     content.dataInWebArchiveFormat = selectionInWebArchiveFormat();
314     content.dataInRTFDFormat = [attributedString containsAttachments] ? dataInRTFDFormat(attributedString) : 0;
315     content.dataInRTFFormat = dataInRTFFormat(attributedString);
316     content.dataInStringFormat = stringSelectionForPasteboardWithImageAltText();
317     client()->getClientPasteboardDataForRange(selectedRange().get(), content.clientTypes, content.clientData);
318
319     pasteboard.write(content);
320 }
321
322 static void getImage(Element& imageElement, RefPtr<Image>& image, CachedImage*& cachedImage)
323 {
324     auto renderer = imageElement.renderer();
325     if (!renderer || !renderer->isRenderImage())
326         return;
327
328     CachedImage* tentativeCachedImage = toRenderImage(renderer)->cachedImage();
329     if (!tentativeCachedImage || tentativeCachedImage->errorOccurred()) {
330         tentativeCachedImage = 0;
331         return;
332     }
333
334     image = tentativeCachedImage->imageForRenderer(renderer);
335     if (!image)
336         return;
337     
338     cachedImage = tentativeCachedImage;
339 }
340
341 void Editor::writeImageToPasteboard(Pasteboard& pasteboard, Element& imageElement, const URL&, const String& title)
342 {
343     PasteboardImage pasteboardImage;
344
345     CachedImage* cachedImage;
346     getImage(imageElement, pasteboardImage.image, cachedImage);
347     if (!pasteboardImage.image)
348         return;
349     ASSERT(cachedImage);
350
351     pasteboardImage.url.url = imageElement.document().completeURL(stripLeadingAndTrailingHTMLSpaces(imageElement.imageSourceURL()));
352     pasteboardImage.url.title = title;
353     pasteboardImage.resourceMIMEType = pasteboard.resourceMIMEType(cachedImage->response().mimeType());
354     pasteboardImage.resourceData = cachedImage->resourceBuffer()->sharedBuffer();
355
356     pasteboard.write(pasteboardImage);
357 }
358
359 class Editor::WebContentReader final : public PasteboardWebContentReader {
360 public:
361     WebContentReader(Frame& frame, Range& context, bool allowPlainText)
362         : frame(frame)
363         , context(context)
364         , allowPlainText(allowPlainText)
365         , madeFragmentFromPlainText(false)
366     {
367     }
368
369     void addFragment(PassRefPtr<DocumentFragment>);
370
371     Frame& frame;
372     Range& context;
373     const bool allowPlainText;
374
375     RefPtr<DocumentFragment> fragment;
376     bool madeFragmentFromPlainText;
377
378 private:
379     virtual bool readWebArchive(PassRefPtr<SharedBuffer>) override;
380     virtual bool readFilenames(const Vector<String>&) override;
381     virtual bool readHTML(const String&) override;
382     virtual bool readRTFD(PassRefPtr<SharedBuffer>) override;
383     virtual bool readRTF(PassRefPtr<SharedBuffer>) override;
384     virtual bool readImage(PassRefPtr<SharedBuffer>, const String& type) override;
385     virtual bool readURL(const URL&, const String& title) override;
386     virtual bool readPlainText(const String&) override;
387 };
388
389 void Editor::WebContentReader::addFragment(PassRefPtr<DocumentFragment> newFragment)
390 {
391     if (fragment) {
392         if (newFragment && newFragment->firstChild()) {
393             ExceptionCode ec;
394             fragment->appendChild(newFragment->firstChild(), ec);
395         }
396     } else
397         fragment = newFragment;
398 }
399
400 bool Editor::WebContentReader::readWebArchive(PassRefPtr<SharedBuffer> buffer)
401 {
402     if (!frame.document())
403         return false;
404
405     RefPtr<LegacyWebArchive> archive = LegacyWebArchive::create(URL(), buffer.get());
406     if (!archive)
407         return false;
408
409     RefPtr<ArchiveResource> mainResource = archive->mainResource();
410     if (!mainResource)
411         return false;
412
413     const String& type = mainResource->mimeType();
414
415     if (frame.loader().client().canShowMIMETypeAsHTML(type)) {
416         // FIXME: The code in createFragmentAndAddResources calls setDefersLoading(true). Don't we need that here?
417         if (DocumentLoader* loader = frame.loader().documentLoader())
418             loader->addAllArchiveResources(archive.get());
419
420         String markupString = String::fromUTF8(mainResource->data()->data(), mainResource->data()->size());
421         addFragment(createFragmentFromMarkup(*frame.document(), markupString, mainResource->url(), DisallowScriptingAndPluginContent));
422         return true;
423     }
424
425     return false;
426 }
427
428 bool Editor::WebContentReader::readFilenames(const Vector<String>&)
429 {
430     return false;
431 }
432
433 bool Editor::WebContentReader::readHTML(const String& string)
434 {
435     if (!frame.document())
436         return false;
437
438     addFragment(createFragmentFromMarkup(*frame.document(), string, emptyString(), DisallowScriptingAndPluginContent));
439     return true;
440 }
441
442 bool Editor::WebContentReader::readRTFD(PassRefPtr<SharedBuffer> buffer)
443 {
444     addFragment(frame.editor().createFragmentAndAddResources(adoptNS([[NSAttributedString alloc] initWithRTFD:buffer->createNSData().get() documentAttributes:nullptr]).get()));
445     return fragment;
446 }
447
448 bool Editor::WebContentReader::readRTF(PassRefPtr<SharedBuffer> buffer)
449 {
450     addFragment(frame.editor().createFragmentAndAddResources(adoptNS([[NSAttributedString alloc] initWithRTF:buffer->createNSData().get() documentAttributes:nullptr]).get()));
451     return fragment;
452 }
453
454 bool Editor::WebContentReader::readImage(PassRefPtr<SharedBuffer> buffer, const String& type)
455 {
456     RetainPtr<CFStringRef> stringType = type.createCFString();
457     RetainPtr<NSString> filenameExtension = adoptNS((NSString *)UTTypeCopyPreferredTagWithClass(stringType.get(), kUTTagClassFilenameExtension));
458     NSString *relativeURLPart = [@"image" stringByAppendingString:filenameExtension.get()];
459     RetainPtr<NSString> mimeType = adoptNS((NSString *)UTTypeCopyPreferredTagWithClass(stringType.get(), kUTTagClassMIMEType));
460
461     addFragment(frame.editor().createFragmentForImageResourceAndAddResource(ArchiveResource::create(buffer, URL::fakeURLWithRelativePart(relativeURLPart), mimeType.get(), emptyString(), emptyString())));
462     return fragment;
463 }
464
465 bool Editor::WebContentReader::readURL(const URL& url, const String&)
466 {
467     if (url.isEmpty())
468         return false;
469
470     if (!frame.editor().client()->hasRichlyEditableSelection()) {
471         if (readPlainText([(NSURL *)url absoluteString]))
472             return true;
473     }
474
475     if ([(NSURL *)url isFileURL]) {
476         NSString *localPath = [(NSURL *)url relativePath];
477         // Only allow url attachments from ~/Media for now.
478         if (![localPath hasPrefix:[(NSString *)CPSharedResourcesDirectory() stringByAppendingString:@"/Media/DCIM/"]])
479             return false;
480
481         RetainPtr<NSString> fileType = adoptNS((NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (CFStringRef)[localPath pathExtension], NULL));
482         NSData *data = [NSData dataWithContentsOfFile:localPath];
483         if (UTTypeConformsTo((CFStringRef)fileType.get(), kUTTypePNG)) {
484             addFragment(frame.editor().createFragmentForImageResourceAndAddResource(ArchiveResource::create(SharedBuffer::wrapNSData([[data copy] autorelease]), URL::fakeURLWithRelativePart("image.png"), @"image/png", emptyString(), emptyString())));
485             return fragment;
486         } else if (UTTypeConformsTo((CFStringRef)fileType.get(), kUTTypeJPEG)) {
487             addFragment(frame.editor().createFragmentForImageResourceAndAddResource(ArchiveResource::create(SharedBuffer::wrapNSData([[data copy] autorelease]), URL::fakeURLWithRelativePart("image.jpg"), @"image/jpg", emptyString(), emptyString())));
488             return fragment;
489         }
490     } else {
491         RefPtr<Element> anchor = frame.document()->createElement(HTMLNames::aTag, false);
492         anchor->setAttribute(HTMLNames::hrefAttr, url.string());
493         anchor->appendChild(frame.document()->createTextNode([[(NSURL *)url absoluteString] precomposedStringWithCanonicalMapping]));
494
495         RefPtr<DocumentFragment> newFragment = frame.document()->createDocumentFragment();
496         newFragment->appendChild(anchor.release());
497         addFragment(newFragment);
498         return true;
499     }
500     return false;
501 }
502
503 bool Editor::WebContentReader::readPlainText(const String& text)
504 {
505     if (!allowPlainText)
506         return false;
507
508     addFragment(createFragmentFromText(context, [text precomposedStringWithCanonicalMapping]));
509     if (!fragment)
510         return false;
511
512     madeFragmentFromPlainText = true;
513     return true;
514 }
515
516 // FIXME: Should give this function a name that makes it clear it adds resources to the document loader as a side effect.
517 // Or refactor so it does not do that.
518 PassRefPtr<DocumentFragment> Editor::webContentFromPasteboard(Pasteboard& pasteboard, Range& context, bool allowPlainText, bool& chosePlainText)
519 {
520     WebContentReader reader(m_frame, context, allowPlainText);
521     pasteboard.read(reader);
522     chosePlainText = reader.madeFragmentFromPlainText;
523     return reader.fragment.release();
524 }
525
526 void Editor::pasteWithPasteboard(Pasteboard* pasteboard, bool allowPlainText, MailBlockquoteHandling mailBlockquoteHandling)
527 {
528     RefPtr<Range> range = selectedRange();
529     WebContentReader reader(m_frame, *range, allowPlainText);
530     int numberOfPasteboardItems = client()->getPasteboardItemsCount();
531     for (int i = 0; i < numberOfPasteboardItems; ++i) {
532         RefPtr<DocumentFragment> fragment = client()->documentFragmentFromDelegate(i);
533         if (!fragment)
534             continue;
535
536         reader.addFragment(fragment);
537     }
538
539     RefPtr<DocumentFragment> fragment = reader.fragment;
540     if (!fragment) {
541         bool chosePlainTextIgnored;
542         fragment = webContentFromPasteboard(*pasteboard, *range, allowPlainText, chosePlainTextIgnored);
543     }
544
545     if (fragment && shouldInsertFragment(fragment, range, EditorInsertActionPasted))
546         pasteAsFragment(fragment, canSmartReplaceWithPasteboard(*pasteboard), false, mailBlockquoteHandling);
547 }
548
549 PassRefPtr<DocumentFragment> Editor::createFragmentAndAddResources(NSAttributedString *string)
550 {
551     if (!m_frame.page() || !m_frame.document() || !m_frame.document()->isHTMLDocument())
552         return nullptr;
553
554     if (!string)
555         return nullptr;
556
557     bool wasDeferringCallbacks = m_frame.page()->defersLoading();
558     if (!wasDeferringCallbacks)
559         m_frame.page()->setDefersLoading(true);
560
561     Vector<RefPtr<ArchiveResource>> resources;
562     RefPtr<DocumentFragment> fragment = client()->documentFragmentFromAttributedString(string, resources);
563
564     if (DocumentLoader* loader = m_frame.loader().documentLoader()) {
565         for (size_t i = 0, size = resources.size(); i < size; ++i)
566             loader->addArchiveResource(resources[i]);
567     }
568
569     if (!wasDeferringCallbacks)
570         m_frame.page()->setDefersLoading(false);
571     
572     return fragment.release();
573 }
574
575 PassRefPtr<DocumentFragment> Editor::createFragmentForImageResourceAndAddResource(PassRefPtr<ArchiveResource> resource)
576 {
577     if (!resource)
578         return nullptr;
579
580     RefPtr<Element> imageElement = m_frame.document()->createElement(HTMLNames::imgTag, false);
581     // FIXME: The code in createFragmentAndAddResources calls setDefersLoading(true). Don't we need that here?
582     if (DocumentLoader* loader = m_frame.loader().documentLoader())
583         loader->addArchiveResource(resource.get());
584
585     NSURL *URL = resource->url();
586     imageElement->setAttribute(HTMLNames::srcAttr, [URL isFileURL] ? [URL absoluteString] : resource->url());
587
588     RefPtr<DocumentFragment> fragment = m_frame.document()->createDocumentFragment();
589     fragment->appendChild(imageElement.release());
590
591     return fragment.release();
592 }
593
594 } // namespace WebCore
595
596 #endif // PLATFORM(IOS)