1/*
2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * Copyright (C) 2003-2018 Apple Inc. All rights reserved.
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Library General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Library General Public License for more details.
15 *
16 * You should have received a copy of the GNU Library General Public License
17 * along with this library; see the file COPYING.LIB. If not, write to
18 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19 * Boston, MA 02110-1301, USA.
20 */
21
22#include "config.h"
23#include "CharacterData.h"
24
25#include "Attr.h"
26#include "ElementTraversal.h"
27#include "EventNames.h"
28#include "FrameSelection.h"
29#include "InspectorInstrumentation.h"
30#include "MutationEvent.h"
31#include "MutationObserverInterestGroup.h"
32#include "MutationRecord.h"
33#include "ProcessingInstruction.h"
34#include "RenderText.h"
35#include "StyleInheritedData.h"
36#include <unicode/ubrk.h>
37#include <wtf/IsoMallocInlines.h>
38#include <wtf/Ref.h>
39
40namespace WebCore {
41
42WTF_MAKE_ISO_ALLOCATED_IMPL(CharacterData);
43
44static bool canUseSetDataOptimization(const CharacterData& node)
45{
46 auto& document = node.document();
47 return !document.hasListenerType(Document::DOMCHARACTERDATAMODIFIED_LISTENER) && !document.hasMutationObserversOfType(MutationObserver::CharacterData)
48 && !document.hasListenerType(Document::DOMSUBTREEMODIFIED_LISTENER);
49}
50
51void CharacterData::setData(const String& data)
52{
53 const String& nonNullData = !data.isNull() ? data : emptyString();
54 unsigned oldLength = length();
55
56 if (m_data == nonNullData && canUseSetDataOptimization(*this)) {
57 document().textRemoved(*this, 0, oldLength);
58 if (document().frame())
59 document().frame()->selection().textWasReplaced(this, 0, oldLength, oldLength);
60 return;
61 }
62
63 Ref<CharacterData> protectedThis(*this);
64
65 setDataAndUpdate(nonNullData, 0, oldLength, nonNullData.length());
66 document().textRemoved(*this, 0, oldLength);
67}
68
69ExceptionOr<String> CharacterData::substringData(unsigned offset, unsigned count)
70{
71 if (offset > length())
72 return Exception { IndexSizeError };
73
74 return m_data.substring(offset, count);
75}
76
77unsigned CharacterData::parserAppendData(const String& string, unsigned offset, unsigned lengthLimit)
78{
79 unsigned oldLength = m_data.length();
80
81 ASSERT(lengthLimit >= oldLength);
82
83 unsigned characterLength = string.length() - offset;
84 unsigned characterLengthLimit = std::min(characterLength, lengthLimit - oldLength);
85
86 // Check that we are not on an unbreakable boundary.
87 // Some text break iterator implementations work best if the passed buffer is as small as possible,
88 // see <https://bugs.webkit.org/show_bug.cgi?id=29092>.
89 // We need at least two characters look-ahead to account for UTF-16 surrogates.
90 if (characterLengthLimit < characterLength) {
91 NonSharedCharacterBreakIterator it(StringView(string).substring(offset, (characterLengthLimit + 2 > characterLength) ? characterLength : characterLengthLimit + 2));
92 if (!ubrk_isBoundary(it, characterLengthLimit))
93 characterLengthLimit = ubrk_preceding(it, characterLengthLimit);
94 }
95
96 if (!characterLengthLimit)
97 return 0;
98
99 String oldData = m_data;
100 if (string.is8Bit())
101 m_data.append(string.characters8() + offset, characterLengthLimit);
102 else
103 m_data.append(string.characters16() + offset, characterLengthLimit);
104
105 ASSERT(!renderer() || is<Text>(*this));
106 if (is<Text>(*this) && parentNode())
107 downcast<Text>(*this).updateRendererAfterContentChange(oldLength, 0);
108
109 notifyParentAfterChange(ContainerNode::ChildChangeSource::Parser);
110
111 auto mutationRecipients = MutationObserverInterestGroup::createForCharacterDataMutation(*this);
112 if (UNLIKELY(mutationRecipients))
113 mutationRecipients->enqueueMutationRecord(MutationRecord::createCharacterData(*this, oldData));
114
115 return characterLengthLimit;
116}
117
118void CharacterData::appendData(const String& data)
119{
120 String newStr = m_data;
121 newStr.append(data);
122
123 setDataAndUpdate(newStr, m_data.length(), 0, data.length());
124
125 // FIXME: Should we call textInserted here?
126}
127
128ExceptionOr<void> CharacterData::insertData(unsigned offset, const String& data)
129{
130 if (offset > length())
131 return Exception { IndexSizeError };
132
133 String newStr = m_data;
134 newStr.insert(data, offset);
135
136 setDataAndUpdate(newStr, offset, 0, data.length());
137
138 document().textInserted(*this, offset, data.length());
139
140 return { };
141}
142
143ExceptionOr<void> CharacterData::deleteData(unsigned offset, unsigned count)
144{
145 if (offset > length())
146 return Exception { IndexSizeError };
147
148 count = std::min(count, length() - offset);
149
150 String newStr = m_data;
151 newStr.remove(offset, count);
152
153 setDataAndUpdate(newStr, offset, count, 0);
154
155 document().textRemoved(*this, offset, count);
156
157 return { };
158}
159
160ExceptionOr<void> CharacterData::replaceData(unsigned offset, unsigned count, const String& data)
161{
162 if (offset > length())
163 return Exception { IndexSizeError };
164
165 count = std::min(count, length() - offset);
166
167 String newStr = m_data;
168 newStr.remove(offset, count);
169 newStr.insert(data, offset);
170
171 setDataAndUpdate(newStr, offset, count, data.length());
172
173 // update the markers for spell checking and grammar checking
174 document().textRemoved(*this, offset, count);
175 document().textInserted(*this, offset, data.length());
176
177 return { };
178}
179
180String CharacterData::nodeValue() const
181{
182 return m_data;
183}
184
185ExceptionOr<void> CharacterData::setNodeValue(const String& nodeValue)
186{
187 setData(nodeValue);
188 return { };
189}
190
191void CharacterData::setDataAndUpdate(const String& newData, unsigned offsetOfReplacedData, unsigned oldLength, unsigned newLength)
192{
193 String oldData = m_data;
194 m_data = newData;
195
196 ASSERT(!renderer() || is<Text>(*this));
197 if (is<Text>(*this) && parentNode())
198 downcast<Text>(*this).updateRendererAfterContentChange(offsetOfReplacedData, oldLength);
199
200 if (is<ProcessingInstruction>(*this))
201 downcast<ProcessingInstruction>(*this).checkStyleSheet();
202
203 if (document().frame())
204 document().frame()->selection().textWasReplaced(this, offsetOfReplacedData, oldLength, newLength);
205
206 notifyParentAfterChange(ContainerNode::ChildChangeSource::API);
207
208 dispatchModifiedEvent(oldData);
209}
210
211void CharacterData::notifyParentAfterChange(ContainerNode::ChildChangeSource source)
212{
213 document().incDOMTreeVersion();
214
215 if (!parentNode())
216 return;
217
218 ContainerNode::ChildChange change = {
219 ContainerNode::TextChanged,
220 ElementTraversal::previousSibling(*this),
221 ElementTraversal::nextSibling(*this),
222 source
223 };
224
225 parentNode()->childrenChanged(change);
226}
227
228void CharacterData::dispatchModifiedEvent(const String& oldData)
229{
230 if (auto mutationRecipients = MutationObserverInterestGroup::createForCharacterDataMutation(*this))
231 mutationRecipients->enqueueMutationRecord(MutationRecord::createCharacterData(*this, oldData));
232
233 if (!isInShadowTree()) {
234 if (document().hasListenerType(Document::DOMCHARACTERDATAMODIFIED_LISTENER))
235 dispatchScopedEvent(MutationEvent::create(eventNames().DOMCharacterDataModifiedEvent, Event::CanBubble::Yes, nullptr, oldData, m_data));
236 dispatchSubtreeModifiedEvent();
237 }
238
239 InspectorInstrumentation::characterDataModified(document(), *this);
240}
241
242int CharacterData::maxCharacterOffset() const
243{
244 return static_cast<int>(length());
245}
246
247} // namespace WebCore
248