1use std::cell::LazyCell;
7
8use dom_struct::dom_struct;
9use script_bindings::codegen::InheritTypes::{CharacterDataTypeId, NodeTypeId, TextTypeId};
10
11use crate::dom::bindings::cell::{DomRefCell, Ref};
12use crate::dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods;
13use crate::dom::bindings::codegen::Bindings::NodeBinding::Node_Binding::NodeMethods;
14use crate::dom::bindings::codegen::Bindings::ProcessingInstructionBinding::ProcessingInstructionMethods;
15use crate::dom::bindings::codegen::UnionTypes::NodeOrString;
16use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
17use crate::dom::bindings::inheritance::Castable;
18use crate::dom::bindings::root::{DomRoot, LayoutDom};
19use crate::dom::bindings::str::DOMString;
20use crate::dom::cdatasection::CDATASection;
21use crate::dom::comment::Comment;
22use crate::dom::document::Document;
23use crate::dom::element::Element;
24use crate::dom::mutationobserver::{Mutation, MutationObserver};
25use crate::dom::node::{ChildrenMutation, Node, NodeDamage};
26use crate::dom::processinginstruction::ProcessingInstruction;
27use crate::dom::text::Text;
28use crate::dom::virtualmethods::vtable_for;
29use crate::script_runtime::CanGc;
30
31#[dom_struct]
33pub(crate) struct CharacterData {
34 node: Node,
35 data: DomRefCell<DOMString>,
36}
37
38impl CharacterData {
39 pub(crate) fn new_inherited(data: DOMString, document: &Document) -> CharacterData {
40 CharacterData {
41 node: Node::new_inherited(document),
42 data: DomRefCell::new(data),
43 }
44 }
45
46 pub(crate) fn clone_with_data(
47 &self,
48 data: DOMString,
49 document: &Document,
50 can_gc: CanGc,
51 ) -> DomRoot<Node> {
52 match self.upcast::<Node>().type_id() {
53 NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => {
54 DomRoot::upcast(Comment::new(data, document, None, can_gc))
55 },
56 NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => {
57 let pi = self.downcast::<ProcessingInstruction>().unwrap();
58 DomRoot::upcast(ProcessingInstruction::new(
59 pi.Target(),
60 data,
61 document,
62 can_gc,
63 ))
64 },
65 NodeTypeId::CharacterData(CharacterDataTypeId::Text(TextTypeId::CDATASection)) => {
66 DomRoot::upcast(CDATASection::new(data, document, can_gc))
67 },
68 NodeTypeId::CharacterData(CharacterDataTypeId::Text(TextTypeId::Text)) => {
69 DomRoot::upcast(Text::new(data, document, can_gc))
70 },
71 _ => unreachable!(),
72 }
73 }
74
75 #[inline]
76 pub(crate) fn data(&self) -> Ref<'_, DOMString> {
77 self.data.borrow()
78 }
79
80 #[inline]
81 pub(crate) fn append_data(&self, data: &str) {
82 self.queue_mutation_record();
83 self.data.borrow_mut().push_str(data);
84 self.content_changed();
85 }
86
87 fn content_changed(&self) {
88 let node = self.upcast::<Node>();
89 node.dirty(NodeDamage::Other);
90
91 if self.is::<Text>() {
95 if let Some(parent_node) = node.GetParentNode() {
96 let mutation = ChildrenMutation::ChangeText;
97 vtable_for(&parent_node).children_changed(&mutation);
98 }
99 }
100 }
101
102 fn queue_mutation_record(&self) {
104 let mutation = LazyCell::new(|| Mutation::CharacterData {
105 old_value: self.data.borrow().clone(),
106 });
107 MutationObserver::queue_a_mutation_record(self.upcast::<Node>(), mutation);
108 }
109}
110
111impl CharacterDataMethods<crate::DomTypeHolder> for CharacterData {
112 fn Data(&self) -> DOMString {
114 self.data.borrow().clone()
115 }
116
117 fn SetData(&self, data: DOMString) {
119 self.queue_mutation_record();
120 let old_length = self.Length();
121 let new_length = data.encode_utf16().count() as u32;
122 *self.data.borrow_mut() = data;
123 self.content_changed();
124 let node = self.upcast::<Node>();
125 node.ranges()
126 .replace_code_units(node, 0, old_length, new_length);
127 }
128
129 fn Length(&self) -> u32 {
131 self.data.borrow().encode_utf16().count() as u32
132 }
133
134 fn SubstringData(&self, offset: u32, count: u32) -> Fallible<DOMString> {
136 let data = self.data.borrow();
137 let mut substring = String::new();
139 let remaining = match split_at_utf16_code_unit_offset(&data, offset) {
140 Ok((_, astral, s)) => {
141 if astral.is_some() {
145 substring += "\u{FFFD}";
146 }
147 s
148 },
149 Err(()) => return Err(Error::IndexSize),
151 };
152 match split_at_utf16_code_unit_offset(remaining, count) {
153 Err(()) => substring += remaining,
155 Ok((s, astral, _)) => {
157 substring += s;
158 if astral.is_some() {
162 substring += "\u{FFFD}";
163 }
164 },
165 };
166 Ok(DOMString::from(substring))
167 }
168
169 fn AppendData(&self, data: DOMString) {
171 self.append_data(&data);
173 }
174
175 fn InsertData(&self, offset: u32, arg: DOMString) -> ErrorResult {
177 self.ReplaceData(offset, 0, arg)
178 }
179
180 fn DeleteData(&self, offset: u32, count: u32) -> ErrorResult {
182 self.ReplaceData(offset, count, DOMString::new())
183 }
184
185 fn ReplaceData(&self, offset: u32, count: u32, arg: DOMString) -> ErrorResult {
187 let mut new_data;
188 {
189 let data = self.data.borrow();
190 let prefix;
191 let replacement_before;
192 let remaining;
193 match split_at_utf16_code_unit_offset(&data, offset) {
194 Ok((p, astral, r)) => {
195 prefix = p;
196 replacement_before = if astral.is_some() { "\u{FFFD}" } else { "" };
200 remaining = r;
201 },
202 Err(()) => return Err(Error::IndexSize),
204 };
205 let replacement_after;
206 let suffix;
207 match split_at_utf16_code_unit_offset(remaining, count) {
208 Err(()) => {
210 replacement_after = "";
211 suffix = "";
212 },
213 Ok((_, astral, s)) => {
214 replacement_after = if astral.is_some() { "\u{FFFD}" } else { "" };
218 suffix = s;
219 },
220 };
221 self.queue_mutation_record();
223
224 new_data = String::with_capacity(
226 prefix.len() +
227 replacement_before.len() +
228 arg.len() +
229 replacement_after.len() +
230 suffix.len(),
231 );
232 new_data.push_str(prefix);
233 new_data.push_str(replacement_before);
234 new_data.push_str(&arg);
235 new_data.push_str(replacement_after);
236 new_data.push_str(suffix);
237 }
238 *self.data.borrow_mut() = DOMString::from(new_data);
239 self.content_changed();
240 let node = self.upcast::<Node>();
242 node.ranges()
243 .replace_code_units(node, offset, count, arg.encode_utf16().count() as u32);
244 Ok(())
245 }
246
247 fn Before(&self, nodes: Vec<NodeOrString>, can_gc: CanGc) -> ErrorResult {
249 self.upcast::<Node>().before(nodes, can_gc)
250 }
251
252 fn After(&self, nodes: Vec<NodeOrString>, can_gc: CanGc) -> ErrorResult {
254 self.upcast::<Node>().after(nodes, can_gc)
255 }
256
257 fn ReplaceWith(&self, nodes: Vec<NodeOrString>, can_gc: CanGc) -> ErrorResult {
259 self.upcast::<Node>().replace_with(nodes, can_gc)
260 }
261
262 fn Remove(&self, can_gc: CanGc) {
264 let node = self.upcast::<Node>();
265 node.remove_self(can_gc);
266 }
267
268 fn GetPreviousElementSibling(&self) -> Option<DomRoot<Element>> {
270 self.upcast::<Node>()
271 .preceding_siblings()
272 .filter_map(DomRoot::downcast)
273 .next()
274 }
275
276 fn GetNextElementSibling(&self) -> Option<DomRoot<Element>> {
278 self.upcast::<Node>()
279 .following_siblings()
280 .filter_map(DomRoot::downcast)
281 .next()
282 }
283}
284
285pub(crate) trait LayoutCharacterDataHelpers<'dom> {
286 fn data_for_layout(self) -> &'dom str;
287}
288
289impl<'dom> LayoutCharacterDataHelpers<'dom> for LayoutDom<'dom, CharacterData> {
290 #[allow(unsafe_code)]
291 #[inline]
292 fn data_for_layout(self) -> &'dom str {
293 unsafe { self.unsafe_get().data.borrow_for_layout() }
294 }
295}
296
297fn split_at_utf16_code_unit_offset(s: &str, offset: u32) -> Result<(&str, Option<char>, &str), ()> {
312 let mut code_units = 0;
313 for (i, c) in s.char_indices() {
314 if code_units == offset {
315 let (a, b) = s.split_at(i);
316 return Ok((a, None, b));
317 }
318 code_units += 1;
319 if c > '\u{FFFF}' {
320 if code_units == offset {
321 debug_assert_eq!(c.len_utf8(), 4);
322 warn!("Splitting a surrogate pair in CharacterData API.");
323 return Ok((&s[..i], Some(c), &s[i + c.len_utf8()..]));
324 }
325 code_units += 1;
326 }
327 }
328 if code_units == offset {
329 Ok((s, None, ""))
330 } else {
331 Err(())
332 }
333}