1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! A safe wrapper for DOM nodes that prevents layout from mutating the DOM, from letting DOM nodes
//! escape, and from generally doing anything that it isn't supposed to. This is accomplished via
//! a simple whitelist of allowed operations, along with some lifetime magic to prevent nodes from
//! escaping.
//!
//! As a security wrapper is only as good as its whitelist, be careful when adding operations to
//! this list. The cardinal rules are:
//!
//! 1. Layout is not allowed to mutate the DOM.
//!
//! 2. Layout is not allowed to see anything with `LayoutJS` in the name, because it could hang
//! onto these objects and cause use-after-free.
//!
//! When implementing wrapper functions, be careful that you do not touch the borrow flags, or you
//! will race and cause spurious task failure. (Note that I do not believe these races are
//! exploitable, but they'll result in brokenness nonetheless.)
//!
//! Rules of the road for this file:
//!
//! * You must not use `.get()`; instead, use `.unsafe_get()`.
//!
//! * Do not call any methods on DOM nodes without checking to see whether they use borrow flags.
//!
//! o Instead of `get_attr()`, use `.get_attr_val_for_layout()`.
//!
//! o Instead of `html_element_in_html_document()`, use
//! `html_element_in_html_document_for_layout()`.
#![allow(unsafe_blocks)]
use canvas::canvas_paint_task::CanvasMsg;
use context::SharedLayoutContext;
use css::node_style::StyledNode;
use incremental::RestyleDamage;
use util::{LayoutDataAccess, LayoutDataFlags, LayoutDataWrapper, OpaqueNodeMethods};
use util::{PrivateLayoutData};
use cssparser::RGBA;
use gfx::display_list::OpaqueNode;
use script::dom::bindings::codegen::InheritTypes::{ElementCast, HTMLIFrameElementCast};
use script::dom::bindings::codegen::InheritTypes::{HTMLCanvasElementCast, HTMLImageElementCast};
use script::dom::bindings::codegen::InheritTypes::{HTMLInputElementCast, HTMLTextAreaElementCast};
use script::dom::bindings::codegen::InheritTypes::{NodeCast, TextCast};
use script::dom::bindings::js::LayoutJS;
use script::dom::element::{Element, ElementTypeId};
use script::dom::element::{LayoutElementHelpers, RawLayoutElementHelpers};
use script::dom::htmlelement::HTMLElementTypeId;
use script::dom::htmlcanvaselement::{HTMLCanvasElement, LayoutHTMLCanvasElementHelpers};
use script::dom::htmliframeelement::HTMLIFrameElement;
use script::dom::htmlimageelement::LayoutHTMLImageElementHelpers;
use script::dom::htmlinputelement::{HTMLInputElement, LayoutHTMLInputElementHelpers};
use script::dom::htmltextareaelement::{HTMLTextAreaElement, LayoutHTMLTextAreaElementHelpers};
use script::dom::node::{Node, NodeTypeId};
use script::dom::node::{LayoutNodeHelpers, RawLayoutNodeHelpers, SharedLayoutData};
use script::dom::node::{HAS_CHANGED, IS_DIRTY, HAS_DIRTY_SIBLINGS, HAS_DIRTY_DESCENDANTS};
use script::dom::text::Text;
use script::layout_interface::LayoutChan;
use msg::constellation_msg::{PipelineId, SubpageId};
use servo_util::str::{LengthOrPercentageOrAuto, is_whitespace};
use std::borrow::ToOwned;
use std::cell::{Ref, RefMut};
use std::marker::ContravariantLifetime;
use std::mem;
use std::sync::mpsc::Sender;
use string_cache::{Atom, Namespace};
use style::computed_values::{content, display, white_space};
use selectors::parser::{NamespaceConstraint, AttrSelector};
use style::legacy::{LengthAttribute, SimpleColorAttribute, UnsignedIntegerAttribute, IntegerAttribute};
use style::node::{TElement, TElementAttributes, TNode};
use style::properties::PropertyDeclarationBlock;
use url::Url;
/// Allows some convenience methods on generic layout nodes.
pub trait TLayoutNode {
/// Creates a new layout node with the same lifetime as this layout node.
unsafe fn new_with_this_lifetime(&self, node: &LayoutJS<Node>) -> Self;
/// Returns the type ID of this node. Fails if this node is borrowed mutably. Returns `None`
/// if this is a pseudo-element; otherwise, returns `Some`.
fn type_id(&self) -> Option<NodeTypeId>;
/// Returns the interior of this node as a `LayoutJS`. This is highly unsafe for layout to
/// call and as such is marked `unsafe`.
unsafe fn get_jsmanaged<'a>(&'a self) -> &'a LayoutJS<Node>;
/// Returns the interior of this node as a `Node`. This is highly unsafe for layout to call
/// and as such is marked `unsafe`.
unsafe fn get<'a>(&'a self) -> &'a Node {
&*self.get_jsmanaged().unsafe_get()
}
fn node_is_element(&self) -> bool {
match self.type_id() {
Some(NodeTypeId::Element(..)) => true,
_ => false
}
}
fn node_is_document(&self) -> bool {
match self.type_id() {
Some(NodeTypeId::Document(..)) => true,
_ => false
}
}
/// If this is an image element, returns its URL. If this is not an image element, fails.
///
/// FIXME(pcwalton): Don't copy URLs.
fn image_url(&self) -> Option<Url> {
unsafe {
match HTMLImageElementCast::to_layout_js(self.get_jsmanaged()) {
Some(elem) => elem.image().as_ref().map(|url| (*url).clone()),
None => panic!("not an image!")
}
}
}
fn get_renderer(&self) -> Option<Sender<CanvasMsg>> {
unsafe {
let canvas_element: Option<LayoutJS<HTMLCanvasElement>> = HTMLCanvasElementCast::to_layout_js(self.get_jsmanaged());
canvas_element.and_then(|elem| elem.get_renderer())
}
}
fn get_canvas_width(&self) -> u32 {
unsafe {
let canvas_element: Option<LayoutJS<HTMLCanvasElement>> = HTMLCanvasElementCast::to_layout_js(self.get_jsmanaged());
canvas_element.unwrap().get_canvas_width()
}
}
fn get_canvas_height(&self) -> u32 {
unsafe {
let canvas_element: Option<LayoutJS<HTMLCanvasElement>> = HTMLCanvasElementCast::to_layout_js(self.get_jsmanaged());
canvas_element.unwrap().get_canvas_height()
}
}
/// If this node is an iframe element, returns its pipeline and subpage IDs. If this node is
/// not an iframe element, fails.
fn iframe_pipeline_and_subpage_ids(&self) -> (PipelineId, SubpageId) {
unsafe {
let iframe_element: LayoutJS<HTMLIFrameElement> =
match HTMLIFrameElementCast::to_layout_js(self.get_jsmanaged()) {
Some(elem) => elem,
None => panic!("not an iframe element!")
};
((*iframe_element.unsafe_get()).containing_page_pipeline_id().unwrap(),
(*iframe_element.unsafe_get()).subpage_id().unwrap())
}
}
/// If this is a text node, copies out the text. If this is not a text node, fails.
///
/// FIXME(pcwalton): Don't copy text. Atomically reference count instead.
fn text(&self) -> String;
/// Returns the first child of this node.
fn first_child(&self) -> Option<Self>;
}
/// A wrapper so that layout can access only the methods that it should have access to. Layout must
/// only ever see these and must never see instances of `LayoutJS`.
#[derive(Copy)]
pub struct LayoutNode<'a> {
/// The wrapped node.
node: LayoutJS<Node>,
/// Being chained to a ContravariantLifetime prevents `LayoutNode`s from escaping.
pub chain: ContravariantLifetime<'a>,
}
impl<'ln> Clone for LayoutNode<'ln> {
fn clone(&self) -> LayoutNode<'ln> {
LayoutNode {
node: self.node.clone(),
chain: self.chain,
}
}
}
impl<'a> PartialEq for LayoutNode<'a> {
#[inline]
fn eq(&self, other: &LayoutNode) -> bool {
self.node == other.node
}
}
impl<'ln> TLayoutNode for LayoutNode<'ln> {
unsafe fn new_with_this_lifetime(&self, node: &LayoutJS<Node>) -> LayoutNode<'ln> {
LayoutNode {
node: node.transmute_copy(),
chain: self.chain,
}
}
fn type_id(&self) -> Option<NodeTypeId> {
unsafe {
Some(self.node.type_id_for_layout())
}
}
unsafe fn get_jsmanaged<'a>(&'a self) -> &'a LayoutJS<Node> {
&self.node
}
fn first_child(&self) -> Option<LayoutNode<'ln>> {
unsafe {
self.get_jsmanaged().first_child_ref().map(|node| self.new_with_this_lifetime(&node))
}
}
fn text(&self) -> String {
unsafe {
let text: Option<LayoutJS<Text>> = TextCast::to_layout_js(self.get_jsmanaged());
if let Some(text) = text {
return (*text.unsafe_get()).characterdata().data_for_layout().to_owned();
}
let input: Option<LayoutJS<HTMLInputElement>> = HTMLInputElementCast::to_layout_js(self.get_jsmanaged());
if let Some(input) = input {
return input.get_value_for_layout();
}
let area: Option<LayoutJS<HTMLTextAreaElement>> = HTMLTextAreaElementCast::to_layout_js(self.get_jsmanaged());
if let Some(area) = area {
return area.get_value_for_layout();
}
panic!("not text!")
}
}
}
impl<'ln> LayoutNode<'ln> {
pub fn dump(self) {
self.dump_indent(0);
}
fn dump_indent(self, indent: uint) {
let mut s = String::new();
for _ in range(0, indent) {
s.push_str(" ");
}
s.push_str(self.debug_str().as_slice());
println!("{}", s);
for kid in self.children() {
kid.dump_indent(indent + 1);
}
}
fn debug_str(self) -> String {
format!("{:?}: changed={} dirty={} dirty_descendants={}",
self.type_id(), self.has_changed(), self.is_dirty(), self.has_dirty_descendants())
}
pub fn flow_debug_id(self) -> uint {
let layout_data_ref = self.borrow_layout_data();
match *layout_data_ref {
None => 0u,
Some(ref layout_data) => layout_data.data.flow_construction_result.debug_id()
}
}
pub fn traverse_preorder(self) -> LayoutTreeIterator<'ln> {
LayoutTreeIterator::new(self)
}
fn last_child(self) -> Option<LayoutNode<'ln>> {
unsafe {
self.get_jsmanaged().last_child_ref().map(|node| self.new_with_this_lifetime(&node))
}
}
/// Returns an iterator over this node's children.
pub fn children(self) -> LayoutNodeChildrenIterator<'ln> {
// FIXME(zwarich): Remove this when UFCS lands and there is a better way
// of disambiguating methods.
fn first_child<T: TLayoutNode>(this: T) -> Option<T> {
this.first_child()
}
LayoutNodeChildrenIterator {
current: first_child(self),
}
}
pub fn rev_children(self) -> LayoutNodeReverseChildrenIterator<'ln> {
LayoutNodeReverseChildrenIterator {
current: self.last_child()
}
}
pub unsafe fn get_jsmanaged<'a>(&'a self) -> &'a LayoutJS<Node> {
&self.node
}
/// Resets layout data and styles for the node.
///
/// FIXME(pcwalton): Do this as part of fragment building instead of in a traversal.
pub fn initialize_layout_data(self, chan: LayoutChan) {
let mut layout_data_ref = self.mutate_layout_data();
match *layout_data_ref {
None => {
*layout_data_ref = Some(LayoutDataWrapper {
chan: Some(chan),
shared_data: SharedLayoutData { style: None },
data: box PrivateLayoutData::new(),
});
}
Some(_) => {}
}
}
pub fn has_children(self) -> bool {
self.first_child().is_some()
}
/// While doing a reflow, the node at the root has no parent, as far as we're
/// concerned. This method returns `None` at the reflow root.
pub fn layout_parent_node(self, shared: &SharedLayoutContext) -> Option<LayoutNode<'ln>> {
let opaque_node: OpaqueNode = OpaqueNodeMethods::from_layout_node(&self);
if opaque_node == shared.reflow_root {
None
} else {
self.parent_node()
}
}
pub fn debug_id(self) -> uint {
let opaque: OpaqueNode = OpaqueNodeMethods::from_layout_node(&self);
opaque.to_untrusted_node_address().0 as uint
}
}
impl<'ln> TNode<'ln, LayoutElement<'ln>> for LayoutNode<'ln> {
fn parent_node(self) -> Option<LayoutNode<'ln>> {
unsafe {
self.node.parent_node_ref().map(|node| self.new_with_this_lifetime(&node))
}
}
fn first_child(self) -> Option<LayoutNode<'ln>> {
unsafe {
self.node.first_child_ref().map(|node| self.new_with_this_lifetime(&node))
}
}
fn last_child(self) -> Option<LayoutNode<'ln>> {
unsafe {
self.node.last_child_ref().map(|node| self.new_with_this_lifetime(&node))
}
}
fn prev_sibling(self) -> Option<LayoutNode<'ln>> {
unsafe {
self.node.prev_sibling_ref().map(|node| self.new_with_this_lifetime(&node))
}
}
fn next_sibling(self) -> Option<LayoutNode<'ln>> {
unsafe {
self.node.next_sibling_ref().map(|node| self.new_with_this_lifetime(&node))
}
}
/// If this is an element, accesses the element data. Fails if this is not an element node.
#[inline]
fn as_element(self) -> LayoutElement<'ln> {
unsafe {
let elem: LayoutJS<Element> = match ElementCast::to_layout_js(&self.node) {
Some(elem) => elem,
None => panic!("not an element")
};
LayoutElement {
element: &*elem.unsafe_get(),
}
}
}
fn is_element(self) -> bool {
self.node_is_element()
}
fn is_document(self) -> bool {
self.node_is_document()
}
fn match_attr<F>(self, attr: &AttrSelector, test: F) -> bool where F: Fn(&str) -> bool {
assert!(self.is_element());
let name = if self.is_html_element_in_html_document() {
&attr.lower_name
} else {
&attr.name
};
match attr.namespace {
NamespaceConstraint::Specific(ref ns) => {
let element = self.as_element();
element.get_attr(ns, name).map_or(false, |attr| test(attr))
},
NamespaceConstraint::Any => {
let element = self.as_element();
element.get_attrs(name).iter().any(|attr| test(*attr))
}
}
}
fn is_html_element_in_html_document(self) -> bool {
unsafe {
match ElementCast::to_layout_js(&self.node) {
Some(elem) => elem.html_element_in_html_document_for_layout(),
None => false
}
}
}
fn has_changed(self) -> bool {
unsafe { self.node.get_flag(HAS_CHANGED) }
}
unsafe fn set_changed(self, value: bool) {
self.node.set_flag(HAS_CHANGED, value)
}
fn is_dirty(self) -> bool {
unsafe { self.node.get_flag(IS_DIRTY) }
}
unsafe fn set_dirty(self, value: bool) {
self.node.set_flag(IS_DIRTY, value)
}
fn has_dirty_siblings(self) -> bool {
unsafe { self.node.get_flag(HAS_DIRTY_SIBLINGS) }
}
unsafe fn set_dirty_siblings(self, value: bool) {
self.node.set_flag(HAS_DIRTY_SIBLINGS, value);
}
fn has_dirty_descendants(self) -> bool {
unsafe { self.node.get_flag(HAS_DIRTY_DESCENDANTS) }
}
unsafe fn set_dirty_descendants(self, value: bool) {
self.node.set_flag(HAS_DIRTY_DESCENDANTS, value)
}
}
pub struct LayoutNodeChildrenIterator<'a> {
current: Option<LayoutNode<'a>>,
}
impl<'a> Iterator for LayoutNodeChildrenIterator<'a> {
type Item = LayoutNode<'a>;
fn next(&mut self) -> Option<LayoutNode<'a>> {
let node = self.current;
self.current = node.and_then(|node| node.next_sibling());
node
}
}
pub struct LayoutNodeReverseChildrenIterator<'a> {
current: Option<LayoutNode<'a>>,
}
impl<'a> Iterator for LayoutNodeReverseChildrenIterator<'a> {
type Item = LayoutNode<'a>;
fn next(&mut self) -> Option<LayoutNode<'a>> {
let node = self.current;
self.current = node.and_then(|node| node.prev_sibling());
node
}
}
pub struct LayoutTreeIterator<'a> {
stack: Vec<LayoutNode<'a>>,
}
impl<'a> LayoutTreeIterator<'a> {
fn new(root: LayoutNode<'a>) -> LayoutTreeIterator<'a> {
let mut stack = vec!();
stack.push(root);
LayoutTreeIterator {
stack: stack
}
}
}
impl<'a> Iterator for LayoutTreeIterator<'a> {
type Item = LayoutNode<'a>;
fn next(&mut self) -> Option<LayoutNode<'a>> {
let ret = self.stack.pop();
ret.map(|node| self.stack.extend(node.rev_children()));
ret
}
}
/// A wrapper around elements that ensures layout can only ever access safe properties.
#[derive(Copy)]
pub struct LayoutElement<'le> {
element: &'le Element,
}
impl<'le> LayoutElement<'le> {
pub fn style_attribute(&self) -> &'le Option<PropertyDeclarationBlock> {
let style: &Option<PropertyDeclarationBlock> = unsafe {
&*self.element.style_attribute().borrow_for_layout()
};
style
}
}
impl<'le> TElement<'le> for LayoutElement<'le> {
#[inline]
fn get_local_name(self) -> &'le Atom {
self.element.local_name()
}
#[inline]
fn get_namespace(self) -> &'le Namespace {
self.element.namespace()
}
#[inline]
fn get_attr(self, namespace: &Namespace, name: &Atom) -> Option<&'le str> {
unsafe { self.element.get_attr_val_for_layout(namespace, name) }
}
#[inline]
fn get_attrs(self, name: &Atom) -> Vec<&'le str> {
unsafe {
self.element.get_attr_vals_for_layout(name)
}
}
fn get_link(self) -> Option<&'le str> {
// FIXME: This is HTML only.
let node: &Node = NodeCast::from_actual(self.element);
match node.type_id_for_layout() {
// http://www.whatwg.org/specs/web-apps/current-work/multipage/selectors.html#
// selector-link
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAreaElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLLinkElement)) => {
unsafe {
self.element.get_attr_val_for_layout(&ns!(""), &atom!("href"))
}
}
_ => None,
}
}
#[inline]
fn get_hover_state(self) -> bool {
unsafe {
let node: &Node = NodeCast::from_actual(self.element);
node.get_hover_state_for_layout()
}
}
#[inline]
fn get_id(self) -> Option<Atom> {
unsafe {
self.element.get_attr_atom_for_layout(&ns!(""), &atom!("id"))
}
}
#[inline]
fn get_disabled_state(self) -> bool {
unsafe {
let node: &Node = NodeCast::from_actual(self.element);
node.get_disabled_state_for_layout()
}
}
#[inline]
fn get_enabled_state(self) -> bool {
unsafe {
let node: &Node = NodeCast::from_actual(self.element);
node.get_enabled_state_for_layout()
}
}
#[inline]
fn get_checked_state(self) -> bool {
unsafe {
self.element.get_checked_state_for_layout()
}
}
#[inline]
fn get_indeterminate_state(self) -> bool {
unsafe {
self.element.get_indeterminate_state_for_layout()
}
}
#[inline]
fn has_class(self, name: &Atom) -> bool {
unsafe {
self.element.has_class_for_layout(name)
}
}
#[inline(always)]
fn each_class<F>(self, mut callback: F) where F: FnMut(&Atom) {
unsafe {
match self.element.get_classes_for_layout() {
None => {}
Some(ref classes) => {
for class in classes.iter() {
callback(class)
}
}
}
}
}
#[inline]
fn has_nonzero_border(self) -> bool {
unsafe {
match self.element
.get_unsigned_integer_attribute_for_layout(UnsignedIntegerAttribute::Border) {
None | Some(0) => false,
_ => true,
}
}
}
}
impl<'le> TElementAttributes for LayoutElement<'le> {
fn get_length_attribute(self, length_attribute: LengthAttribute) -> LengthOrPercentageOrAuto {
unsafe {
self.element.get_length_attribute_for_layout(length_attribute)
}
}
fn get_integer_attribute(self, integer_attribute: IntegerAttribute) -> Option<i32> {
unsafe {
self.element.get_integer_attribute_for_layout(integer_attribute)
}
}
fn get_unsigned_integer_attribute(self, attribute: UnsignedIntegerAttribute) -> Option<u32> {
unsafe {
self.element.get_unsigned_integer_attribute_for_layout(attribute)
}
}
fn get_simple_color_attribute(self, attribute: SimpleColorAttribute) -> Option<RGBA> {
unsafe {
self.element.get_simple_color_attribute_for_layout(attribute)
}
}
}
fn get_content(content_list: &content::T) -> String {
match *content_list {
content::T::Content(ref value) => {
let iter = &mut value.clone().into_iter().peekable();
match iter.next() {
Some(content::ContentItem::StringContent(content)) => content,
_ => "".to_owned(),
}
}
_ => "".to_owned(),
}
}
#[derive(Copy, PartialEq, Clone)]
pub enum PseudoElementType {
Normal,
Before(display::T),
After(display::T),
}
impl PseudoElementType {
pub fn is_before(&self) -> bool {
match *self {
PseudoElementType::Before(_) => true,
_ => false,
}
}
pub fn is_after(&self) -> bool {
match *self {
PseudoElementType::After(_) => true,
_ => false,
}
}
}
/// A thread-safe version of `LayoutNode`, used during flow construction. This type of layout
/// node does not allow any parents or siblings of nodes to be accessed, to avoid races.
#[derive(Copy, Clone)]
pub struct ThreadSafeLayoutNode<'ln> {
/// The wrapped node.
node: LayoutNode<'ln>,
pseudo: PseudoElementType,
}
impl<'ln> TLayoutNode for ThreadSafeLayoutNode<'ln> {
/// Creates a new layout node with the same lifetime as this layout node.
unsafe fn new_with_this_lifetime(&self, node: &LayoutJS<Node>) -> ThreadSafeLayoutNode<'ln> {
ThreadSafeLayoutNode {
node: LayoutNode {
node: node.transmute_copy(),
chain: self.node.chain,
},
pseudo: PseudoElementType::Normal,
}
}
/// Returns `None` if this is a pseudo-element.
fn type_id(&self) -> Option<NodeTypeId> {
if self.pseudo != PseudoElementType::Normal {
return None
}
self.node.type_id()
}
unsafe fn get_jsmanaged<'a>(&'a self) -> &'a LayoutJS<Node> {
self.node.get_jsmanaged()
}
unsafe fn get<'a>(&'a self) -> &'a Node { // this change.
&*self.get_jsmanaged().unsafe_get()
}
fn first_child(&self) -> Option<ThreadSafeLayoutNode<'ln>> {
if self.pseudo != PseudoElementType::Normal {
return None
}
if self.has_before_pseudo() {
// FIXME(pcwalton): This logic looks weird. Is it right?
match self.pseudo {
PseudoElementType::Normal => {
let pseudo_before_node = self.with_pseudo(PseudoElementType::Before(self.get_before_display()));
return Some(pseudo_before_node)
}
PseudoElementType::Before(display::T::inline) => {}
PseudoElementType::Before(_) => {
let pseudo_before_node = self.with_pseudo(PseudoElementType::Before(display::T::inline));
return Some(pseudo_before_node)
}
_ => {}
}
}
unsafe {
self.get_jsmanaged().first_child_ref().map(|node| self.new_with_this_lifetime(&node))
}
}
fn text(&self) -> String {
if self.pseudo != PseudoElementType::Normal {
let layout_data_ref = self.borrow_layout_data();
let node_layout_data_wrapper = layout_data_ref.as_ref().unwrap();
if self.pseudo.is_before() {
let before_style = node_layout_data_wrapper.data.before_style.as_ref().unwrap();
return get_content(&before_style.get_box().content)
} else {
let after_style = node_layout_data_wrapper.data.after_style.as_ref().unwrap();
return get_content(&after_style.get_box().content)
}
}
self.node.text()
}
}
impl<'ln> ThreadSafeLayoutNode<'ln> {
/// Creates a new `ThreadSafeLayoutNode` from the given `LayoutNode`.
pub fn new<'a>(node: &LayoutNode<'a>) -> ThreadSafeLayoutNode<'a> {
ThreadSafeLayoutNode {
node: node.clone(),
pseudo: PseudoElementType::Normal,
}
}
/// Creates a new `ThreadSafeLayoutNode` for the same `LayoutNode`
/// with a different pseudo-element type.
fn with_pseudo(&self, pseudo: PseudoElementType) -> ThreadSafeLayoutNode<'ln> {
ThreadSafeLayoutNode {
node: self.node.clone(),
pseudo: pseudo,
}
}
pub fn debug_id(self) -> uint {
self.node.debug_id()
}
pub fn flow_debug_id(self) -> uint {
self.node.flow_debug_id()
}
/// Returns the next sibling of this node. Unsafe and private because this can lead to races.
unsafe fn next_sibling(&self) -> Option<ThreadSafeLayoutNode<'ln>> {
if self.pseudo.is_before() {
return self.get_jsmanaged().first_child_ref().map(|node| self.new_with_this_lifetime(&node))
}
self.get_jsmanaged().next_sibling_ref().map(|node| self.new_with_this_lifetime(&node))
}
/// Returns an iterator over this node's children.
pub fn children(&self) -> ThreadSafeLayoutNodeChildrenIterator<'ln> {
ThreadSafeLayoutNodeChildrenIterator {
current_node: self.first_child(),
parent_node: Some(self.clone()),
}
}
/// If this is an element, accesses the element data. Fails if this is not an element node.
#[inline]
pub fn as_element(&self) -> ThreadSafeLayoutElement<'ln> {
unsafe {
let element = match ElementCast::to_layout_js(self.get_jsmanaged()) {
Some(e) => e.unsafe_get(),
None => panic!("not an element")
};
// FIXME(pcwalton): Workaround until Rust gets multiple lifetime parameters on
// implementations.
ThreadSafeLayoutElement {
element: &*element,
}
}
}
#[inline]
pub fn get_pseudo_element_type(&self) -> PseudoElementType {
self.pseudo
}
#[inline]
pub fn get_normal_display(&self) -> display::T {
let mut layout_data_ref = self.mutate_layout_data();
let node_layout_data_wrapper = layout_data_ref.as_mut().unwrap();
let style = node_layout_data_wrapper.shared_data.style.as_ref().unwrap();
style.get_box().display
}
#[inline]
pub fn get_before_display(&self) -> display::T {
let mut layout_data_ref = self.mutate_layout_data();
let node_layout_data_wrapper = layout_data_ref.as_mut().unwrap();
let style = node_layout_data_wrapper.data.before_style.as_ref().unwrap();
style.get_box().display
}
#[inline]
pub fn get_after_display(&self) -> display::T {
let mut layout_data_ref = self.mutate_layout_data();
let node_layout_data_wrapper = layout_data_ref.as_mut().unwrap();
let style = node_layout_data_wrapper.data.after_style.as_ref().unwrap();
style.get_box().display
}
#[inline]
pub fn has_before_pseudo(&self) -> bool {
let layout_data_wrapper = self.borrow_layout_data();
let layout_data_wrapper_ref = layout_data_wrapper.as_ref().unwrap();
layout_data_wrapper_ref.data.before_style.is_some()
}
#[inline]
pub fn has_after_pseudo(&self) -> bool {
let layout_data_wrapper = self.borrow_layout_data();
let layout_data_wrapper_ref = layout_data_wrapper.as_ref().unwrap();
layout_data_wrapper_ref.data.after_style.is_some()
}
/// Borrows the layout data without checking. Fails on a conflicting borrow.
#[inline(always)]
fn borrow_layout_data_unchecked<'a>(&'a self) -> *const Option<LayoutDataWrapper> {
unsafe {
mem::transmute(self.get().layout_data_unchecked())
}
}
/// Borrows the layout data immutably. Fails on a conflicting borrow.
///
/// TODO(pcwalton): Make this private. It will let us avoid borrow flag checks in some cases.
#[inline(always)]
pub fn borrow_layout_data<'a>(&'a self) -> Ref<'a,Option<LayoutDataWrapper>> {
unsafe {
mem::transmute(self.get().layout_data())
}
}
/// Borrows the layout data mutably. Fails on a conflicting borrow.
///
/// TODO(pcwalton): Make this private. It will let us avoid borrow flag checks in some cases.
#[inline(always)]
pub fn mutate_layout_data<'a>(&'a self) -> RefMut<'a,Option<LayoutDataWrapper>> {
unsafe {
mem::transmute(self.get().layout_data_mut())
}
}
/// Traverses the tree in postorder.
///
/// TODO(pcwalton): Offer a parallel version with a compatible API.
pub fn traverse_postorder_mut<T:PostorderNodeMutTraversal>(&mut self, traversal: &mut T)
-> bool {
if traversal.should_prune(self) {
return true
}
let mut opt_kid = self.first_child();
loop {
match opt_kid {
None => break,
Some(mut kid) => {
if !kid.traverse_postorder_mut(traversal) {
return false
}
unsafe {
opt_kid = kid.next_sibling()
}
}
}
}
traversal.process(self)
}
pub fn is_ignorable_whitespace(&self) -> bool {
unsafe {
let text: LayoutJS<Text> = match TextCast::to_layout_js(self.get_jsmanaged()) {
Some(text) => text,
None => return false
};
if !is_whitespace((*text.unsafe_get()).characterdata().data_for_layout()) {
return false
}
// NB: See the rules for `white-space` here:
//
// http://www.w3.org/TR/CSS21/text.html#propdef-white-space
//
// If you implement other values for this property, you will almost certainly
// want to update this check.
match self.style().get_inheritedtext().white_space {
white_space::T::normal => true,
_ => false,
}
}
}
pub fn get_input_value(&self) -> String {
unsafe {
let input: Option<LayoutJS<HTMLInputElement>> = HTMLInputElementCast::to_layout_js(self.get_jsmanaged());
match input {
Some(input) => input.get_value_for_layout(),
None => panic!("not an input element!")
}
}
}
pub fn get_input_size(&self) -> u32 {
unsafe {
match HTMLInputElementCast::to_layout_js(self.get_jsmanaged()) {
Some(input) => input.get_size_for_layout(),
None => panic!("not an input element!")
}
}
}
pub fn get_unsigned_integer_attribute(self, attribute: UnsignedIntegerAttribute)
-> Option<u32> {
unsafe {
let elem: Option<LayoutJS<Element>> = ElementCast::to_layout_js(self.get_jsmanaged());
match elem {
Some(element) => {
(*element.unsafe_get()).get_unsigned_integer_attribute_for_layout(attribute)
}
None => panic!("not an element!")
}
}
}
/// Get the description of how to account for recent style changes.
/// This is a simple bitfield and fine to copy by value.
pub fn restyle_damage(self) -> RestyleDamage {
let layout_data_ref = self.borrow_layout_data();
layout_data_ref.as_ref().unwrap().data.restyle_damage
}
/// Set the restyle damage field.
pub fn set_restyle_damage(self, damage: RestyleDamage) {
let mut layout_data_ref = self.mutate_layout_data();
match &mut *layout_data_ref {
&mut Some(ref mut layout_data) => layout_data.data.restyle_damage = damage,
_ => panic!("no layout data for this node"),
}
}
/// Returns the layout data flags for this node.
pub fn flags(self) -> LayoutDataFlags {
unsafe {
match *self.borrow_layout_data_unchecked() {
None => panic!(),
Some(ref layout_data) => layout_data.data.flags,
}
}
}
/// Adds the given flags to this node.
pub fn insert_flags(self, new_flags: LayoutDataFlags) {
let mut layout_data_ref = self.mutate_layout_data();
match &mut *layout_data_ref {
&mut Some(ref mut layout_data) => layout_data.data.flags.insert(new_flags),
_ => panic!("no layout data for this node"),
}
}
/// Removes the given flags from this node.
pub fn remove_flags(self, flags: LayoutDataFlags) {
let mut layout_data_ref = self.mutate_layout_data();
match &mut *layout_data_ref {
&mut Some(ref mut layout_data) => layout_data.data.flags.remove(flags),
_ => panic!("no layout data for this node"),
}
}
/// Returns true if this node contributes content. This is used in the implementation of
/// `empty_cells` per CSS 2.1 § 17.6.1.1.
pub fn is_content(&self) -> bool {
match self.type_id() {
Some(NodeTypeId::Element(..)) | Some(NodeTypeId::Text(..)) => true,
_ => false
}
}
}
pub struct ThreadSafeLayoutNodeChildrenIterator<'a> {
current_node: Option<ThreadSafeLayoutNode<'a>>,
parent_node: Option<ThreadSafeLayoutNode<'a>>,
}
impl<'a> Iterator for ThreadSafeLayoutNodeChildrenIterator<'a> {
type Item = ThreadSafeLayoutNode<'a>;
fn next(&mut self) -> Option<ThreadSafeLayoutNode<'a>> {
let node = self.current_node.clone();
match node {
Some(ref node) => {
if node.pseudo.is_after() {
return None
}
match self.parent_node {
Some(ref parent_node) => {
if parent_node.pseudo == PseudoElementType::Normal {
self.current_node = self.current_node.clone().and_then(|node| {
unsafe {
node.next_sibling()
}
});
} else {
self.current_node = None;
}
}
None => {}
}
}
None => {
match self.parent_node {
Some(ref parent_node) => {
if parent_node.has_after_pseudo() {
let pseudo_after_node = if parent_node.pseudo == PseudoElementType::Normal {
let pseudo = PseudoElementType::After(parent_node.get_after_display());
Some(parent_node.with_pseudo(pseudo))
} else {
None
};
self.current_node = pseudo_after_node;
return self.current_node.clone()
}
}
None => {}
}
}
}
node
}
}
/// A wrapper around elements that ensures layout can only ever access safe properties and cannot
/// race on elements.
pub struct ThreadSafeLayoutElement<'le> {
element: &'le Element,
}
impl<'le> ThreadSafeLayoutElement<'le> {
#[inline]
pub fn get_attr(&self, namespace: &Namespace, name: &Atom) -> Option<&'le str> {
unsafe {
self.element.get_attr_val_for_layout(namespace, name)
}
}
}
/// A bottom-up, parallelizable traversal.
pub trait PostorderNodeMutTraversal {
/// The operation to perform. Return true to continue or false to stop.
fn process<'a>(&'a mut self, node: &ThreadSafeLayoutNode<'a>) -> bool;
/// Returns true if this node should be pruned. If this returns true, we skip the operation
/// entirely and do not process any descendant nodes. This is called *before* child nodes are
/// visited. The default implementation never prunes any nodes.
fn should_prune<'a>(&'a self, _node: &ThreadSafeLayoutNode<'a>) -> bool {
false
}
}
/// Opaque type stored in type-unsafe work queues for parallel layout.
/// Must be transmutable to and from LayoutNode/ThreadSafeLayoutNode.
pub type UnsafeLayoutNode = (uint, uint);
pub fn layout_node_to_unsafe_layout_node(node: &LayoutNode) -> UnsafeLayoutNode {
unsafe {
let ptr: uint = mem::transmute_copy(node);
(ptr, 0)
}
}
// FIXME(#3044): This should be updated to use a real lifetime instead of
// faking one.
pub unsafe fn layout_node_from_unsafe_layout_node(node: &UnsafeLayoutNode) -> LayoutNode<'static> {
let (node, _) = *node;
mem::transmute(node)
}
/// A top-down traversal.
pub trait PreorderDomTraversal {
/// The operation to perform. Return true to continue or false to stop.
fn process(&self, node: LayoutNode);
}
/// A bottom-up traversal, with a optional in-order pass.
pub trait PostorderDomTraversal {
/// The operation to perform. Return true to continue or false to stop.
fn process(&self, node: LayoutNode);
}
|