diff options
-rw-r--r-- | components/gfx/font_cache_task.rs | 8 | ||||
-rw-r--r-- | components/layout/context.rs | 10 | ||||
-rw-r--r-- | components/layout/display_list_builder.rs | 4 | ||||
-rw-r--r-- | components/layout/layout_task.rs | 7 | ||||
-rw-r--r-- | components/layout/parallel.rs | 148 | ||||
-rw-r--r-- | components/layout/sequential.rs | 31 | ||||
-rw-r--r-- | components/layout/traversal.rs | 277 | ||||
-rw-r--r-- | components/layout/wrapper.rs | 12 | ||||
-rw-r--r-- | components/net/fetch/request.rs | 197 | ||||
-rw-r--r-- | components/servo/Cargo.lock | 2 | ||||
-rw-r--r-- | components/style/dom.rs | 8 | ||||
-rw-r--r-- | components/style/lib.rs | 3 | ||||
-rw-r--r-- | components/style/parallel.rs | 141 | ||||
-rw-r--r-- | components/style/sequential.rs | 28 | ||||
-rw-r--r-- | components/style/traversal.rs | 259 | ||||
-rw-r--r-- | tests/unit/gfx/Cargo.toml | 6 | ||||
-rw-r--r-- | tests/unit/gfx/font_cache_task.rs | 21 | ||||
-rw-r--r-- | tests/unit/gfx/lib.rs | 3 | ||||
-rw-r--r-- | tests/wpt/mozilla/tests/css/linear_gradients_lengths_a.html | 3 | ||||
-rw-r--r-- | tests/wpt/mozilla/tests/css/linear_gradients_lengths_ref.html | 3 |
20 files changed, 658 insertions, 513 deletions
diff --git a/components/gfx/font_cache_task.rs b/components/gfx/font_cache_task.rs index 6c4b893e6e9..ab3d67c6538 100644 --- a/components/gfx/font_cache_task.rs +++ b/components/gfx/font_cache_task.rs @@ -152,7 +152,7 @@ impl FontCache { let family_name = LowercaseString::new(family.name()); if !self.web_families.contains_key(&family_name) { let templates = FontTemplates::new(); - self.web_families.insert(family_name, templates); + self.web_families.insert(family_name.clone(), templates); } match src { @@ -207,10 +207,10 @@ impl FontCache { } }); } - Source::Local(ref family) => { - let family_name = LowercaseString::new(family.name()); + Source::Local(ref font) => { + let font_face_name = LowercaseString::new(font.name()); let templates = &mut self.web_families.get_mut(&family_name).unwrap(); - for_each_variation(&family_name, |path| { + for_each_variation(&font_face_name, |path| { templates.add_template(Atom::from(&*path), None); }); result.send(()).unwrap(); diff --git a/components/layout/context.rs b/components/layout/context.rs index a10fe334730..43c51147934 100644 --- a/components/layout/context.rs +++ b/components/layout/context.rs @@ -128,16 +128,6 @@ impl<'a> LayoutContext<'a> { self.cached_local_layout_context.font_context.borrow_mut() } - #[inline(always)] - pub fn applicable_declarations_cache(&self) -> RefMut<ApplicableDeclarationsCache> { - self.local_context().applicable_declarations_cache.borrow_mut() - } - - #[inline(always)] - pub fn style_sharing_candidate_cache(&self) -> RefMut<StyleSharingCandidateCache> { - self.local_context().style_sharing_candidate_cache.borrow_mut() - } - pub fn get_or_request_image(&self, url: Url, use_placeholder: UsePlaceholder) -> Option<Arc<Image>> { // See if the image is already available diff --git a/components/layout/display_list_builder.rs b/components/layout/display_list_builder.rs index 7cc1d3f6311..99f26266189 100644 --- a/components/layout/display_list_builder.rs +++ b/components/layout/display_list_builder.rs @@ -335,7 +335,7 @@ impl FragmentDisplayListBuilding for Fragment { Some(computed::Image::LinearGradient(ref gradient)) => { self.build_display_list_for_background_linear_gradient(display_list, level, - absolute_bounds, + &bounds, &clip, gradient, style) @@ -345,7 +345,7 @@ impl FragmentDisplayListBuilding for Fragment { display_list, layout_context, level, - absolute_bounds, + &bounds, &clip, image_url) } diff --git a/components/layout/layout_task.rs b/components/layout/layout_task.rs index 0015cd3fc33..7c39d61db22 100644 --- a/components/layout/layout_task.rs +++ b/components/layout/layout_task.rs @@ -38,7 +38,7 @@ use msg::ParseErrorReporter; use msg::compositor_msg::Epoch; use msg::constellation_msg::{ConstellationChan, Failure, PipelineId}; use net_traits::image_cache_task::{ImageCacheChan, ImageCacheResult, ImageCacheTask}; -use parallel::{self, WorkQueueData}; +use parallel; use profile_traits::mem::{self, Report, ReportKind, ReportsChan}; use profile_traits::time::{TimerMetadataFrameType, TimerMetadataReflowType}; use profile_traits::time::{self, TimerMetadata, profile}; @@ -67,6 +67,7 @@ use style::computed_values::{filter, mix_blend_mode}; use style::context::{SharedStyleContext, StylistWrapper}; use style::dom::{TDocument, TElement, TNode}; use style::media_queries::{Device, MediaType}; +use style::parallel::WorkQueueData; use style::selector_matching::{Stylist, USER_OR_USER_AGENT_STYLESHEETS}; use style::stylesheets::{CSSRuleIteratorExt, Stylesheet}; use traversal::RecalcStyleAndConstructFlows; @@ -1025,11 +1026,11 @@ impl LayoutTask { // Perform CSS selector matching and flow construction. match self.parallel_traversal { None => { - sequential::traverse_dom_preorder::<ServoLayoutNode, RecalcStyleAndConstructFlows>( + sequential::traverse_dom::<ServoLayoutNode, RecalcStyleAndConstructFlows>( node, &shared_layout_context); } Some(ref mut traversal) => { - parallel::traverse_dom_preorder::<ServoLayoutNode, RecalcStyleAndConstructFlows>( + parallel::traverse_dom::<ServoLayoutNode, RecalcStyleAndConstructFlows>( node, &shared_layout_context, traversal); } } diff --git a/components/layout/parallel.rs b/components/layout/parallel.rs index fa52a7efdb2..4ea427b11ee 100644 --- a/components/layout/parallel.rs +++ b/components/layout/parallel.rs @@ -11,28 +11,23 @@ use context::{LayoutContext, SharedLayoutContext}; use flow::{self, Flow, MutableFlowUtils, PostorderFlowTraversal, PreorderFlowTraversal}; use flow_ref::{self, FlowRef}; -use gfx::display_list::OpaqueNode; use profile_traits::time::{self, TimerMetadata, profile}; use std::mem; use std::sync::atomic::{AtomicIsize, Ordering}; -use style::dom::UnsafeNode; -use traversal::PostorderNodeMutTraversal; +use style::dom::{TNode, UnsafeNode}; +use style::parallel::{CHUNK_SIZE, WorkQueueData}; +use style::parallel::{run_queue_with_custom_work_data_type}; use traversal::{AssignBSizesAndStoreOverflow, AssignISizes, BubbleISizes}; -use traversal::{BuildDisplayList, ComputeAbsolutePositions}; -use traversal::{DomTraversal, DomTraversalContext}; +use traversal::{BuildDisplayList, ComputeAbsolutePositions, PostorderNodeMutTraversal}; use util::opts; use util::workqueue::{WorkQueue, WorkUnit, WorkerProxy}; -use wrapper::LayoutNode; -const CHUNK_SIZE: usize = 64; - -pub struct WorkQueueData(usize, usize); +pub use style::parallel::traverse_dom; #[allow(dead_code)] fn static_assertion(node: UnsafeNode) { unsafe { let _: UnsafeFlow = ::std::intrinsics::transmute(node); - let _: UnsafeNodeList = ::std::intrinsics::transmute(node); } } @@ -55,18 +50,8 @@ pub fn borrowed_flow_to_unsafe_flow(flow: &Flow) -> UnsafeFlow { } } -pub type UnsafeNodeList = (Box<Vec<UnsafeNode>>, OpaqueNode); - pub type UnsafeFlowList = (Box<Vec<UnsafeNode>>, usize); -pub type ChunkedDomTraversalFunction = - extern "Rust" fn(UnsafeNodeList, - &mut WorkerProxy<SharedLayoutContext, UnsafeNodeList>); - -pub type DomTraversalFunction = - extern "Rust" fn(OpaqueNode, UnsafeNode, - &mut WorkerProxy<SharedLayoutContext, UnsafeNodeList>); - pub type ChunkedFlowTraversalFunction = extern "Rust" fn(UnsafeFlowList, &mut WorkerProxy<SharedLayoutContext, UnsafeFlowList>); @@ -232,104 +217,6 @@ impl<'a> ParallelPreorderFlowTraversal for ComputeAbsolutePositions<'a> { impl<'a> ParallelPostorderFlowTraversal for BuildDisplayList<'a> {} -/// A parallel top-down DOM traversal. -#[inline(always)] -fn top_down_dom<'ln, N, T>(unsafe_nodes: UnsafeNodeList, - proxy: &mut WorkerProxy<SharedLayoutContext, UnsafeNodeList>) - where N: LayoutNode<'ln>, T: DomTraversal<'ln, N> { - let shared_layout_context = proxy.user_data(); - let layout_context = LayoutContext::new(shared_layout_context); - let traversal_context = DomTraversalContext { - layout_context: &layout_context, - root: unsafe_nodes.1, - }; - - let mut discovered_child_nodes = Vec::new(); - for unsafe_node in *unsafe_nodes.0 { - // Get a real layout node. - let node = unsafe { N::from_unsafe(&unsafe_node) }; - - // Perform the appropriate traversal. - T::process_preorder(&traversal_context, node); - - let child_count = node.children_count(); - - // Reset the count of children. - { - let data = node.mutate_data().unwrap(); - data.parallel.children_count.store(child_count as isize, - Ordering::Relaxed); - } - - // Possibly enqueue the children. - if child_count != 0 { - for kid in node.children() { - discovered_child_nodes.push(kid.to_unsafe()) - } - } else { - // If there were no more children, start walking back up. - bottom_up_dom::<N, T>(unsafe_nodes.1, unsafe_node, proxy) - } - } - - for chunk in discovered_child_nodes.chunks(CHUNK_SIZE) { - proxy.push(WorkUnit { - fun: top_down_dom::<N, T>, - data: (box chunk.iter().cloned().collect(), unsafe_nodes.1), - }); - } -} - -/// Process current node and potentially traverse its ancestors. -/// -/// If we are the last child that finished processing, recursively process -/// our parent. Else, stop. Also, stop at the root. -/// -/// Thus, if we start with all the leaves of a tree, we end up traversing -/// the whole tree bottom-up because each parent will be processed exactly -/// once (by the last child that finishes processing). -/// -/// The only communication between siblings is that they both -/// fetch-and-subtract the parent's children count. -fn bottom_up_dom<'ln, N, T>(root: OpaqueNode, - unsafe_node: UnsafeNode, - proxy: &mut WorkerProxy<SharedLayoutContext, UnsafeNodeList>) - where N: LayoutNode<'ln>, T: DomTraversal<'ln, N> { - let shared_layout_context = proxy.user_data(); - let layout_context = LayoutContext::new(shared_layout_context); - let traversal_context = DomTraversalContext { - layout_context: &layout_context, - root: root, - }; - - // Get a real layout node. - let mut node = unsafe { N::from_unsafe(&unsafe_node) }; - loop { - // Perform the appropriate operation. - T::process_postorder(&traversal_context, node); - - let parent = match node.layout_parent_node(traversal_context.root) { - None => break, - Some(parent) => parent, - }; - - let parent_data = unsafe { - &*parent.borrow_data_unchecked().unwrap() - }; - - if parent_data - .parallel - .children_count - .fetch_sub(1, Ordering::Relaxed) != 1 { - // Get out of here and find another node to work on. - break - } - - // We were the last child of our parent. Construct flows for our parent. - node = parent; - } -} - fn assign_inline_sizes(unsafe_flows: UnsafeFlowList, proxy: &mut WorkerProxy<SharedLayoutContext, UnsafeFlowList>) { let shared_layout_context = proxy.user_data(); @@ -372,31 +259,6 @@ fn build_display_list(unsafe_flow: UnsafeFlow, build_display_list_traversal.run_parallel(unsafe_flow); } -fn run_queue_with_custom_work_data_type<To, F>( - queue: &mut WorkQueue<SharedLayoutContext, WorkQueueData>, - callback: F, - shared_layout_context: &SharedLayoutContext) - where To: 'static + Send, F: FnOnce(&mut WorkQueue<SharedLayoutContext, To>) { - let queue: &mut WorkQueue<SharedLayoutContext, To> = unsafe { - mem::transmute(queue) - }; - callback(queue); - queue.run(shared_layout_context); -} - -pub fn traverse_dom_preorder<'ln, N, T>( - root: N, - shared_layout_context: &SharedLayoutContext, - queue: &mut WorkQueue<SharedLayoutContext, WorkQueueData>) - where N: LayoutNode<'ln>, T: DomTraversal<'ln, N> { - run_queue_with_custom_work_data_type(queue, |queue| { - queue.push(WorkUnit { - fun: top_down_dom::<N, T>, - data: (box vec![root.to_unsafe()], root.opaque()), - }); - }, shared_layout_context); -} - pub fn traverse_flow_tree_preorder( root: &mut FlowRef, profiler_metadata: Option<TimerMetadata>, diff --git a/components/layout/sequential.rs b/components/layout/sequential.rs index 310560e2fa7..ad332f30fdd 100644 --- a/components/layout/sequential.rs +++ b/components/layout/sequential.rs @@ -12,36 +12,13 @@ use flow::{self, Flow, ImmutableFlowUtils, InorderFlowTraversal, MutableFlowUtil use flow_ref::{self, FlowRef}; use fragment::FragmentBorderBoxIterator; use generated_content::ResolveGeneratedContent; -use traversal::PostorderNodeMutTraversal; +use style::dom::TNode; +use style::traversal::DomTraversalContext; use traversal::{AssignBSizesAndStoreOverflow, AssignISizes}; -use traversal::{BubbleISizes, BuildDisplayList, ComputeAbsolutePositions}; -use traversal::{DomTraversal, DomTraversalContext}; +use traversal::{BubbleISizes, BuildDisplayList, ComputeAbsolutePositions, PostorderNodeMutTraversal}; use util::opts; -use wrapper::LayoutNode; - -pub fn traverse_dom_preorder<'ln, N, T>(root: N, - shared_layout_context: &SharedLayoutContext) - where N: LayoutNode<'ln>, - T: DomTraversal<'ln, N> { - fn doit<'a, 'ln, N, T>(context: &'a DomTraversalContext<'a>, node: N) - where N: LayoutNode<'ln>, T: DomTraversal<'ln, N> { - T::process_preorder(context, node); - - for kid in node.children() { - doit::<N, T>(context, kid); - } - - T::process_postorder(context, node); - } - let layout_context = LayoutContext::new(shared_layout_context); - let traversal_context = DomTraversalContext { - layout_context: &layout_context, - root: root.opaque(), - }; - - doit::<N, T>(&traversal_context, root); -} +pub use style::sequential::traverse_dom; pub fn resolve_generated_content(root: &mut FlowRef, shared_layout_context: &SharedLayoutContext) { fn doit(flow: &mut Flow, level: u32, traversal: &mut ResolveGeneratedContent) { diff --git a/components/layout/traversal.rs b/components/layout/traversal.rs index b740e7dbcf3..c42ba491732 100644 --- a/components/layout/traversal.rs +++ b/components/layout/traversal.rs @@ -5,142 +5,68 @@ //! Traversals over the DOM and flow trees, running the layout computations. use construct::FlowConstructor; -use context::LayoutContext; +use context::{LayoutContext, SharedLayoutContext}; use flow::{PostorderFlowTraversal, PreorderFlowTraversal}; use flow::{self, Flow}; use gfx::display_list::OpaqueNode; use incremental::{BUBBLE_ISIZES, REFLOW, REFLOW_OUT_OF_FLOW, REPAINT, RestyleDamage}; use script::layout_interface::ReflowGoal; -use selectors::bloom::BloomFilter; -use std::cell::RefCell; use std::mem; use style::context::StyleContext; -use style::dom::{TRestyleDamage, UnsafeNode}; -use style::matching::{ApplicableDeclarations, ElementMatchMethods, MatchMethods, StyleSharingResult}; +use style::matching::MatchMethods; +use style::traversal::{DomTraversalContext, STYLE_BLOOM}; +use style::traversal::{put_task_local_bloom_filter, recalc_style_at}; use util::opts; use util::tid::tid; use wrapper::{LayoutNode, ThreadSafeLayoutNode}; -/// Every time we do another layout, the old bloom filters are invalid. This is -/// detected by ticking a generation number every layout. -type Generation = u32; - -/// A pair of the bloom filter used for css selector matching, and the node to -/// which it applies. This is used to efficiently do `Descendant` selector -/// matches. Thanks to the bloom filter, we can avoid walking up the tree -/// looking for ancestors that aren't there in the majority of cases. -/// -/// As we walk down the DOM tree a task-local bloom filter is built of all the -/// CSS `SimpleSelector`s which are part of a `Descendant` compound selector -/// (i.e. paired with a `Descendant` combinator, in the `next` field of a -/// `CompoundSelector`. -/// -/// Before a `Descendant` selector match is tried, it's compared against the -/// bloom filter. If the bloom filter can exclude it, the selector is quickly -/// rejected. -/// -/// When done styling a node, all selectors previously inserted into the filter -/// are removed. -/// -/// Since a work-stealing queue is used for styling, sometimes, the bloom filter -/// will no longer be the for the parent of the node we're currently on. When -/// this happens, the task local bloom filter will be thrown away and rebuilt. -thread_local!( - static STYLE_BLOOM: RefCell<Option<(Box<BloomFilter>, UnsafeNode, Generation)>> = RefCell::new(None)); - -/// Returns the task local bloom filter. -/// -/// If one does not exist, a new one will be made for you. If it is out of date, -/// it will be cleared and reused. -fn take_task_local_bloom_filter<'ln, N>(parent_node: Option<N>, - root: OpaqueNode, - layout_context: &LayoutContext) - -> Box<BloomFilter> - where N: LayoutNode<'ln> { - STYLE_BLOOM.with(|style_bloom| { - match (parent_node, style_bloom.borrow_mut().take()) { - // Root node. Needs new bloom filter. - (None, _ ) => { - debug!("[{}] No parent, but new bloom filter!", tid()); - box BloomFilter::new() - } - // No bloom filter for this thread yet. - (Some(parent), None) => { - let mut bloom_filter = box BloomFilter::new(); - insert_ancestors_into_bloom_filter(&mut bloom_filter, parent, root); - bloom_filter - } - // Found cached bloom filter. - (Some(parent), Some((mut bloom_filter, old_node, old_generation))) => { - if old_node == parent.to_unsafe() && - old_generation == layout_context.shared_context().generation { - // Hey, the cached parent is our parent! We can reuse the bloom filter. - debug!("[{}] Parent matches (={}). Reusing bloom filter.", tid(), old_node.0); - } else { - // Oh no. the cached parent is stale. I guess we need a new one. Reuse the existing - // allocation to avoid malloc churn. - bloom_filter.clear(); - insert_ancestors_into_bloom_filter(&mut bloom_filter, parent, root); - } - bloom_filter - }, +pub struct RecalcStyleAndConstructFlows<'lc> { + context: LayoutContext<'lc>, + root: OpaqueNode, +} + +impl<'lc, 'ln, N: LayoutNode<'ln>> DomTraversalContext<'ln, N> for RecalcStyleAndConstructFlows<'lc> { + type SharedContext = SharedLayoutContext; + #[allow(unsafe_code)] + fn new<'a>(shared: &'a Self::SharedContext, root: OpaqueNode) -> Self { + // FIXME(bholley): This transmutation from &'a to &'lc is very unfortunate, but I haven't + // found a way to avoid it despite spending several days on it (and consulting Manishearth, + // brson, and nmatsakis). + // + // The crux of the problem is that parameterizing DomTraversalContext on the lifetime of + // the SharedContext doesn't work for a variety of reasons [1]. However, the code in + // parallel.rs needs to be able to use the DomTraversalContext trait (or something similar) + // to stack-allocate a struct (a generalized LayoutContext<'a>) that holds a borrowed + // SharedContext, which means that the struct needs to be parameterized on a lifetime. + // Given the aforementioned constraint, the only way to accomplish this is to avoid + // propagating the borrow lifetime from the struct to the trait, but that means that the + // new() method on the trait cannot require the lifetime of its argument to match the + // lifetime of the Self object it creates. + // + // This could be solved with an associated type with an unbound lifetime parameter, but + // that would require higher-kinded types, which don't exist yet and probably aren't coming + // for a while. + // + // So we transmute. :-( This is safe because the DomTravesalContext is stack-allocated on + // the worker thread while processing a WorkUnit, whereas the borrowed SharedContext is + // live for the entire duration of the restyle. This really could _almost_ compile: all + // we'd need to do is change the signature to to |new<'a: 'lc>|, and everything would + // work great. But we can't do that, because that would cause a mismatch with the signature + // in the trait we're implementing, and we can't mention 'lc in that trait at all for the + // reasons described above. + // + // [1] For example, the WorkQueue type needs to be parameterized on the concrete type of + // DomTraversalContext::SharedContext, and the WorkQueue lifetime is similar to that of the + // LayoutTask, generally much longer than that of a given SharedLayoutContext borrow. + let shared_lc: &'lc SharedLayoutContext = unsafe { mem::transmute(shared) }; + RecalcStyleAndConstructFlows { + context: LayoutContext::new(shared_lc), + root: root, } - }) -} - -fn put_task_local_bloom_filter(bf: Box<BloomFilter>, - unsafe_node: &UnsafeNode, - layout_context: &LayoutContext) { - STYLE_BLOOM.with(move |style_bloom| { - assert!(style_bloom.borrow().is_none(), - "Putting into a never-taken task-local bloom filter"); - *style_bloom.borrow_mut() = Some((bf, *unsafe_node, layout_context.shared_context().generation)); - }) -} - -/// "Ancestors" in this context is inclusive of ourselves. -fn insert_ancestors_into_bloom_filter<'ln, N>(bf: &mut Box<BloomFilter>, - mut n: N, - root: OpaqueNode) - where N: LayoutNode<'ln> { - debug!("[{}] Inserting ancestors.", tid()); - let mut ancestors = 0; - loop { - ancestors += 1; - - n.insert_into_bloom_filter(&mut **bf); - n = match n.layout_parent_node(root) { - None => break, - Some(p) => p, - }; } - debug!("[{}] Inserted {} ancestors.", tid(), ancestors); -} -#[derive(Copy, Clone)] -pub struct DomTraversalContext<'a> { - pub layout_context: &'a LayoutContext<'a>, - pub root: OpaqueNode, -} - -pub trait DomTraversal<'ln, N: LayoutNode<'ln>> { - fn process_preorder<'a>(context: &'a DomTraversalContext<'a>, node: N); - fn process_postorder<'a>(context: &'a DomTraversalContext<'a>, node: N); -} - -/// FIXME(bholley): I added this now to demonstrate the usefulness of the new design. -/// This is currently unused, but will be used shortly. -#[allow(dead_code)] -pub struct RecalcStyleOnly; -impl<'ln, N: LayoutNode<'ln>> DomTraversal<'ln, N> for RecalcStyleOnly { - fn process_preorder<'a>(context: &'a DomTraversalContext<'a>, node: N) { recalc_style_at(context, node); } - fn process_postorder<'a>(_: &'a DomTraversalContext<'a>, _: N) {} -} - -pub struct RecalcStyleAndConstructFlows; -impl<'ln, N: LayoutNode<'ln>> DomTraversal<'ln, N> for RecalcStyleAndConstructFlows { - fn process_preorder<'a>(context: &'a DomTraversalContext<'a>, node: N) { recalc_style_at(context, node); } - fn process_postorder<'a>(context: &'a DomTraversalContext<'a>, node: N) { construct_flows_at(context, node); } + fn process_preorder(&self, node: N) { recalc_style_at(&self.context, self.root, node); } + fn process_postorder(&self, node: N) { construct_flows_at(&self.context, self.root, node); } } /// A bottom-up, parallelizable traversal. @@ -149,107 +75,10 @@ pub trait PostorderNodeMutTraversal<'ln, ConcreteThreadSafeLayoutNode: ThreadSaf fn process(&mut self, node: &ConcreteThreadSafeLayoutNode) -> bool; } -/// The recalc-style-for-node traversal, which styles each node and must run before -/// layout computation. This computes the styles applied to each node. -#[inline] -#[allow(unsafe_code)] -fn recalc_style_at<'a, 'ln, N: LayoutNode<'ln>> (context: &'a DomTraversalContext<'a>, node: N) { - // Initialize layout data. - // - // FIXME(pcwalton): Stop allocating here. Ideally this should just be done by the HTML - // parser. - node.initialize_data(); - - // Get the parent node. - let parent_opt = node.layout_parent_node(context.root); - - // Get the style bloom filter. - let mut bf = take_task_local_bloom_filter(parent_opt, context.root, context.layout_context); - - let nonincremental_layout = opts::get().nonincremental_layout; - if nonincremental_layout || node.is_dirty() { - // Remove existing CSS styles from nodes whose content has changed (e.g. text changed), - // to force non-incremental reflow. - if node.has_changed() { - let node = node.to_threadsafe(); - node.unstyle(); - } - - // Check to see whether we can share a style with someone. - let style_sharing_candidate_cache = - &mut context.layout_context.style_sharing_candidate_cache(); - - let sharing_result = match node.as_element() { - Some(element) => { - unsafe { - element.share_style_if_possible(style_sharing_candidate_cache, - parent_opt.clone()) - } - }, - None => StyleSharingResult::CannotShare, - }; - - // Otherwise, match and cascade selectors. - match sharing_result { - StyleSharingResult::CannotShare => { - let mut applicable_declarations = ApplicableDeclarations::new(); - - let shareable_element = match node.as_element() { - Some(element) => { - // Perform the CSS selector matching. - let stylist = unsafe { &*context.layout_context.shared_context().stylist.0 }; - if element.match_element(stylist, - Some(&*bf), - &mut applicable_declarations) { - Some(element) - } else { - None - } - }, - None => { - if node.has_changed() { - node.set_restyle_damage(N::ConcreteRestyleDamage::rebuild_and_reflow()) - } - None - }, - }; - - // Perform the CSS cascade. - unsafe { - node.cascade_node(&context.layout_context.shared.style_context, - parent_opt, - &applicable_declarations, - &mut context.layout_context.applicable_declarations_cache(), - &context.layout_context.shared_context().new_animations_sender); - } - - // Add ourselves to the LRU cache. - if let Some(element) = shareable_element { - style_sharing_candidate_cache.insert_if_possible(&element); - } - } - StyleSharingResult::StyleWasShared(index, damage) => { - style_sharing_candidate_cache.touch(index); - node.set_restyle_damage(damage); - } - } - } - - let unsafe_layout_node = node.to_unsafe(); - - // Before running the children, we need to insert our nodes into the bloom - // filter. - debug!("[{}] + {:X}", tid(), unsafe_layout_node.0); - node.insert_into_bloom_filter(&mut *bf); - - // NB: flow construction updates the bloom filter on the way up. - put_task_local_bloom_filter(bf, &unsafe_layout_node, context.layout_context); -} - /// The flow construction traversal, which builds flows for styled nodes. #[inline] #[allow(unsafe_code)] -fn construct_flows_at<'a, 'ln, N: LayoutNode<'ln>>(context: &'a DomTraversalContext<'a>, node: N) { +fn construct_flows_at<'a, 'ln, N: LayoutNode<'ln>>(context: &'a LayoutContext<'a>, root: OpaqueNode, node: N) { // Construct flows for this node. { let tnode = node.to_threadsafe(); @@ -257,7 +86,7 @@ fn construct_flows_at<'a, 'ln, N: LayoutNode<'ln>>(context: &'a DomTraversalCont // Always reconstruct if incremental layout is turned off. let nonincremental_layout = opts::get().nonincremental_layout; if nonincremental_layout || node.has_dirty_descendants() { - let mut flow_constructor = FlowConstructor::new(context.layout_context); + let mut flow_constructor = FlowConstructor::new(context); if nonincremental_layout || !flow_constructor.repair_if_possible(&tnode) { flow_constructor.process(&tnode); debug!("Constructed flow for {:x}: {:x}", @@ -286,9 +115,9 @@ fn construct_flows_at<'a, 'ln, N: LayoutNode<'ln>>(context: &'a DomTraversalCont }); assert_eq!(old_node, unsafe_layout_node); - assert_eq!(old_generation, context.layout_context.shared_context().generation); + assert_eq!(old_generation, context.shared_context().generation); - match node.layout_parent_node(context.root) { + match node.layout_parent_node(root) { None => { debug!("[{}] - {:X}, and deleting BF.", tid(), unsafe_layout_node.0); // If this is the reflow root, eat the task-local bloom filter. @@ -297,7 +126,7 @@ fn construct_flows_at<'a, 'ln, N: LayoutNode<'ln>>(context: &'a DomTraversalCont // Otherwise, put it back, but remove this node. node.remove_from_bloom_filter(&mut *bf); let unsafe_parent = parent.to_unsafe(); - put_task_local_bloom_filter(bf, &unsafe_parent, context.layout_context); + put_task_local_bloom_filter(bf, &unsafe_parent, &context.shared_context()); }, }; } diff --git a/components/layout/wrapper.rs b/components/layout/wrapper.rs index 4a3ca347848..aa947937d0b 100644 --- a/components/layout/wrapper.rs +++ b/components/layout/wrapper.rs @@ -275,6 +275,14 @@ impl<'ln> TNode<'ln> for ServoLayoutNode<'ln> { self.node.next_sibling_ref().map(|node| self.new_with_this_lifetime(&node)) } } + + fn style(&self) -> Ref<Arc<ComputedValues>> { + Ref::map(self.borrow_data().unwrap(), |data| data.style.as_ref().unwrap()) + } + + fn unstyle(self) { + self.mutate_data().unwrap().style = None; + } } impl<'ln> LayoutNode<'ln> for ServoLayoutNode<'ln> { @@ -696,6 +704,8 @@ pub trait ThreadSafeLayoutNode<'ln> : Clone + Copy + Sized { /// Returns the style results for the given node. If CSS selector matching /// has not yet been performed, fails. + /// + /// Unlike the version on TNode, this handles pseudo-elements. #[inline] fn style(&self) -> Ref<Arc<ComputedValues>> { Ref::map(self.borrow_layout_data().unwrap(), |data| { @@ -709,6 +719,8 @@ pub trait ThreadSafeLayoutNode<'ln> : Clone + Copy + Sized { } /// Removes the style from this node. + /// + /// Unlike the version on TNode, this handles pseudo-elements. fn unstyle(self) { let mut data = self.mutate_layout_data().unwrap(); let style = diff --git a/components/net/fetch/request.rs b/components/net/fetch/request.rs index 3c3c10f45a5..0980e07c3e5 100644 --- a/components/net/fetch/request.rs +++ b/components/net/fetch/request.rs @@ -19,7 +19,7 @@ use net_traits::response::{CacheState, HttpsState, Response, ResponseType, Termi use net_traits::{AsyncFetchListener, Metadata}; use resource_task::CancellationListener; use std::ascii::AsciiExt; -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::rc::Rc; use std::str::FromStr; use std::thread; @@ -100,17 +100,17 @@ pub enum ResponseTainting { /// A [Request](https://fetch.spec.whatwg.org/#requests) as defined by the Fetch spec #[derive(Clone)] pub struct Request { - pub method: Method, + pub method: RefCell<Method>, // Use the last method on url_list to act as spec url field - pub url_list: Vec<Url>, - pub headers: Headers, + pub url_list: RefCell<Vec<Url>>, + pub headers: RefCell<Headers>, pub unsafe_request: bool, pub body: Option<Vec<u8>>, pub preserve_content_codings: bool, // pub client: GlobalRef, // XXXManishearth copy over only the relevant fields of the global scope, // not the entire scope to avoid the libscript dependency pub is_service_worker_global_scope: bool, - pub skip_service_worker: bool, + pub skip_service_worker: Cell<bool>, pub context: Context, pub context_frame_type: ContextFrameType, pub origin: Option<Url>, // FIXME: Use Url::Origin @@ -123,23 +123,23 @@ pub struct Request { pub mode: RequestMode, pub credentials_mode: CredentialsMode, pub use_url_credentials: bool, - pub cache_mode: CacheMode, + pub cache_mode: Cell<CacheMode>, pub redirect_mode: RedirectMode, - pub redirect_count: u32, + pub redirect_count: Cell<u32>, pub response_tainting: ResponseTainting } impl Request { pub fn new(url: Url, context: Context, is_service_worker_global_scope: bool) -> Request { Request { - method: Method::Get, - url_list: vec![url], - headers: Headers::new(), + method: RefCell::new(Method::Get), + url_list: RefCell::new(vec![url]), + headers: RefCell::new(Headers::new()), unsafe_request: false, body: None, preserve_content_codings: false, is_service_worker_global_scope: is_service_worker_global_scope, - skip_service_worker: false, + skip_service_worker: Cell::new(false), context: context, context_frame_type: ContextFrameType::ContextNone, origin: None, @@ -152,38 +152,38 @@ impl Request { mode: RequestMode::NoCORS, credentials_mode: CredentialsMode::Omit, use_url_credentials: false, - cache_mode: CacheMode::Default, + cache_mode: Cell::new(CacheMode::Default), redirect_mode: RedirectMode::Follow, - redirect_count: 0, + redirect_count: Cell::new(0), response_tainting: ResponseTainting::Basic, } } fn get_last_url_string(&self) -> String { - self.url_list.last().unwrap().serialize() + self.url_list.borrow().last().unwrap().serialize() } - fn current_url(&self) -> &Url { - self.url_list.last().unwrap() + fn current_url(&self) -> Url { + self.url_list.borrow().last().unwrap().clone() } } pub fn fetch_async(request: Request, cors_flag: bool, listener: Box<AsyncFetchListener + Send>) { spawn_named(format!("fetch for {:?}", request.get_last_url_string()), move || { - let request = Rc::new(RefCell::new(request)); + let request = Rc::new(request); let res = fetch(request, cors_flag); listener.response_available(res); }) } /// [Fetch](https://fetch.spec.whatwg.org#concept-fetch) -fn fetch(request: Rc<RefCell<Request>>, cors_flag: bool) -> Response { +pub fn fetch(request: Rc<Request>, cors_flag: bool) -> Response { // Step 1 - if request.borrow().context != Context::Fetch && !request.borrow().headers.has::<Accept>() { + if request.context != Context::Fetch && !request.headers.borrow().has::<Accept>() { // Substep 1 - let value = match request.borrow().context { + let value = match request.context { Context::Favicon | Context::Image | Context::ImageSet => vec![qitem(Mime(TopLevel::Image, SubLevel::Png, vec![])), @@ -203,7 +203,7 @@ fn fetch(request: Rc<RefCell<Request>>, cors_flag: bool) -> Response { QualityItem::new(Mime(TopLevel::Application, SubLevel::Xml, vec![]), q(0.9)), QualityItem::new(Mime(TopLevel::Star, SubLevel::Star, vec![]), q(0.8))], - Context::Internal if request.borrow().context_frame_type != ContextFrameType::ContextNone + Context::Internal if request.context_frame_type != ContextFrameType::ContextNone => vec![qitem(Mime(TopLevel::Text, SubLevel::Html, vec![])), // FIXME: This should properly generate a MimeType that has a // SubLevel of xhtml+xml (https://github.com/hyperium/mime.rs/issues/22) @@ -218,12 +218,12 @@ fn fetch(request: Rc<RefCell<Request>>, cors_flag: bool) -> Response { }; // Substep 2 - request.borrow_mut().headers.set(Accept(value)); + request.headers.borrow_mut().set(Accept(value)); } // Step 2 - if request.borrow().context != Context::Fetch && !request.borrow().headers.has::<AcceptLanguage>() { - request.borrow_mut().headers.set(AcceptLanguage(vec![qitem("en-US".parse().unwrap())])); + if request.context != Context::Fetch && !request.headers.borrow().has::<AcceptLanguage>() { + request.headers.borrow_mut().set(AcceptLanguage(vec![qitem("en-US".parse().unwrap())])); } // TODO: Figure out what a Priority object is @@ -233,17 +233,16 @@ fn fetch(request: Rc<RefCell<Request>>, cors_flag: bool) -> Response { } /// [Main fetch](https://fetch.spec.whatwg.org/#concept-main-fetch) -fn main_fetch(request: Rc<RefCell<Request>>, _cors_flag: bool) -> Response { +fn main_fetch(request: Rc<Request>, _cors_flag: bool) -> Response { // TODO: Implement main fetch spec let _ = basic_fetch(request); Response::network_error() } /// [Basic fetch](https://fetch.spec.whatwg.org#basic-fetch) -fn basic_fetch(request: Rc<RefCell<Request>>) -> Response { +fn basic_fetch(request: Rc<Request>) -> Response { - let req = request.borrow(); - let url = req.url_list.last().unwrap(); + let url = request.current_url(); let scheme = url.scheme.clone(); match &*scheme { @@ -281,7 +280,7 @@ fn http_fetch_async(request: Request, listener: Box<AsyncFetchListener + Send>) { spawn_named(format!("http_fetch for {:?}", request.get_last_url_string()), move || { - let request = Rc::new(RefCell::new(request)); + let request = Rc::new(request); let res = http_fetch(request, BasicCORSCache::new(), cors_flag, cors_preflight_flag, authentication_fetch_flag); @@ -290,7 +289,7 @@ fn http_fetch_async(request: Request, } /// [HTTP fetch](https://fetch.spec.whatwg.org#http-fetch) -fn http_fetch(request: Rc<RefCell<Request>>, +fn http_fetch(request: Rc<Request>, mut cache: BasicCORSCache, cors_flag: bool, cors_preflight_flag: bool, @@ -303,7 +302,7 @@ fn http_fetch(request: Rc<RefCell<Request>>, let mut actual_response: Option<Rc<RefCell<Response>>> = None; // Step 3 - if !request.borrow().skip_service_worker && !request.borrow().is_service_worker_global_scope { + if !request.skip_service_worker.get() && !request.is_service_worker_global_scope { // TODO: Substep 1 (handle fetch unimplemented) if let Some(ref res) = response { @@ -317,9 +316,9 @@ fn http_fetch(request: Rc<RefCell<Request>>, // Substep 3 if (resp.response_type == ResponseType::Opaque && - request.borrow().mode != RequestMode::NoCORS) || + request.mode != RequestMode::NoCORS) || (resp.response_type == ResponseType::OpaqueRedirect && - request.borrow().redirect_mode != RedirectMode::Manual) || + request.redirect_mode != RedirectMode::Manual) || resp.response_type == ResponseType::Error { return Response::network_error(); } @@ -329,7 +328,7 @@ fn http_fetch(request: Rc<RefCell<Request>>, if let Some(ref res) = actual_response { let mut resp = res.borrow_mut(); if resp.url_list.is_empty() { - resp.url_list = request.borrow().url_list.clone(); + resp.url_list = request.url_list.borrow().clone(); } } @@ -347,18 +346,18 @@ fn http_fetch(request: Rc<RefCell<Request>>, // FIXME: Once Url::Origin is available, rewrite origin to // take an Origin instead of a Url - let origin = request.borrow().origin.clone().unwrap_or(Url::parse("").unwrap()); - let url = request.borrow().url_list.last().unwrap().clone(); - let credentials = request.borrow().credentials_mode == CredentialsMode::Include; + let origin = request.origin.clone().unwrap_or(Url::parse("").unwrap()); + let url = request.current_url(); + let credentials = request.credentials_mode == CredentialsMode::Include; let method_cache_match = cache.match_method(CacheRequestDetails { origin: origin.clone(), destination: url.clone(), credentials: credentials - }, request.borrow().method.clone()); + }, request.method.borrow().clone()); - method_mismatch = !method_cache_match && (!is_simple_method(&request.borrow().method) || - request.borrow().mode == RequestMode::ForcedPreflightMode); - header_mismatch = request.borrow().headers.iter().any(|view| + method_mismatch = !method_cache_match && (!is_simple_method(&request.method.borrow()) || + request.mode == RequestMode::ForcedPreflightMode); + header_mismatch = request.headers.borrow().iter().any(|view| !cache.match_header(CacheRequestDetails { origin: origin.clone(), destination: url.clone(), @@ -376,13 +375,13 @@ fn http_fetch(request: Rc<RefCell<Request>>, } // Substep 2 - request.borrow_mut().skip_service_worker = true; + request.skip_service_worker.set(true); // Substep 3 - let credentials = match request.borrow().credentials_mode { + let credentials = match request.credentials_mode { CredentialsMode::Include => true, CredentialsMode::CredentialsSameOrigin if (!cors_flag || - request.borrow().response_tainting == ResponseTainting::Opaque) + request.response_tainting == ResponseTainting::Opaque) => true, _ => false }; @@ -410,7 +409,7 @@ fn http_fetch(request: Rc<RefCell<Request>>, StatusCode::TemporaryRedirect | StatusCode::PermanentRedirect => { // Step 1 - if request.borrow().redirect_mode == RedirectMode::Error { + if request.redirect_mode == RedirectMode::Error { return Response::network_error(); } @@ -425,7 +424,7 @@ fn http_fetch(request: Rc<RefCell<Request>>, }; // Step 5 - let location_url = UrlParser::new().base_url(request.borrow().url_list.last().unwrap()).parse(&*location); + let location_url = UrlParser::new().base_url(&request.current_url()).parse(&*location); // Step 6 let location_url = match location_url { @@ -435,14 +434,14 @@ fn http_fetch(request: Rc<RefCell<Request>>, }; // Step 7 - if request.borrow().redirect_count == 20 { + if request.redirect_count.get() == 20 { return Response::network_error(); } // Step 8 - request.borrow_mut().redirect_count += 1; + request.redirect_count.set(request.redirect_count.get() + 1); - match request.borrow().redirect_mode { + match request.redirect_mode { // Step 9 RedirectMode::Manual => { @@ -454,9 +453,9 @@ fn http_fetch(request: Rc<RefCell<Request>>, // Substep 1 // FIXME: Use Url::origin - // if (request.borrow().mode == RequestMode::CORSMode || - // request.borrow().mode == RequestMode::ForcedPreflightMode) && - // location_url.origin() != request.borrow().url.origin() && + // if (request.mode == RequestMode::CORSMode || + // request.mode == RequestMode::ForcedPreflightMode) && + // location_url.origin() != request.url.origin() && // has_credentials(&location_url) { // return Response::network_error(); // } @@ -468,7 +467,7 @@ fn http_fetch(request: Rc<RefCell<Request>>, // Substep 3 // FIXME: Use Url::origin - // if cors_flag && location_url.origin() != request.borrow().url.origin() { + // if cors_flag && location_url.origin() != request.url.origin() { // request.borrow_mut().origin = Origin::UID(OpaqueOrigin); // } @@ -476,12 +475,12 @@ fn http_fetch(request: Rc<RefCell<Request>>, if actual_response.status.unwrap() == StatusCode::SeeOther || ((actual_response.status.unwrap() == StatusCode::MovedPermanently || actual_response.status.unwrap() == StatusCode::Found) && - request.borrow().method == Method::Post) { - request.borrow_mut().method = Method::Get; + *request.method.borrow() == Method::Post) { + *request.method.borrow_mut() = Method::Get; } // Substep 5 - request.borrow_mut().url_list.push(location_url); + request.url_list.borrow_mut().push(location_url); // Substep 6 return main_fetch(request.clone(), cors_flag); @@ -503,7 +502,7 @@ fn http_fetch(request: Rc<RefCell<Request>>, // TODO: Spec says requires testing on multiple WWW-Authenticate headers // Step 3 - if !request.borrow().use_url_credentials || authentication_fetch_flag { + if !request.use_url_credentials || authentication_fetch_flag { // TODO: Prompt the user for username and password from the window } @@ -544,7 +543,7 @@ fn http_fetch(request: Rc<RefCell<Request>>, } /// [HTTP network or cache fetch](https://fetch.spec.whatwg.org#http-network-or-cache-fetch) -fn http_network_or_cache_fetch(request: Rc<RefCell<Request>>, +fn http_network_or_cache_fetch(request: Rc<Request>, credentials_flag: bool, authentication_fetch_flag: bool) -> Response { @@ -553,15 +552,15 @@ fn http_network_or_cache_fetch(request: Rc<RefCell<Request>>, // Step 1 let http_request = if request_has_no_window && - request.borrow().redirect_mode != RedirectMode::Follow { + request.redirect_mode != RedirectMode::Follow { request.clone() } else { - Rc::new(RefCell::new(request.borrow().clone())) + Rc::new((*request).clone()) }; - let content_length_value = match http_request.borrow().body { + let content_length_value = match http_request.body { None => - match http_request.borrow().method { + match *http_request.method.borrow() { // Step 3 Method::Head | Method::Post | Method::Put => Some(0), @@ -574,15 +573,15 @@ fn http_network_or_cache_fetch(request: Rc<RefCell<Request>>, // Step 5 if let Some(content_length_value) = content_length_value { - http_request.borrow_mut().headers.set(ContentLength(content_length_value)); + http_request.headers.borrow_mut().set(ContentLength(content_length_value)); } // Step 6 - match http_request.borrow().referer { + match http_request.referer { Referer::NoReferer => - http_request.borrow_mut().headers.set(RefererHeader("".to_owned())), + http_request.headers.borrow_mut().set(RefererHeader("".to_owned())), Referer::RefererUrl(ref http_request_referer) => - http_request.borrow_mut().headers.set(RefererHeader(http_request_referer.serialize())), + http_request.headers.borrow_mut().set(RefererHeader(http_request_referer.serialize())), Referer::Client => // it should be impossible for referer to be anything else during fetching // https://fetch.spec.whatwg.org/#concept-request-referrer @@ -590,25 +589,25 @@ fn http_network_or_cache_fetch(request: Rc<RefCell<Request>>, }; // Step 7 - if http_request.borrow().omit_origin_header == false { + if http_request.omit_origin_header == false { // TODO update this when https://github.com/hyperium/hyper/pull/691 is finished - if let Some(ref _origin) = http_request.borrow().origin { - // http_request.borrow_mut().headers.set_raw("origin", origin); + if let Some(ref _origin) = http_request.origin { + // http_request.headers.borrow_mut().set_raw("origin", origin); } } // Step 8 - if !http_request.borrow().headers.has::<UserAgent>() { - http_request.borrow_mut().headers.set(UserAgent(global_user_agent().to_owned())); + if !http_request.headers.borrow().has::<UserAgent>() { + http_request.headers.borrow_mut().set(UserAgent(global_user_agent().to_owned())); } // Step 9 - if http_request.borrow().cache_mode == CacheMode::Default && is_no_store_cache(&http_request.borrow().headers) { - http_request.borrow_mut().cache_mode = CacheMode::NoStore; + if http_request.cache_mode.get() == CacheMode::Default && is_no_store_cache(&http_request.headers.borrow()) { + http_request.cache_mode.set(CacheMode::NoStore); } // Step 10 - // modify_request_headers(http_request.borrow().headers); + // modify_request_headers(http_request.headers.borrow()); // Step 11 // TODO some of this step can't be implemented yet @@ -625,10 +624,9 @@ fn http_network_or_cache_fetch(request: Rc<RefCell<Request>>, // Substep 4 if authentication_fetch_flag { - let http_req = http_request.borrow(); - let current_url = http_req.current_url(); + let current_url = http_request.current_url(); - authorization_value = if includes_credentials(current_url) { + authorization_value = if includes_credentials(¤t_url) { Some(Basic { username: current_url.username().unwrap_or("").to_owned(), password: current_url.password().map(str::to_owned) @@ -641,7 +639,7 @@ fn http_network_or_cache_fetch(request: Rc<RefCell<Request>>, // Substep 5 if let Some(basic) = authorization_value { - http_request.borrow_mut().headers.set(Authorization(basic)); + http_request.headers.borrow_mut().set(Authorization(basic)); } } @@ -654,12 +652,12 @@ fn http_network_or_cache_fetch(request: Rc<RefCell<Request>>, // Step 14 // TODO have a HTTP cache to check for a completed response let complete_http_response_from_cache: Option<Response> = None; - if http_request.borrow().cache_mode != CacheMode::NoStore && - http_request.borrow().cache_mode != CacheMode::Reload && + if http_request.cache_mode.get() != CacheMode::NoStore && + http_request.cache_mode.get() != CacheMode::Reload && complete_http_response_from_cache.is_some() { // Substep 1 - if http_request.borrow().cache_mode == CacheMode::ForceCache { + if http_request.cache_mode.get() == CacheMode::ForceCache { // TODO pull response from HTTP cache // response = http_request } @@ -670,23 +668,23 @@ fn http_network_or_cache_fetch(request: Rc<RefCell<Request>>, }; // Substep 2 - if !revalidation_needed && http_request.borrow().cache_mode == CacheMode::Default { + if !revalidation_needed && http_request.cache_mode.get() == CacheMode::Default { // TODO pull response from HTTP cache // response = http_request // response.cache_state = CacheState::Local; } // Substep 3 - if revalidation_needed && http_request.borrow().cache_mode == CacheMode::Default || - http_request.borrow_mut().cache_mode == CacheMode::NoCache { + if revalidation_needed && http_request.cache_mode.get() == CacheMode::Default || + http_request.cache_mode.get() == CacheMode::NoCache { // TODO this substep } // Step 15 // TODO have a HTTP cache to check for a partial response - } else if http_request.borrow().cache_mode == CacheMode::Default || - http_request.borrow().cache_mode == CacheMode::ForceCache { + } else if http_request.cache_mode.get() == CacheMode::Default || + http_request.cache_mode.get() == CacheMode::ForceCache { // TODO this substep } @@ -699,8 +697,8 @@ fn http_network_or_cache_fetch(request: Rc<RefCell<Request>>, // Step 17 if let Some(status) = response.status { if status == StatusCode::NotModified && - (http_request.borrow().cache_mode == CacheMode::Default || - http_request.borrow().cache_mode == CacheMode::NoCache) { + (http_request.cache_mode.get() == CacheMode::Default || + http_request.cache_mode.get() == CacheMode::NoCache) { // Substep 1 // TODO this substep @@ -727,8 +725,8 @@ fn http_network_or_cache_fetch(request: Rc<RefCell<Request>>, } /// [HTTP network fetch](https://fetch.spec.whatwg.org/#http-network-fetch) -fn http_network_fetch(request: Rc<RefCell<Request>>, - http_request: Rc<RefCell<Request>>, +fn http_network_fetch(request: Rc<Request>, + http_request: Rc<Request>, credentials_flag: bool) -> Response { // TODO: Implement HTTP network fetch spec @@ -746,13 +744,16 @@ fn http_network_fetch(request: Rc<RefCell<Request>>, let factory = NetworkHttpRequestFactory { connector: connection, }; - let req = request.borrow(); - let url = req.current_url(); + let url = request.current_url(); let cancellation_listener = CancellationListener::new(None); - let wrapped_response = obtain_response(&factory, &url, &req.method, &mut request.borrow_mut().headers, - &cancellation_listener, &None, &req.method, - &None, req.redirect_count, &None, ""); + let wrapped_response = obtain_response(&factory, &url, &request.method.borrow(), + // TODO nikkisquared: use this line instead + // after merging with another branch + // &request.headers.borrow() + &mut *request.headers.borrow_mut(), + &cancellation_listener, &None, &request.method.borrow(), + &None, request.redirect_count.get(), &None, ""); let mut response = Response::new(); match wrapped_response { @@ -792,7 +793,7 @@ fn http_network_fetch(request: Rc<RefCell<Request>>, }; // Step 6 - response.url_list = request.borrow().url_list.clone(); + response.url_list = request.url_list.borrow().clone(); // Step 7 @@ -818,13 +819,13 @@ fn http_network_fetch(request: Rc<RefCell<Request>>, } /// [CORS preflight fetch](https://fetch.spec.whatwg.org#cors-preflight-fetch) -fn preflight_fetch(request: Rc<RefCell<Request>>) -> Response { +fn preflight_fetch(request: Rc<Request>) -> Response { // TODO: Implement preflight fetch spec Response::network_error() } /// [CORS check](https://fetch.spec.whatwg.org#concept-cors-check) -fn cors_check(request: Rc<RefCell<Request>>, response: &Response) -> Result<(), ()> { +fn cors_check(request: Rc<Request>, response: &Response) -> Result<(), ()> { // TODO: Implement CORS check spec Err(()) } diff --git a/components/servo/Cargo.lock b/components/servo/Cargo.lock index 264fbbdc470..8071d0e8829 100644 --- a/components/servo/Cargo.lock +++ b/components/servo/Cargo.lock @@ -650,6 +650,8 @@ name = "gfx_tests" version = "0.0.1" dependencies = [ "gfx 0.0.1", + "ipc-channel 0.1.0 (git+https://github.com/servo/ipc-channel)", + "style 0.0.1", ] [[package]] diff --git a/components/style/dom.rs b/components/style/dom.rs index 40933b03a7e..f85484e0c70 100644 --- a/components/style/dom.rs +++ b/components/style/dom.rs @@ -156,6 +156,14 @@ pub trait TNode<'ln> : Sized + Copy + Clone { fn prev_sibling(&self) -> Option<Self>; fn next_sibling(&self) -> Option<Self>; + + + /// Returns the style results for the given node. If CSS selector matching + /// has not yet been performed, fails. + fn style(&self) -> Ref<Arc<ComputedValues>>; + + /// Removes the style from this node. + fn unstyle(self); } pub trait TDocument<'ld> : Sized + Copy + Clone { diff --git a/components/style/lib.rs b/components/style/lib.rs index e010a92f0b2..0f0dfca30cf 100644 --- a/components/style/lib.rs +++ b/components/style/lib.rs @@ -53,10 +53,13 @@ pub mod dom; pub mod font_face; pub mod matching; pub mod media_queries; +pub mod parallel; pub mod parser; pub mod restyle_hints; pub mod selector_matching; +pub mod sequential; pub mod stylesheets; +pub mod traversal; #[macro_use] #[allow(non_camel_case_types)] pub mod values; diff --git a/components/style/parallel.rs b/components/style/parallel.rs new file mode 100644 index 00000000000..cb8e8260a21 --- /dev/null +++ b/components/style/parallel.rs @@ -0,0 +1,141 @@ +/* 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/. */ + +//! Implements parallel traversal over the DOM tree. +//! +//! This code is highly unsafe. Keep this file small and easy to audit. + +#![allow(unsafe_code)] + +use dom::{OpaqueNode, TNode, UnsafeNode}; +use std::mem; +use std::sync::atomic::Ordering; +use traversal::DomTraversalContext; +use util::workqueue::{WorkQueue, WorkUnit, WorkerProxy}; + +#[allow(dead_code)] +fn static_assertion(node: UnsafeNode) { + unsafe { + let _: UnsafeNodeList = ::std::intrinsics::transmute(node); + } +} + +pub type UnsafeNodeList = (Box<Vec<UnsafeNode>>, OpaqueNode); + +pub const CHUNK_SIZE: usize = 64; + +pub struct WorkQueueData(usize, usize); + +pub fn run_queue_with_custom_work_data_type<To, F, SharedContext: Sync>( + queue: &mut WorkQueue<SharedContext, WorkQueueData>, + callback: F, + shared: &SharedContext) + where To: 'static + Send, F: FnOnce(&mut WorkQueue<SharedContext, To>) { + let queue: &mut WorkQueue<SharedContext, To> = unsafe { + mem::transmute(queue) + }; + callback(queue); + queue.run(shared); +} + +pub fn traverse_dom<'ln, N, C>(root: N, + queue_data: &C::SharedContext, + queue: &mut WorkQueue<C::SharedContext, WorkQueueData>) + where N: TNode<'ln>, C: DomTraversalContext<'ln, N> { + run_queue_with_custom_work_data_type(queue, |queue| { + queue.push(WorkUnit { + fun: top_down_dom::<N, C>, + data: (box vec![root.to_unsafe()], root.opaque()), + }); + }, queue_data); +} + +/// A parallel top-down DOM traversal. +#[inline(always)] +fn top_down_dom<'ln, N, C>(unsafe_nodes: UnsafeNodeList, + proxy: &mut WorkerProxy<C::SharedContext, UnsafeNodeList>) + where N: TNode<'ln>, C: DomTraversalContext<'ln, N> { + let context = C::new(proxy.user_data(), unsafe_nodes.1); + + let mut discovered_child_nodes = Vec::new(); + for unsafe_node in *unsafe_nodes.0 { + // Get a real layout node. + let node = unsafe { N::from_unsafe(&unsafe_node) }; + + // Perform the appropriate traversal. + context.process_preorder(node); + + let child_count = node.children_count(); + + // Reset the count of children. + { + let data = node.mutate_data().unwrap(); + data.parallel.children_count.store(child_count as isize, + Ordering::Relaxed); + } + + // Possibly enqueue the children. + if child_count != 0 { + for kid in node.children() { + discovered_child_nodes.push(kid.to_unsafe()) + } + } else { + // If there were no more children, start walking back up. + bottom_up_dom::<N, C>(unsafe_nodes.1, unsafe_node, proxy) + } + } + + for chunk in discovered_child_nodes.chunks(CHUNK_SIZE) { + proxy.push(WorkUnit { + fun: top_down_dom::<N, C>, + data: (box chunk.iter().cloned().collect(), unsafe_nodes.1), + }); + } +} + +/// Process current node and potentially traverse its ancestors. +/// +/// If we are the last child that finished processing, recursively process +/// our parent. Else, stop. Also, stop at the root. +/// +/// Thus, if we start with all the leaves of a tree, we end up traversing +/// the whole tree bottom-up because each parent will be processed exactly +/// once (by the last child that finishes processing). +/// +/// The only communication between siblings is that they both +/// fetch-and-subtract the parent's children count. +fn bottom_up_dom<'ln, N, C>(root: OpaqueNode, + unsafe_node: UnsafeNode, + proxy: &mut WorkerProxy<C::SharedContext, UnsafeNodeList>) + where N: TNode<'ln>, C: DomTraversalContext<'ln, N> { + let context = C::new(proxy.user_data(), root); + + // Get a real layout node. + let mut node = unsafe { N::from_unsafe(&unsafe_node) }; + loop { + // Perform the appropriate operation. + context.process_postorder(node); + + let parent = match node.layout_parent_node(root) { + None => break, + Some(parent) => parent, + }; + + let parent_data = unsafe { + &*parent.borrow_data_unchecked().unwrap() + }; + + if parent_data + .parallel + .children_count + .fetch_sub(1, Ordering::Relaxed) != 1 { + // Get out of here and find another node to work on. + break + } + + // We were the last child of our parent. Construct flows for our parent. + node = parent; + } +} + diff --git a/components/style/sequential.rs b/components/style/sequential.rs new file mode 100644 index 00000000000..9dfbb0126c1 --- /dev/null +++ b/components/style/sequential.rs @@ -0,0 +1,28 @@ +/* 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/. */ + +//! Implements sequential traversal over the DOM tree. + +use dom::TNode; +use traversal::DomTraversalContext; + +pub fn traverse_dom<'ln, N, C>(root: N, + shared: &C::SharedContext) + where N: TNode<'ln>, + C: DomTraversalContext<'ln, N> { + fn doit<'a, 'ln, N, C>(context: &'a C, node: N) + where N: TNode<'ln>, C: DomTraversalContext<'ln, N> { + context.process_preorder(node); + + for kid in node.children() { + doit::<N, C>(context, kid); + } + + context.process_postorder(node); + } + + let context = C::new(shared, root.opaque()); + doit::<N, C>(&context, root); +} + diff --git a/components/style/traversal.rs b/components/style/traversal.rs new file mode 100644 index 00000000000..c3307aa2593 --- /dev/null +++ b/components/style/traversal.rs @@ -0,0 +1,259 @@ +/* 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/. */ + +use context::{LocalStyleContext, SharedStyleContext, StyleContext}; +use dom::{OpaqueNode, TNode, TRestyleDamage, UnsafeNode}; +use matching::{ApplicableDeclarations, ElementMatchMethods, MatchMethods, StyleSharingResult}; +use selectors::bloom::BloomFilter; +use std::cell::RefCell; +use std::mem; +use std::rc::Rc; +use util::opts; +use util::tid::tid; + +/// Every time we do another layout, the old bloom filters are invalid. This is +/// detected by ticking a generation number every layout. +pub type Generation = u32; + +/// A pair of the bloom filter used for css selector matching, and the node to +/// which it applies. This is used to efficiently do `Descendant` selector +/// matches. Thanks to the bloom filter, we can avoid walking up the tree +/// looking for ancestors that aren't there in the majority of cases. +/// +/// As we walk down the DOM tree a task-local bloom filter is built of all the +/// CSS `SimpleSelector`s which are part of a `Descendant` compound selector +/// (i.e. paired with a `Descendant` combinator, in the `next` field of a +/// `CompoundSelector`. +/// +/// Before a `Descendant` selector match is tried, it's compared against the +/// bloom filter. If the bloom filter can exclude it, the selector is quickly +/// rejected. +/// +/// When done styling a node, all selectors previously inserted into the filter +/// are removed. +/// +/// Since a work-stealing queue is used for styling, sometimes, the bloom filter +/// will no longer be the for the parent of the node we're currently on. When +/// this happens, the task local bloom filter will be thrown away and rebuilt. +thread_local!( + pub static STYLE_BLOOM: RefCell<Option<(Box<BloomFilter>, UnsafeNode, Generation)>> = RefCell::new(None)); + +/// Returns the task local bloom filter. +/// +/// If one does not exist, a new one will be made for you. If it is out of date, +/// it will be cleared and reused. +fn take_task_local_bloom_filter<'ln, N>(parent_node: Option<N>, + root: OpaqueNode, + context: &SharedStyleContext) + -> Box<BloomFilter> + where N: TNode<'ln> { + STYLE_BLOOM.with(|style_bloom| { + match (parent_node, style_bloom.borrow_mut().take()) { + // Root node. Needs new bloom filter. + (None, _ ) => { + debug!("[{}] No parent, but new bloom filter!", tid()); + box BloomFilter::new() + } + // No bloom filter for this thread yet. + (Some(parent), None) => { + let mut bloom_filter = box BloomFilter::new(); + insert_ancestors_into_bloom_filter(&mut bloom_filter, parent, root); + bloom_filter + } + // Found cached bloom filter. + (Some(parent), Some((mut bloom_filter, old_node, old_generation))) => { + if old_node == parent.to_unsafe() && + old_generation == context.generation { + // Hey, the cached parent is our parent! We can reuse the bloom filter. + debug!("[{}] Parent matches (={}). Reusing bloom filter.", tid(), old_node.0); + } else { + // Oh no. the cached parent is stale. I guess we need a new one. Reuse the existing + // allocation to avoid malloc churn. + bloom_filter.clear(); + insert_ancestors_into_bloom_filter(&mut bloom_filter, parent, root); + } + bloom_filter + }, + } + }) +} + +pub fn put_task_local_bloom_filter(bf: Box<BloomFilter>, + unsafe_node: &UnsafeNode, + context: &SharedStyleContext) { + STYLE_BLOOM.with(move |style_bloom| { + assert!(style_bloom.borrow().is_none(), + "Putting into a never-taken task-local bloom filter"); + *style_bloom.borrow_mut() = Some((bf, *unsafe_node, context.generation)); + }) +} + +/// "Ancestors" in this context is inclusive of ourselves. +fn insert_ancestors_into_bloom_filter<'ln, N>(bf: &mut Box<BloomFilter>, + mut n: N, + root: OpaqueNode) + where N: TNode<'ln> { + debug!("[{}] Inserting ancestors.", tid()); + let mut ancestors = 0; + loop { + ancestors += 1; + + n.insert_into_bloom_filter(&mut **bf); + n = match n.layout_parent_node(root) { + None => break, + Some(p) => p, + }; + } + debug!("[{}] Inserted {} ancestors.", tid(), ancestors); +} + +pub trait DomTraversalContext<'ln, N: TNode<'ln>> { + type SharedContext: Sync + 'static; + fn new<'a>(&'a Self::SharedContext, OpaqueNode) -> Self; + fn process_preorder(&self, node: N); + fn process_postorder(&self, node: N); +} + +/// FIXME(bholley): I added this now to demonstrate the usefulness of the new design. +/// This is currently unused, but will be used shortly. + +#[allow(dead_code)] +pub struct StandaloneStyleContext<'a> { + pub shared: &'a SharedStyleContext, + cached_local_style_context: Rc<LocalStyleContext>, +} + +impl<'a> StandaloneStyleContext<'a> { + pub fn new(_: &'a SharedStyleContext) -> Self { panic!("Not implemented") } +} + +impl<'a> StyleContext<'a> for StandaloneStyleContext<'a> { + fn shared_context(&self) -> &'a SharedStyleContext { + &self.shared + } + + fn local_context(&self) -> &LocalStyleContext { + &self.cached_local_style_context + } +} + +#[allow(dead_code)] +pub struct RecalcStyleOnly<'lc> { + context: StandaloneStyleContext<'lc>, + root: OpaqueNode, +} + +impl<'lc, 'ln, N: TNode<'ln>> DomTraversalContext<'ln, N> for RecalcStyleOnly<'lc> { + type SharedContext = SharedStyleContext; + #[allow(unsafe_code)] + fn new<'a>(shared: &'a Self::SharedContext, root: OpaqueNode) -> Self { + // See the comment in RecalcStyleAndConstructFlows::new for an explanation of why this is + // necessary. + let shared_lc: &'lc SharedStyleContext = unsafe { mem::transmute(shared) }; + RecalcStyleOnly { + context: StandaloneStyleContext::new(shared_lc), + root: root, + } + } + + fn process_preorder(&self, node: N) { recalc_style_at(&self.context, self.root, node); } + fn process_postorder(&self, _: N) {} +} + +/// The recalc-style-for-node traversal, which styles each node and must run before +/// layout computation. This computes the styles applied to each node. +#[inline] +#[allow(unsafe_code)] +pub fn recalc_style_at<'a, 'ln, N: TNode<'ln>, C: StyleContext<'a>> (context: &'a C, root: OpaqueNode, node: N) { + // Initialize layout data. + // + // FIXME(pcwalton): Stop allocating here. Ideally this should just be done by the HTML + // parser. + node.initialize_data(); + + // Get the parent node. + let parent_opt = node.layout_parent_node(root); + + // Get the style bloom filter. + let mut bf = take_task_local_bloom_filter(parent_opt, root, context.shared_context()); + + let nonincremental_layout = opts::get().nonincremental_layout; + if nonincremental_layout || node.is_dirty() { + // Remove existing CSS styles from nodes whose content has changed (e.g. text changed), + // to force non-incremental reflow. + if node.has_changed() { + node.unstyle(); + } + + // Check to see whether we can share a style with someone. + let style_sharing_candidate_cache = + &mut context.local_context().style_sharing_candidate_cache.borrow_mut(); + + let sharing_result = match node.as_element() { + Some(element) => { + unsafe { + element.share_style_if_possible(style_sharing_candidate_cache, + parent_opt.clone()) + } + }, + None => StyleSharingResult::CannotShare, + }; + + // Otherwise, match and cascade selectors. + match sharing_result { + StyleSharingResult::CannotShare => { + let mut applicable_declarations = ApplicableDeclarations::new(); + + let shareable_element = match node.as_element() { + Some(element) => { + // Perform the CSS selector matching. + let stylist = unsafe { &*context.shared_context().stylist.0 }; + if element.match_element(stylist, + Some(&*bf), + &mut applicable_declarations) { + Some(element) + } else { + None + } + }, + None => { + if node.has_changed() { + node.set_restyle_damage(N::ConcreteRestyleDamage::rebuild_and_reflow()) + } + None + }, + }; + + // Perform the CSS cascade. + unsafe { + node.cascade_node(&context.shared_context(), + parent_opt, + &applicable_declarations, + &mut context.local_context().applicable_declarations_cache.borrow_mut(), + &context.shared_context().new_animations_sender); + } + + // Add ourselves to the LRU cache. + if let Some(element) = shareable_element { + style_sharing_candidate_cache.insert_if_possible(&element); + } + } + StyleSharingResult::StyleWasShared(index, damage) => { + style_sharing_candidate_cache.touch(index); + node.set_restyle_damage(damage); + } + } + } + + let unsafe_layout_node = node.to_unsafe(); + + // Before running the children, we need to insert our nodes into the bloom + // filter. + debug!("[{}] + {:X}", tid(), unsafe_layout_node.0); + node.insert_into_bloom_filter(&mut *bf); + + // NB: flow construction updates the bloom filter on the way up. + put_task_local_bloom_filter(bf, &unsafe_layout_node, context.shared_context()); +} + diff --git a/tests/unit/gfx/Cargo.toml b/tests/unit/gfx/Cargo.toml index 24e43ff3def..55ec4c14504 100644 --- a/tests/unit/gfx/Cargo.toml +++ b/tests/unit/gfx/Cargo.toml @@ -10,3 +10,9 @@ doctest = false [dependencies.gfx] path = "../../../components/gfx" + +[dependencies.ipc-channel] +git = "https://github.com/servo/ipc-channel" + +[dependencies.style] +path = "../../../components/style" diff --git a/tests/unit/gfx/font_cache_task.rs b/tests/unit/gfx/font_cache_task.rs new file mode 100644 index 00000000000..54cc417acb0 --- /dev/null +++ b/tests/unit/gfx/font_cache_task.rs @@ -0,0 +1,21 @@ +/* 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/. */ + +use gfx::font_cache_task::FontCacheTask; +use ipc_channel::ipc; +use style::computed_values::font_family::FontFamily; +use style::font_face::Source; + +#[test] +fn test_local_web_font() { + let (inp_chan, _) = ipc::channel().unwrap(); + let (out_chan, out_receiver) = ipc::channel().unwrap(); + let font_cache_task = FontCacheTask::new(inp_chan); + let family_name = FontFamily::FamilyName(From::from("test family")); + let variant_name = FontFamily::FamilyName(From::from("test font face")); + + font_cache_task.add_web_font(family_name, Source::Local(variant_name), out_chan); + + assert_eq!(out_receiver.recv().unwrap(), ()); +} diff --git a/tests/unit/gfx/lib.rs b/tests/unit/gfx/lib.rs index 9a5040b6fe1..3bac7b06edc 100644 --- a/tests/unit/gfx/lib.rs +++ b/tests/unit/gfx/lib.rs @@ -3,5 +3,8 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ extern crate gfx; +extern crate ipc_channel; +extern crate style; +#[cfg(test)] mod font_cache_task; #[cfg(test)] mod text_util; diff --git a/tests/wpt/mozilla/tests/css/linear_gradients_lengths_a.html b/tests/wpt/mozilla/tests/css/linear_gradients_lengths_a.html index 7cc0c449f5f..36ab50d6866 100644 --- a/tests/wpt/mozilla/tests/css/linear_gradients_lengths_a.html +++ b/tests/wpt/mozilla/tests/css/linear_gradients_lengths_a.html @@ -9,9 +9,10 @@ section { width: 100px; height: 100px; border: solid black 1px; + background-clip: content-box; } #a { - background: linear-gradient(to right, white, white 30px, black 30px, black); + background-image: linear-gradient(to right, white, white 30px, black 30px, black); } </style> </head> diff --git a/tests/wpt/mozilla/tests/css/linear_gradients_lengths_ref.html b/tests/wpt/mozilla/tests/css/linear_gradients_lengths_ref.html index 3a9aec01525..a067067fff6 100644 --- a/tests/wpt/mozilla/tests/css/linear_gradients_lengths_ref.html +++ b/tests/wpt/mozilla/tests/css/linear_gradients_lengths_ref.html @@ -8,9 +8,10 @@ section { width: 100px; height: 100px; border: solid black 1px; + background-clip: content-box; } #a { - background: linear-gradient(to right, white, white 30%, black 30%, black); + background-image: linear-gradient(to right, white, white 30%, black 30%, black); } </style> </head> |