Modernize RenderStyleConstants.h - Part 3
[WebKit-https.git] / Source / WebCore / editing / cocoa / EditorCocoa.mm
1 /*
2  * Copyright (C) 2006-2017 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 "ArchiveResource.h"
30 #import "CSSValueList.h"
31 #import "CSSValuePool.h"
32 #import "CachedResourceLoader.h"
33 #import "ColorMac.h"
34 #import "DocumentFragment.h"
35 #import "DocumentLoader.h"
36 #import "Editing.h"
37 #import "EditingStyle.h"
38 #import "EditorClient.h"
39 #import "FontCascade.h"
40 #import "Frame.h"
41 #import "FrameLoader.h"
42 #import "FrameSelection.h"
43 #import "HTMLAttachmentElement.h"
44 #import "HTMLConverter.h"
45 #import "HTMLImageElement.h"
46 #import "HTMLSpanElement.h"
47 #import "LegacyWebArchive.h"
48 #import "Pasteboard.h"
49 #import "RenderElement.h"
50 #import "RenderStyle.h"
51 #import "Text.h"
52 #import "WebContentReader.h"
53 #import "WebCoreNSURLExtras.h"
54 #import "markup.h"
55 #import <pal/spi/cocoa/NSAttributedStringSPI.h>
56 #import <pal/spi/cocoa/NSKeyedArchiverSPI.h>
57 #import <wtf/BlockObjCExceptions.h>
58
59 namespace WebCore {
60
61 void Editor::getTextDecorationAttributesRespectingTypingStyle(const RenderStyle& style, NSMutableDictionary* result) const
62 {
63     RefPtr<EditingStyle> typingStyle = m_frame.selection().typingStyle();
64     if (typingStyle && typingStyle->style()) {
65         RefPtr<CSSValue> value = typingStyle->style()->getPropertyCSSValue(CSSPropertyWebkitTextDecorationsInEffect);
66         if (value && value->isValueList()) {
67             CSSValueList& valueList = downcast<CSSValueList>(*value);
68             if (valueList.hasValue(CSSValuePool::singleton().createIdentifierValue(CSSValueLineThrough).ptr()))
69                 [result setObject:@(NSUnderlineStyleSingle) forKey:NSStrikethroughStyleAttributeName];
70             if (valueList.hasValue(CSSValuePool::singleton().createIdentifierValue(CSSValueUnderline).ptr()))
71                 [result setObject:@(NSUnderlineStyleSingle) forKey:NSUnderlineStyleAttributeName];
72         }
73     } else {
74         auto decoration = style.textDecorationsInEffect();
75         if (decoration & TextDecoration::LineThrough)
76             [result setObject:@(NSUnderlineStyleSingle) forKey:NSStrikethroughStyleAttributeName];
77         if (decoration & TextDecoration::Underline)
78             [result setObject:@(NSUnderlineStyleSingle) forKey:NSUnderlineStyleAttributeName];
79     }
80 }
81
82 RetainPtr<NSDictionary> Editor::fontAttributesForSelectionStart() const
83 {
84     Node* nodeToRemove;
85     auto* style = styleForSelectionStart(&m_frame, nodeToRemove);
86     if (!style)
87         return nil;
88
89     RetainPtr<NSMutableDictionary> attributes = adoptNS([[NSMutableDictionary alloc] init]);
90
91     if (auto ctFont = style->fontCascade().primaryFont().getCTFont())
92         [attributes setObject:(id)ctFont forKey:NSFontAttributeName];
93
94     // FIXME: Why would we not want to retrieve these attributes on iOS?
95 #if PLATFORM(MAC)
96     if (style->visitedDependentColor(CSSPropertyBackgroundColor).isVisible())
97         [attributes setObject:nsColor(style->visitedDependentColor(CSSPropertyBackgroundColor)) forKey:NSBackgroundColorAttributeName];
98
99     if (style->visitedDependentColor(CSSPropertyColor).isValid() && !Color::isBlackColor(style->visitedDependentColor(CSSPropertyColor)))
100         [attributes setObject:nsColor(style->visitedDependentColor(CSSPropertyColor)) forKey:NSForegroundColorAttributeName];
101
102     const ShadowData* shadowData = style->textShadow();
103     if (shadowData) {
104         RetainPtr<NSShadow> platformShadow = adoptNS([[NSShadow alloc] init]);
105         [platformShadow setShadowOffset:NSMakeSize(shadowData->x(), shadowData->y())];
106         [platformShadow setShadowBlurRadius:shadowData->radius()];
107         [platformShadow setShadowColor:nsColor(shadowData->color())];
108         [attributes setObject:platformShadow.get() forKey:NSShadowAttributeName];
109     }
110
111     int superscriptInt = 0;
112     switch (style->verticalAlign()) {
113     case VerticalAlign::Baseline:
114     case VerticalAlign::Bottom:
115     case VerticalAlign::BaselineMiddle:
116     case VerticalAlign::Length:
117     case VerticalAlign::Middle:
118     case VerticalAlign::TextBottom:
119     case VerticalAlign::TextTop:
120     case VerticalAlign::Top:
121         break;
122     case VerticalAlign::Sub:
123         superscriptInt = -1;
124         break;
125     case VerticalAlign::Super:
126         superscriptInt = 1;
127         break;
128     }
129     if (superscriptInt)
130         [attributes setObject:@(superscriptInt) forKey:NSSuperscriptAttributeName];
131 #endif
132
133     getTextDecorationAttributesRespectingTypingStyle(*style, attributes.get());
134
135     if (nodeToRemove)
136         nodeToRemove->remove();
137
138     return attributes;
139 }
140
141 static RefPtr<SharedBuffer> archivedDataForAttributedString(NSAttributedString *attributedString)
142 {
143     if (!attributedString.length)
144         return nullptr;
145
146     return SharedBuffer::create(securelyArchivedDataWithRootObject(attributedString));
147 }
148
149 String Editor::selectionInHTMLFormat()
150 {
151     if (auto range = selectedRange())
152         return createMarkup(*range, nullptr, AnnotateForInterchange, false, ResolveNonLocalURLs);
153     return { };
154 }
155
156 #if ENABLE(ATTACHMENT_ELEMENT)
157
158 void Editor::getPasteboardTypesAndDataForAttachment(HTMLAttachmentElement& attachment, Vector<String>& outTypes, Vector<RefPtr<SharedBuffer>>& outData)
159 {
160     auto attachmentRange = Range::create(attachment.document(), { &attachment, Position::PositionIsBeforeAnchor }, { &attachment, Position::PositionIsAfterAnchor });
161     client()->getClientPasteboardDataForRange(attachmentRange.ptr(), outTypes, outData);
162     // FIXME: We should additionally write the attachment as a web archive here, such that drag and drop within the
163     // same page doesn't destroy and recreate attachments unnecessarily. This is also needed to preserve the attachment
164     // display mode when dragging and dropping or cutting and pasting. For the time being, this is disabled because
165     // inserting attachment elements from web archive data sometimes causes attachment data to be lost; this requires
166     // further investigation.
167 }
168
169 #endif
170
171 void Editor::writeSelectionToPasteboard(Pasteboard& pasteboard)
172 {
173     NSAttributedString *attributedString = attributedStringFromRange(*selectedRange());
174
175     PasteboardWebContent content;
176     content.contentOrigin = m_frame.document()->originIdentifierForPasteboard();
177     content.canSmartCopyOrDelete = canSmartCopyOrDelete();
178     content.dataInWebArchiveFormat = selectionInWebArchiveFormat();
179     content.dataInRTFDFormat = attributedString.containsAttachments ? dataInRTFDFormat(attributedString) : nullptr;
180     content.dataInRTFFormat = dataInRTFFormat(attributedString);
181     content.dataInAttributedStringFormat = archivedDataForAttributedString(attributedString);
182     content.dataInHTMLFormat = selectionInHTMLFormat();
183     content.dataInStringFormat = stringSelectionForPasteboardWithImageAltText();
184     client()->getClientPasteboardDataForRange(selectedRange().get(), content.clientTypes, content.clientData);
185
186     pasteboard.write(content);
187 }
188
189 void Editor::writeSelection(PasteboardWriterData& pasteboardWriterData)
190 {
191     NSAttributedString *attributedString = attributedStringFromRange(*selectedRange());
192
193     PasteboardWriterData::WebContent webContent;
194     webContent.contentOrigin = m_frame.document()->originIdentifierForPasteboard();
195     webContent.canSmartCopyOrDelete = canSmartCopyOrDelete();
196     webContent.dataInWebArchiveFormat = selectionInWebArchiveFormat();
197     webContent.dataInRTFDFormat = attributedString.containsAttachments ? dataInRTFDFormat(attributedString) : nullptr;
198     webContent.dataInRTFFormat = dataInRTFFormat(attributedString);
199     webContent.dataInAttributedStringFormat = archivedDataForAttributedString(attributedString);
200     webContent.dataInHTMLFormat = selectionInHTMLFormat();
201     webContent.dataInStringFormat = stringSelectionForPasteboardWithImageAltText();
202     client()->getClientPasteboardDataForRange(selectedRange().get(), webContent.clientTypes, webContent.clientData);
203
204     pasteboardWriterData.setWebContent(WTFMove(webContent));
205 }
206
207 RefPtr<SharedBuffer> Editor::selectionInWebArchiveFormat()
208 {
209     RefPtr<LegacyWebArchive> archive = LegacyWebArchive::createFromSelection(&m_frame);
210     if (!archive)
211         return nullptr;
212     return SharedBuffer::create(archive->rawDataRepresentation().get());
213 }
214
215 // FIXME: Makes no sense that selectedTextForDataTransfer always includes alt text, but stringSelectionForPasteboard does not.
216 // This was left in a bad state when selectedTextForDataTransfer was added. Need to look over clients and fix this.
217 String Editor::stringSelectionForPasteboard()
218 {
219     if (!canCopy())
220         return emptyString();
221     String text = selectedText();
222     text.replace(noBreakSpace, ' ');
223     return text;
224 }
225
226 String Editor::stringSelectionForPasteboardWithImageAltText()
227 {
228     if (!canCopy())
229         return emptyString();
230     String text = selectedTextForDataTransfer();
231     text.replace(noBreakSpace, ' ');
232     return text;
233 }
234
235 void Editor::replaceSelectionWithAttributedString(NSAttributedString *attributedString, MailBlockquoteHandling mailBlockquoteHandling)
236 {
237     if (m_frame.selection().isNone())
238         return;
239
240     if (m_frame.selection().selection().isContentRichlyEditable()) {
241         if (auto fragment = createFragmentAndAddResources(m_frame, attributedString)) {
242             if (shouldInsertFragment(*fragment, selectedRange().get(), EditorInsertAction::Pasted))
243                 pasteAsFragment(fragment.releaseNonNull(), false, false, mailBlockquoteHandling);
244         }
245     } else {
246         String text = attributedString.string;
247         if (shouldInsertText(text, selectedRange().get(), EditorInsertAction::Pasted))
248             pasteAsPlainText(text, false);
249     }
250 }
251
252 String Editor::userVisibleString(const URL& url)
253 {
254     return WebCore::userVisibleString(url);
255 }
256
257 RefPtr<SharedBuffer> Editor::dataInRTFDFormat(NSAttributedString *string)
258 {
259     NSUInteger length = string.length;
260     if (!length)
261         return nullptr;
262
263     BEGIN_BLOCK_OBJC_EXCEPTIONS;
264     return SharedBuffer::create([string RTFDFromRange:NSMakeRange(0, length) documentAttributes:@{ }]);
265     END_BLOCK_OBJC_EXCEPTIONS;
266
267     return nullptr;
268 }
269
270 RefPtr<SharedBuffer> Editor::dataInRTFFormat(NSAttributedString *string)
271 {
272     NSUInteger length = string.length;
273     if (!length)
274         return nullptr;
275
276     BEGIN_BLOCK_OBJC_EXCEPTIONS;
277     return SharedBuffer::create([string RTFFromRange:NSMakeRange(0, length) documentAttributes:@{ }]);
278     END_BLOCK_OBJC_EXCEPTIONS;
279
280     return nullptr;
281 }
282
283 }