1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
8 * Base class for DOM Core's Comment, DocumentType, Text,
9 * CDATASection and ProcessingInstruction nodes.
12 #include "mozilla/dom/CharacterData.h"
14 #include "mozilla/DebugOnly.h"
16 #include "mozilla/AsyncEventDispatcher.h"
17 #include "mozilla/MemoryReporting.h"
18 #include "mozilla/dom/BindContext.h"
19 #include "mozilla/dom/Element.h"
20 #include "mozilla/dom/HTMLSlotElement.h"
21 #include "mozilla/dom/MutationObservers.h"
22 #include "mozilla/dom/ShadowRoot.h"
23 #include "mozilla/dom/Document.h"
24 #include "nsReadableUtils.h"
25 #include "mozilla/InternalMutationEvent.h"
27 #include "nsDOMString.h"
28 #include "nsChangeHint.h"
29 #include "nsCOMArray.h"
30 #include "mozilla/dom/DirectionalityUtils.h"
31 #include "nsCCUncollectableMarker.h"
32 #include "mozAutoDocUpdate.h"
33 #include "nsIContentInlines.h"
34 #include "nsTextNode.h"
35 #include "nsBidiUtils.h"
36 #include "PLDHashTable.h"
37 #include "mozilla/Sprintf.h"
38 #include "nsWindowSizes.h"
39 #include "nsWrapperCacheInlines.h"
41 #if defined(ACCESSIBILITY) && defined(DEBUG)
42 # include "nsAccessibilityService.h"
45 namespace mozilla::dom
{
47 CharacterData::CharacterData(already_AddRefed
<dom::NodeInfo
>&& aNodeInfo
)
48 : nsIContent(std::move(aNodeInfo
)) {
49 MOZ_ASSERT(mNodeInfo
->NodeType() == TEXT_NODE
||
50 mNodeInfo
->NodeType() == CDATA_SECTION_NODE
||
51 mNodeInfo
->NodeType() == COMMENT_NODE
||
52 mNodeInfo
->NodeType() == PROCESSING_INSTRUCTION_NODE
||
53 mNodeInfo
->NodeType() == DOCUMENT_TYPE_NODE
,
54 "Bad NodeType in aNodeInfo");
57 CharacterData::~CharacterData() {
58 MOZ_ASSERT(!IsInUncomposedDoc(),
59 "Please remove this from the document properly");
65 Element
* CharacterData::GetNameSpaceElement() {
66 return Element::FromNodeOrNull(GetParentNode());
69 NS_IMPL_CYCLE_COLLECTION_CLASS(CharacterData
)
71 NS_IMPL_CYCLE_COLLECTION_TRACE_WRAPPERCACHE(CharacterData
)
73 NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_BEGIN(CharacterData
)
74 return Element::CanSkip(tmp
, aRemovingAllowed
);
75 NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_END
77 NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_IN_CC_BEGIN(CharacterData
)
78 return Element::CanSkipInCC(tmp
);
79 NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_IN_CC_END
81 NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_THIS_BEGIN(CharacterData
)
82 return Element::CanSkipThis(tmp
);
83 NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_THIS_END
85 // We purposefully don't TRAVERSE_BEGIN_INHERITED here. All the bits
86 // we should traverse should be added here or in nsINode::Traverse.
87 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INTERNAL(CharacterData
)
88 if (MOZ_UNLIKELY(cb
.WantDebugInfo())) {
90 SprintfLiteral(name
, "CharacterData (len=%d)", tmp
->mText
.GetLength());
91 cb
.DescribeRefCountedNode(tmp
->mRefCnt
.get(), name
);
93 NS_IMPL_CYCLE_COLLECTION_DESCRIBE(CharacterData
, tmp
->mRefCnt
.get())
96 if (!nsIContent::Traverse(tmp
, cb
)) {
97 return NS_SUCCESS_INTERRUPTED_TRAVERSE
;
99 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
101 // We purposefully don't UNLINK_BEGIN_INHERITED here.
102 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(CharacterData
)
103 nsIContent::Unlink(tmp
);
105 if (nsContentSlots
* slots
= tmp
->GetExistingContentSlots()) {
108 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
110 NS_INTERFACE_MAP_BEGIN(CharacterData
)
111 NS_INTERFACE_MAP_ENTRIES_CYCLE_COLLECTION(CharacterData
)
112 NS_INTERFACE_MAP_END_INHERITING(nsIContent
)
114 void CharacterData::GetNodeValueInternal(nsAString
& aNodeValue
) {
118 void CharacterData::SetNodeValueInternal(const nsAString
& aNodeValue
,
119 ErrorResult
& aError
) {
120 aError
= SetTextInternal(0, mText
.GetLength(), aNodeValue
.BeginReading(),
121 aNodeValue
.Length(), true);
124 //----------------------------------------------------------------------
126 // Implementation of CharacterData
128 void CharacterData::SetTextContentInternal(const nsAString
& aTextContent
,
129 nsIPrincipal
* aSubjectPrincipal
,
130 ErrorResult
& aError
) {
131 // Batch possible DOMSubtreeModified events.
132 mozAutoSubtreeModified
subtree(OwnerDoc(), nullptr);
133 return SetNodeValue(aTextContent
, aError
);
136 void CharacterData::GetData(nsAString
& aData
) const {
139 mText
.AppendTo(aData
);
141 // Must use Substring() since nsDependentCString() requires null
142 // terminated strings.
144 const char* data
= mText
.Get1b();
147 CopyASCIItoUTF16(Substring(data
, data
+ mText
.GetLength()), aData
);
154 void CharacterData::SetData(const nsAString
& aData
, ErrorResult
& aRv
) {
155 nsresult rv
= SetTextInternal(0, mText
.GetLength(), aData
.BeginReading(),
156 aData
.Length(), true);
162 void CharacterData::SubstringData(uint32_t aStart
, uint32_t aCount
,
163 nsAString
& aReturn
, ErrorResult
& rv
) {
166 uint32_t textLength
= mText
.GetLength();
167 if (aStart
> textLength
) {
168 rv
.Throw(NS_ERROR_DOM_INDEX_SIZE_ERR
);
172 uint32_t amount
= aCount
;
173 if (amount
> textLength
- aStart
) {
174 amount
= textLength
- aStart
;
178 aReturn
.Assign(mText
.Get2b() + aStart
, amount
);
180 // Must use Substring() since nsDependentCString() requires null
181 // terminated strings.
183 const char* data
= mText
.Get1b() + aStart
;
184 CopyASCIItoUTF16(Substring(data
, data
+ amount
), aReturn
);
188 //----------------------------------------------------------------------
190 void CharacterData::AppendData(const nsAString
& aData
, ErrorResult
& aRv
) {
191 InsertData(mText
.GetLength(), aData
, aRv
);
194 void CharacterData::InsertData(uint32_t aOffset
, const nsAString
& aData
,
197 SetTextInternal(aOffset
, 0, aData
.BeginReading(), aData
.Length(), true);
203 void CharacterData::DeleteData(uint32_t aOffset
, uint32_t aCount
,
205 nsresult rv
= SetTextInternal(aOffset
, aCount
, nullptr, 0, true);
211 void CharacterData::ReplaceData(uint32_t aOffset
, uint32_t aCount
,
212 const nsAString
& aData
, ErrorResult
& aRv
) {
213 nsresult rv
= SetTextInternal(aOffset
, aCount
, aData
.BeginReading(),
214 aData
.Length(), true);
220 nsresult
CharacterData::SetTextInternal(
221 uint32_t aOffset
, uint32_t aCount
, const char16_t
* aBuffer
,
222 uint32_t aLength
, bool aNotify
,
223 CharacterDataChangeInfo::Details
* aDetails
) {
224 MOZ_ASSERT(aBuffer
|| !aLength
, "Null buffer passed to SetTextInternal!");
226 // sanitize arguments
227 uint32_t textLength
= mText
.GetLength();
228 if (aOffset
> textLength
) {
229 return NS_ERROR_DOM_INDEX_SIZE_ERR
;
232 if (aCount
> textLength
- aOffset
) {
233 aCount
= textLength
- aOffset
;
236 uint32_t endOffset
= aOffset
+ aCount
;
238 // Make sure the text fragment can hold the new data.
239 if (aLength
> aCount
&& !mText
.CanGrowBy(aLength
- aCount
)) {
240 return NS_ERROR_OUT_OF_MEMORY
;
243 Document
* document
= GetComposedDoc();
244 mozAutoDocUpdate
updateBatch(document
, aNotify
);
246 bool haveMutationListeners
=
247 aNotify
&& nsContentUtils::HasMutationListeners(
248 this, NS_EVENT_BITS_MUTATION_CHARACTERDATAMODIFIED
, this);
250 RefPtr
<nsAtom
> oldValue
;
251 if (haveMutationListeners
) {
252 oldValue
= GetCurrentValueAtom();
256 CharacterDataChangeInfo info
= {aOffset
== textLength
, aOffset
, endOffset
,
258 MutationObservers::NotifyCharacterDataWillChange(this, info
);
261 Directionality oldDir
= eDir_NotSet
;
262 bool dirAffectsAncestor
=
263 (NodeType() == TEXT_NODE
&&
264 TextNodeWillChangeDirection(static_cast<nsTextNode
*>(this), &oldDir
,
267 if (aOffset
== 0 && endOffset
== textLength
) {
268 // Replacing whole text or old text was empty. Don't bother to check for
269 // bidi in this string if the document already has bidi enabled.
270 // If this is marked as "maybe modified frequently", the text should be
271 // stored as char16_t since converting char* to char16_t* is expensive.
273 mText
.SetTo(aBuffer
, aLength
, !document
|| !document
->GetBidiEnabled(),
274 HasFlag(NS_MAYBE_MODIFIED_FREQUENTLY
));
275 NS_ENSURE_TRUE(ok
, NS_ERROR_OUT_OF_MEMORY
);
276 } else if (aOffset
== textLength
) {
277 // Appending to existing
279 mText
.Append(aBuffer
, aLength
, !document
|| !document
->GetBidiEnabled(),
280 HasFlag(NS_MAYBE_MODIFIED_FREQUENTLY
));
281 NS_ENSURE_TRUE(ok
, NS_ERROR_OUT_OF_MEMORY
);
283 // Merging old and new
285 bool bidi
= mText
.IsBidi();
287 // Allocate new buffer
288 int32_t newLength
= textLength
- aCount
+ aLength
;
289 // Use nsString and not nsAutoString so that we get a nsStringBuffer which
290 // can be just AddRefed in nsTextFragment.
292 to
.SetCapacity(newLength
);
294 // Copy over appropriate data
296 mText
.AppendTo(to
, 0, aOffset
);
299 to
.Append(aBuffer
, aLength
);
300 if (!bidi
&& (!document
|| !document
->GetBidiEnabled())) {
301 bidi
= HasRTLChars(Span(aBuffer
, aLength
));
304 if (endOffset
!= textLength
) {
305 mText
.AppendTo(to
, endOffset
, textLength
- endOffset
);
308 // If this is marked as "maybe modified frequently", the text should be
309 // stored as char16_t since converting char* to char16_t* is expensive.
310 // Use char16_t also when we have bidi characters.
311 bool use2b
= HasFlag(NS_MAYBE_MODIFIED_FREQUENTLY
) || bidi
;
312 bool ok
= mText
.SetTo(to
, false, use2b
);
315 NS_ENSURE_TRUE(ok
, NS_ERROR_OUT_OF_MEMORY
);
318 UnsetFlags(NS_CACHED_TEXT_IS_ONLY_WHITESPACE
);
320 if (document
&& mText
.IsBidi()) {
321 // If we found bidi characters in mText.SetTo() above, indicate that the
322 // document contains bidi characters.
323 document
->SetBidiEnabled();
326 if (dirAffectsAncestor
) {
327 // dirAffectsAncestor being true implies that we have a text node, see
329 MOZ_ASSERT(NodeType() == TEXT_NODE
);
330 TextNodeChangedDirection(static_cast<nsTextNode
*>(this), oldDir
, aNotify
);
335 CharacterDataChangeInfo info
= {aOffset
== textLength
, aOffset
, endOffset
,
337 MutationObservers::NotifyCharacterDataChanged(this, info
);
339 if (haveMutationListeners
) {
340 InternalMutationEvent
mutation(true, eLegacyCharacterDataModified
);
342 mutation
.mPrevAttrValue
= oldValue
;
346 mutation
.mNewAttrValue
= NS_Atomize(val
);
349 mozAutoSubtreeModified
subtree(OwnerDoc(), this);
350 (new AsyncEventDispatcher(this, mutation
))->RunDOMEventWhenSafe();
357 //----------------------------------------------------------------------
359 // Implementation of nsIContent
362 void CharacterData::ToCString(nsAString
& aBuf
, int32_t aOffset
,
363 int32_t aLen
) const {
365 const char16_t
* cp
= mText
.Get2b() + aOffset
;
366 const char16_t
* end
= cp
+ aLen
;
371 aBuf
.AppendLiteral("&");
372 } else if (ch
== '<') {
373 aBuf
.AppendLiteral("<");
374 } else if (ch
== '>') {
375 aBuf
.AppendLiteral(">");
376 } else if ((ch
< ' ') || (ch
>= 127)) {
377 aBuf
.AppendPrintf("\\u%04x", ch
);
383 unsigned char* cp
= (unsigned char*)mText
.Get1b() + aOffset
;
384 const unsigned char* end
= cp
+ aLen
;
389 aBuf
.AppendLiteral("&");
390 } else if (ch
== '<') {
391 aBuf
.AppendLiteral("<");
392 } else if (ch
== '>') {
393 aBuf
.AppendLiteral(">");
394 } else if ((ch
< ' ') || (ch
>= 127)) {
395 aBuf
.AppendPrintf("\\u%04x", ch
);
404 nsresult
CharacterData::BindToTree(BindContext
& aContext
, nsINode
& aParent
) {
405 MOZ_ASSERT(aParent
.IsContent() || aParent
.IsDocument(),
406 "Must have content or document parent!");
407 MOZ_ASSERT(aParent
.OwnerDoc() == OwnerDoc(),
408 "Must have the same owner document");
409 MOZ_ASSERT(OwnerDoc() == &aContext
.OwnerDoc(), "These should match too");
410 MOZ_ASSERT(!IsInUncomposedDoc(), "Already have a document. Unbind first!");
411 MOZ_ASSERT(!IsInComposedDoc(), "Already have a document. Unbind first!");
412 // Note that as we recurse into the kids, they'll have a non-null parent. So
413 // only assert if our parent is _changing_ while we have a parent.
414 MOZ_ASSERT(!GetParentNode() || &aParent
== GetParentNode(),
415 "Already have a parent. Unbind first!");
417 const bool hadParent
= !!GetParentNode();
419 if (aParent
.IsInNativeAnonymousSubtree()) {
420 SetFlags(NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE
);
422 if (aParent
.HasFlag(NODE_HAS_BEEN_IN_UA_WIDGET
)) {
423 SetFlags(NODE_HAS_BEEN_IN_UA_WIDGET
);
425 if (IsRootOfNativeAnonymousSubtree()) {
426 aParent
.SetMayHaveAnonymousChildren();
431 if (!hadParent
&& aParent
.IsContent()) {
432 SetParentIsContent(true);
435 MOZ_ASSERT(!!GetParent() == aParent
.IsContent());
437 if (aParent
.IsInUncomposedDoc() || aParent
.IsInShadowTree()) {
438 // We no longer need to track the subtree pointer (and in fact we'll assert
439 // if we do this any later).
440 ClearSubtreeRootPointer();
441 SetIsConnected(aParent
.IsInComposedDoc());
443 if (aParent
.IsInUncomposedDoc()) {
446 SetFlags(NODE_IS_IN_SHADOW_TREE
);
447 MOZ_ASSERT(aParent
.IsContent() &&
448 aParent
.AsContent()->GetContainingShadow());
449 ExtendedContentSlots()->mContainingShadow
=
450 aParent
.AsContent()->GetContainingShadow();
453 if (IsInComposedDoc() && mText
.IsBidi()) {
454 aContext
.OwnerDoc().SetBidiEnabled();
457 // Clear the lazy frame construction bits.
458 UnsetFlags(NODE_NEEDS_FRAME
| NODE_DESCENDANTS_NEED_FRAMES
);
460 // If we're not in the doc and not in a shadow tree,
461 // update our subtree pointer.
462 SetSubtreeRootPointer(aParent
.SubtreeRoot());
465 MutationObservers::NotifyParentChainChanged(this);
466 if (!hadParent
&& IsRootOfNativeAnonymousSubtree()) {
467 MutationObservers::NotifyNativeAnonymousChildListChange(this, false);
470 UpdateEditableState(false);
472 // Ensure we only do these once, in the case we move the shadow host around.
473 if (aContext
.SubtreeRootChanges()) {
474 HandleShadowDOMRelatedInsertionSteps(hadParent
);
477 MOZ_ASSERT(OwnerDoc() == aParent
.OwnerDoc(), "Bound to wrong document");
478 MOZ_ASSERT(IsInComposedDoc() == aContext
.InComposedDoc());
479 MOZ_ASSERT(IsInUncomposedDoc() == aContext
.InUncomposedDoc());
480 MOZ_ASSERT(&aParent
== GetParentNode(), "Bound to wrong parent node");
481 MOZ_ASSERT(aParent
.IsInUncomposedDoc() == IsInUncomposedDoc());
482 MOZ_ASSERT(aParent
.IsInComposedDoc() == IsInComposedDoc());
483 MOZ_ASSERT(aParent
.IsInShadowTree() == IsInShadowTree());
484 MOZ_ASSERT(aParent
.SubtreeRoot() == SubtreeRoot());
488 void CharacterData::UnbindFromTree(bool aNullParent
) {
489 // Unset frame flags; if we need them again later, they'll get set again.
490 UnsetFlags(NS_CREATE_FRAME_IF_NON_WHITESPACE
| NS_REFRAME_IF_WHITESPACE
);
492 HandleShadowDOMRelatedRemovalSteps(aNullParent
);
495 if (IsRootOfNativeAnonymousSubtree()) {
496 MutationObservers::NotifyNativeAnonymousChildListChange(this, true);
503 SetParentIsContent(false);
506 SetIsConnected(false);
508 if (aNullParent
|| !mParent
->IsInShadowTree()) {
509 UnsetFlags(NODE_IS_IN_SHADOW_TREE
);
511 // Begin keeping track of our subtree root.
512 SetSubtreeRootPointer(aNullParent
? this : mParent
->SubtreeRoot());
515 if (nsExtendedContentSlots
* slots
= GetExistingExtendedContentSlots()) {
516 if (aNullParent
|| !mParent
->IsInShadowTree()) {
517 slots
->mContainingShadow
= nullptr;
521 MutationObservers::NotifyParentChainChanged(this);
523 #if defined(ACCESSIBILITY) && defined(DEBUG)
524 MOZ_ASSERT(!GetAccService() || !GetAccService()->HasAccessible(this),
525 "An accessible for this element still exists!");
529 //----------------------------------------------------------------------
531 // Implementation of the nsIContent interface text functions
533 nsresult
CharacterData::SetText(const char16_t
* aBuffer
, uint32_t aLength
,
535 return SetTextInternal(0, mText
.GetLength(), aBuffer
, aLength
, aNotify
);
538 nsresult
CharacterData::AppendText(const char16_t
* aBuffer
, uint32_t aLength
,
540 return SetTextInternal(mText
.GetLength(), 0, aBuffer
, aLength
, aNotify
);
543 bool CharacterData::TextIsOnlyWhitespace() {
544 MOZ_ASSERT(NS_IsMainThread());
545 if (!ThreadSafeTextIsOnlyWhitespace()) {
546 UnsetFlags(NS_TEXT_IS_ONLY_WHITESPACE
);
547 SetFlags(NS_CACHED_TEXT_IS_ONLY_WHITESPACE
);
551 SetFlags(NS_CACHED_TEXT_IS_ONLY_WHITESPACE
| NS_TEXT_IS_ONLY_WHITESPACE
);
555 bool CharacterData::ThreadSafeTextIsOnlyWhitespace() const {
556 // FIXME: should this method take content language into account?
558 // The fragment contains non-8bit characters and such characters
559 // are never considered whitespace.
561 // FIXME(emilio): This is not quite true in presence of the
562 // NS_MAYBE_MODIFIED_FREQUENTLY flag... But looks like we only set that on
563 // anonymous nodes, so should be fine...
567 if (HasFlag(NS_CACHED_TEXT_IS_ONLY_WHITESPACE
)) {
568 return HasFlag(NS_TEXT_IS_ONLY_WHITESPACE
);
571 const char* cp
= mText
.Get1b();
572 const char* end
= cp
+ mText
.GetLength();
577 // NOTE(emilio): If you ever change the definition of "whitespace" here, you
578 // need to change it too in RestyleManager::CharacterDataChanged.
579 if (!dom::IsSpaceCharacter(ch
)) {
589 already_AddRefed
<nsAtom
> CharacterData::GetCurrentValueAtom() {
592 return NS_Atomize(val
);
595 void CharacterData::AddSizeOfExcludingThis(nsWindowSizes
& aSizes
,
596 size_t* aNodeSize
) const {
597 nsIContent::AddSizeOfExcludingThis(aSizes
, aNodeSize
);
598 *aNodeSize
+= mText
.SizeOfExcludingThis(aSizes
.mState
.mMallocSizeOf
);
601 } // namespace mozilla::dom