Replace script thread root browsing context by a collection of documents.

This commit is contained in:
Alan Jeffrey 2016-10-07 15:52:49 -05:00
parent ee588a31c3
commit 0d16a2a54e
9 changed files with 496 additions and 639 deletions

View file

@ -1623,12 +1623,12 @@ impl<Message, LTF, STF> Constellation<Message, LTF, STF>
pipeline_id: PipelineId, pipeline_id: PipelineId,
event: MozBrowserEvent) { event: MozBrowserEvent) {
assert!(PREFS.is_mozbrowser_enabled()); assert!(PREFS.is_mozbrowser_enabled());
let frame_id = self.pipelines.get(&pipeline_id).map(|pipeline| pipeline.frame_id);
// Find the script channel for the given parent pipeline, // Find the script channel for the given parent pipeline,
// and pass the event to that script thread. // and pass the event to that script thread.
// If the pipeline lookup fails, it is because we have torn down the pipeline, // If the pipeline lookup fails, it is because we have torn down the pipeline,
// so it is reasonable to silently ignore the event. // so it is reasonable to silently ignore the event.
let frame_id = self.pipelines.get(&pipeline_id).map(|pipeline| pipeline.frame_id);
match self.pipelines.get(&parent_pipeline_id) { match self.pipelines.get(&parent_pipeline_id) {
Some(pipeline) => pipeline.trigger_mozbrowser_event(frame_id, event), Some(pipeline) => pipeline.trigger_mozbrowser_event(frame_id, event),
None => warn!("Pipeline {:?} handling mozbrowser event after closure.", parent_pipeline_id), None => warn!("Pipeline {:?} handling mozbrowser event after closure.", parent_pipeline_id),
@ -2206,6 +2206,7 @@ impl<Message, LTF, STF> Constellation<Message, LTF, STF>
// Close a frame (and all children) // Close a frame (and all children)
fn close_frame(&mut self, frame_id: FrameId, exit_mode: ExitPipelineMode) { fn close_frame(&mut self, frame_id: FrameId, exit_mode: ExitPipelineMode) {
debug!("Closing frame {:?}.", frame_id);
// Store information about the pipelines to be closed. Then close the // Store information about the pipelines to be closed. Then close the
// pipelines, before removing ourself from the frames hash map. This // pipelines, before removing ourself from the frames hash map. This
// ordering is vital - so that if close_pipeline() ends up closing // ordering is vital - so that if close_pipeline() ends up closing
@ -2241,10 +2242,12 @@ impl<Message, LTF, STF> Constellation<Message, LTF, STF>
}; };
parent_pipeline.remove_child(frame_id); parent_pipeline.remove_child(frame_id);
} }
debug!("Closed frame {:?}.", frame_id);
} }
// Close all pipelines at and beneath a given frame // Close all pipelines at and beneath a given frame
fn close_pipeline(&mut self, pipeline_id: PipelineId, exit_mode: ExitPipelineMode) { fn close_pipeline(&mut self, pipeline_id: PipelineId, exit_mode: ExitPipelineMode) {
debug!("Closing pipeline {:?}.", pipeline_id);
// Store information about the frames to be closed. Then close the // Store information about the frames to be closed. Then close the
// frames, before removing ourself from the pipelines hash map. This // frames, before removing ourself from the pipelines hash map. This
// ordering is vital - so that if close_frames() ends up closing // ordering is vital - so that if close_frames() ends up closing
@ -2284,6 +2287,7 @@ impl<Message, LTF, STF> Constellation<Message, LTF, STF>
ExitPipelineMode::Normal => pipeline.exit(), ExitPipelineMode::Normal => pipeline.exit(),
ExitPipelineMode::Force => pipeline.force_exit(), ExitPipelineMode::Force => pipeline.force_exit(),
} }
debug!("Closed pipeline {:?}.", pipeline_id);
} }
// Randomly close a pipeline -if --random-pipeline-closure-probability is set // Randomly close a pipeline -if --random-pipeline-closure-probability is set

View file

@ -17,15 +17,15 @@ use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root; use dom::bindings::js::Root;
use dom::bindings::reflector::Reflectable; use dom::bindings::reflector::Reflectable;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::browsingcontext::BrowsingContext;
use dom::element::Element; use dom::element::Element;
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use dom::node::Node; use dom::node::{Node, window_from_node};
use dom::window::Window; use dom::window::Window;
use ipc_channel::ipc::IpcSender; use ipc_channel::ipc::IpcSender;
use js::jsapi::{JSAutoCompartment, ObjectClassName}; use js::jsapi::{JSAutoCompartment, ObjectClassName};
use js::jsval::UndefinedValue; use js::jsval::UndefinedValue;
use msg::constellation_msg::PipelineId; use msg::constellation_msg::PipelineId;
use script_thread::Documents;
use std::ffi::CStr; use std::ffi::CStr;
use std::str; use std::str;
use style::properties::longhands::{margin_bottom, margin_left, margin_right, margin_top}; use style::properties::longhands::{margin_bottom, margin_left, margin_right, margin_top};
@ -72,53 +72,35 @@ pub fn handle_evaluate_js(global: &GlobalScope, eval: String, reply: IpcSender<E
reply.send(result).unwrap(); reply.send(result).unwrap();
} }
pub fn handle_get_root_node(context: &BrowsingContext, pipeline: PipelineId, reply: IpcSender<Option<NodeInfo>>) { pub fn handle_get_root_node(documents: &Documents, pipeline: PipelineId, reply: IpcSender<Option<NodeInfo>>) {
let context = match context.find(pipeline) { let info = documents.find_document(pipeline)
Some(found_context) => found_context, .map(|document| document.upcast::<Node>().summarize());
None => return reply.send(None).unwrap() reply.send(info).unwrap();
};
let document = context.active_document();
let node = document.upcast::<Node>();
reply.send(Some(node.summarize())).unwrap();
} }
pub fn handle_get_document_element(context: &BrowsingContext, pub fn handle_get_document_element(documents: &Documents,
pipeline: PipelineId, pipeline: PipelineId,
reply: IpcSender<Option<NodeInfo>>) { reply: IpcSender<Option<NodeInfo>>) {
let context = match context.find(pipeline) { let info = documents.find_document(pipeline)
Some(found_context) => found_context, .and_then(|document| document.GetDocumentElement())
None => return reply.send(None).unwrap() .map(|element| element.upcast::<Node>().summarize());
}; reply.send(info).unwrap();
let document = context.active_document();
let document_element = document.GetDocumentElement().unwrap();
let node = document_element.upcast::<Node>();
reply.send(Some(node.summarize())).unwrap();
} }
fn find_node_by_unique_id(context: &BrowsingContext, fn find_node_by_unique_id(documents: &Documents,
pipeline: PipelineId, pipeline: PipelineId,
node_id: &str) node_id: &str)
-> Option<Root<Node>> { -> Option<Root<Node>> {
let context = match context.find(pipeline) { documents.find_document(pipeline).and_then(|document|
Some(found_context) => found_context, document.upcast::<Node>().traverse_preorder().find(|candidate| candidate.unique_id() == node_id)
None => return None )
};
let document = context.active_document();
let node = document.upcast::<Node>();
node.traverse_preorder().find(|candidate| candidate.unique_id() == node_id)
} }
pub fn handle_get_children(context: &BrowsingContext, pub fn handle_get_children(documents: &Documents,
pipeline: PipelineId, pipeline: PipelineId,
node_id: String, node_id: String,
reply: IpcSender<Option<Vec<NodeInfo>>>) { reply: IpcSender<Option<Vec<NodeInfo>>>) {
match find_node_by_unique_id(context, pipeline, &*node_id) { match find_node_by_unique_id(documents, pipeline, &*node_id) {
None => return reply.send(None).unwrap(), None => return reply.send(None).unwrap(),
Some(parent) => { Some(parent) => {
let children = parent.children() let children = parent.children()
@ -130,11 +112,11 @@ pub fn handle_get_children(context: &BrowsingContext,
}; };
} }
pub fn handle_get_layout(context: &BrowsingContext, pub fn handle_get_layout(documents: &Documents,
pipeline: PipelineId, pipeline: PipelineId,
node_id: String, node_id: String,
reply: IpcSender<Option<ComputedNodeLayout>>) { reply: IpcSender<Option<ComputedNodeLayout>>) {
let node = match find_node_by_unique_id(context, pipeline, &*node_id) { let node = match find_node_by_unique_id(documents, pipeline, &*node_id) {
None => return reply.send(None).unwrap(), None => return reply.send(None).unwrap(),
Some(found_node) => found_node Some(found_node) => found_node
}; };
@ -144,7 +126,7 @@ pub fn handle_get_layout(context: &BrowsingContext,
let width = rect.Width() as f32; let width = rect.Width() as f32;
let height = rect.Height() as f32; let height = rect.Height() as f32;
let window = context.active_window(); let window = window_from_node(&*node);
let elem = node.downcast::<Element>().expect("should be getting layout of element"); let elem = node.downcast::<Element>().expect("should be getting layout of element");
let computed_style = window.GetComputedStyle(elem, None); let computed_style = window.GetComputedStyle(elem, None);
@ -223,11 +205,11 @@ pub fn handle_get_cached_messages(_pipeline_id: PipelineId,
reply.send(messages).unwrap(); reply.send(messages).unwrap();
} }
pub fn handle_modify_attribute(context: &BrowsingContext, pub fn handle_modify_attribute(documents: &Documents,
pipeline: PipelineId, pipeline: PipelineId,
node_id: String, node_id: String,
modifications: Vec<Modification>) { modifications: Vec<Modification>) {
let node = match find_node_by_unique_id(context, pipeline, &*node_id) { let node = match find_node_by_unique_id(documents, pipeline, &*node_id) {
None => return warn!("node id {} for pipeline id {} is not found", &node_id, &pipeline), None => return warn!("node id {} for pipeline id {} is not found", &node_id, &pipeline),
Some(found_node) => found_node Some(found_node) => found_node
}; };
@ -249,49 +231,39 @@ pub fn handle_wants_live_notifications(global: &GlobalScope, send_notifications:
global.set_devtools_wants_updates(send_notifications); global.set_devtools_wants_updates(send_notifications);
} }
pub fn handle_set_timeline_markers(context: &BrowsingContext, pub fn handle_set_timeline_markers(documents: &Documents,
pipeline: PipelineId, pipeline: PipelineId,
marker_types: Vec<TimelineMarkerType>, marker_types: Vec<TimelineMarkerType>,
reply: IpcSender<Option<TimelineMarker>>) { reply: IpcSender<Option<TimelineMarker>>) {
match context.find(pipeline) { match documents.find_window(pipeline) {
None => reply.send(None).unwrap(), None => reply.send(None).unwrap(),
Some(context) => context.active_window().set_devtools_timeline_markers(marker_types, reply), Some(window) => window.set_devtools_timeline_markers(marker_types, reply),
} }
} }
pub fn handle_drop_timeline_markers(context: &BrowsingContext, pub fn handle_drop_timeline_markers(documents: &Documents,
pipeline: PipelineId, pipeline: PipelineId,
marker_types: Vec<TimelineMarkerType>) { marker_types: Vec<TimelineMarkerType>) {
if let Some(context) = context.find(pipeline) { if let Some(window) = documents.find_window(pipeline) {
context.active_window().drop_devtools_timeline_markers(marker_types); window.drop_devtools_timeline_markers(marker_types);
} }
} }
pub fn handle_request_animation_frame(context: &BrowsingContext, pub fn handle_request_animation_frame(documents: &Documents,
id: PipelineId, id: PipelineId,
actor_name: String) { actor_name: String) {
let context = match context.find(id) { if let Some(doc) = documents.find_document(id) {
None => return warn!("context for pipeline id {} is not found", id), let devtools_sender = doc.window().upcast::<GlobalScope>().devtools_chan().unwrap().clone();
Some(found_node) => found_node doc.request_animation_frame(box move |time| {
}; let msg = ScriptToDevtoolsControlMsg::FramerateTick(actor_name, time);
devtools_sender.send(msg).unwrap();
let doc = context.active_document(); });
let devtools_sender = }
context.active_window().upcast::<GlobalScope>().devtools_chan().unwrap().clone();
doc.request_animation_frame(box move |time| {
let msg = ScriptToDevtoolsControlMsg::FramerateTick(actor_name, time);
devtools_sender.send(msg).unwrap();
});
} }
pub fn handle_reload(context: &BrowsingContext, pub fn handle_reload(documents: &Documents,
id: PipelineId) { id: PipelineId) {
let context = match context.find(id) { if let Some(win) = documents.find_window(id) {
None => return warn!("context for pipeline id {} is not found", id), win.Location().Reload();
Some(found_node) => found_node }
};
let win = context.active_window();
let location = win.Location();
location.Reload();
} }

View file

@ -2,7 +2,6 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::conversions::{ToJSValConvertible, root_from_handleobject}; use dom::bindings::conversions::{ToJSValConvertible, root_from_handleobject};
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference}; use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference};
@ -37,15 +36,9 @@ use std::cell::Cell;
pub struct BrowsingContext { pub struct BrowsingContext {
reflector: Reflector, reflector: Reflector,
/// Pipeline id associated with this context.
id: PipelineId,
/// Indicates if reflow is required when reloading. /// Indicates if reflow is required when reloading.
needs_reflow: Cell<bool>, needs_reflow: Cell<bool>,
/// Stores the child browsing contexts (ex. iframe browsing context)
children: DOMRefCell<Vec<JS<BrowsingContext>>>,
/// The current active document. /// The current active document.
/// Note that the session history is stored in the constellation, /// Note that the session history is stored in the constellation,
/// in the script thread we just track the current active document. /// in the script thread we just track the current active document.
@ -56,19 +49,17 @@ pub struct BrowsingContext {
} }
impl BrowsingContext { impl BrowsingContext {
pub fn new_inherited(frame_element: Option<&Element>, id: PipelineId) -> BrowsingContext { pub fn new_inherited(frame_element: Option<&Element>) -> BrowsingContext {
BrowsingContext { BrowsingContext {
reflector: Reflector::new(), reflector: Reflector::new(),
id: id,
needs_reflow: Cell::new(true), needs_reflow: Cell::new(true),
children: DOMRefCell::new(vec![]),
active_document: Default::default(), active_document: Default::default(),
frame_element: frame_element.map(JS::from_ref), frame_element: frame_element.map(JS::from_ref),
} }
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn new(window: &Window, frame_element: Option<&Element>, id: PipelineId) -> Root<BrowsingContext> { pub fn new(window: &Window, frame_element: Option<&Element>) -> Root<BrowsingContext> {
unsafe { unsafe {
let WindowProxyHandler(handler) = window.windowproxy_handler(); let WindowProxyHandler(handler) = window.windowproxy_handler();
assert!(!handler.is_null()); assert!(!handler.is_null());
@ -81,7 +72,7 @@ impl BrowsingContext {
rooted!(in(cx) let window_proxy = NewWindowProxy(cx, parent, handler)); rooted!(in(cx) let window_proxy = NewWindowProxy(cx, parent, handler));
assert!(!window_proxy.is_null()); assert!(!window_proxy.is_null());
let object = box BrowsingContext::new_inherited(frame_element, id); let object = box BrowsingContext::new_inherited(frame_element);
let raw = Box::into_raw(object); let raw = Box::into_raw(object);
SetProxyExtra(window_proxy.get(), 0, &PrivateValue(raw as *const _)); SetProxyExtra(window_proxy.get(), 0, &PrivateValue(raw as *const _));
@ -118,82 +109,20 @@ impl BrowsingContext {
window_proxy.get() window_proxy.get()
} }
pub fn remove(&self, id: PipelineId) -> Option<Root<BrowsingContext>> {
let remove_idx = self.children
.borrow()
.iter()
.position(|context| context.id == id);
match remove_idx {
Some(idx) => Some(Root::from_ref(&*self.children.borrow_mut().remove(idx))),
None => {
self.children
.borrow_mut()
.iter_mut()
.filter_map(|context| context.remove(id))
.next()
}
}
}
pub fn set_reflow_status(&self, status: bool) -> bool { pub fn set_reflow_status(&self, status: bool) -> bool {
let old = self.needs_reflow.get(); let old = self.needs_reflow.get();
self.needs_reflow.set(status); self.needs_reflow.set(status);
old old
} }
pub fn pipeline_id(&self) -> PipelineId { pub fn active_pipeline_id(&self) -> Option<PipelineId> {
self.id self.active_document.get()
} .map(|doc| doc.window().upcast::<GlobalScope>().pipeline_id())
pub fn push_child_context(&self, context: &BrowsingContext) {
self.children.borrow_mut().push(JS::from_ref(&context));
}
pub fn find_child_by_id(&self, pipeline_id: PipelineId) -> Option<Root<Window>> {
self.children.borrow().iter().find(|context| {
let window = context.active_window();
window.upcast::<GlobalScope>().pipeline_id() == pipeline_id
}).map(|context| context.active_window())
} }
pub fn unset_active_document(&self) { pub fn unset_active_document(&self) {
self.active_document.set(None) self.active_document.set(None)
} }
pub fn iter(&self) -> ContextIterator {
ContextIterator {
stack: vec!(Root::from_ref(self)),
}
}
pub fn find(&self, id: PipelineId) -> Option<Root<BrowsingContext>> {
if self.id == id {
return Some(Root::from_ref(self));
}
self.children.borrow()
.iter()
.filter_map(|c| c.find(id))
.next()
}
}
pub struct ContextIterator {
stack: Vec<Root<BrowsingContext>>,
}
impl Iterator for ContextIterator {
type Item = Root<BrowsingContext>;
fn next(&mut self) -> Option<Root<BrowsingContext>> {
let popped = self.stack.pop();
if let Some(ref context) = popped {
self.stack.extend(context.children.borrow()
.iter()
.map(|c| Root::from_ref(&**c)));
}
popped
}
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]

View file

@ -41,6 +41,7 @@ use js::jsval::{NullValue, UndefinedValue};
use msg::constellation_msg::{FrameType, FrameId, PipelineId, TraversalDirection}; use msg::constellation_msg::{FrameType, FrameId, PipelineId, TraversalDirection};
use net_traits::response::HttpsState; use net_traits::response::HttpsState;
use script_layout_interface::message::ReflowQueryType; use script_layout_interface::message::ReflowQueryType;
use script_thread::ScriptThread;
use script_traits::{IFrameLoadInfo, LoadData, MozBrowserEvent, ScriptMsg as ConstellationMsg}; use script_traits::{IFrameLoadInfo, LoadData, MozBrowserEvent, ScriptMsg as ConstellationMsg};
use script_traits::IFrameSandboxState::{IFrameSandboxed, IFrameUnsandboxed}; use script_traits::IFrameSandboxState::{IFrameSandboxed, IFrameUnsandboxed};
use std::cell::Cell; use std::cell::Cell;
@ -234,7 +235,7 @@ impl HTMLIFrameElement {
pub fn iframe_load_event_steps(&self, loaded_pipeline: PipelineId) { pub fn iframe_load_event_steps(&self, loaded_pipeline: PipelineId) {
// TODO(#9592): assert that the load blocker is present at all times when we // TODO(#9592): assert that the load blocker is present at all times when we
// can guarantee that it's created for the case of iframe.reload(). // can guarantee that it's created for the case of iframe.reload().
assert_eq!(loaded_pipeline, self.pipeline_id().unwrap()); if Some(loaded_pipeline) != self.pipeline_id() { return; }
// TODO A cross-origin child document would not be easily accessible // TODO A cross-origin child document would not be easily accessible
// from this script thread. It's unclear how to implement // from this script thread. It's unclear how to implement
@ -267,13 +268,16 @@ impl HTMLIFrameElement {
} }
pub fn get_content_window(&self) -> Option<Root<Window>> { pub fn get_content_window(&self) -> Option<Root<Window>> {
self.pipeline_id.get().and_then(|pipeline_id| { self.pipeline_id.get()
let window = window_from_node(self); .and_then(|pipeline_id| ScriptThread::find_document(pipeline_id))
let browsing_context = window.browsing_context(); .and_then(|document| {
browsing_context.find_child_by_id(pipeline_id) if self.global().get_url().origin() == document.global().get_url().origin() {
}) Some(Root::from_ref(document.window()))
} else {
None
}
})
} }
} }
pub trait HTMLIFrameElementLayoutMethods { pub trait HTMLIFrameElementLayoutMethods {

View file

@ -97,6 +97,13 @@ impl NodeList {
panic!("called as_simple_list() on a children node list") panic!("called as_simple_list() on a children node list")
} }
} }
pub fn iter(&self) -> NodeListIterator {
NodeListIterator {
nodes: self,
offset: 0,
}
}
} }
#[derive(JSTraceable, HeapSizeOf)] #[derive(JSTraceable, HeapSizeOf)]
@ -277,3 +284,18 @@ impl ChildrenList {
self.last_index.set(0u32); self.last_index.set(0u32);
} }
} }
pub struct NodeListIterator<'a> {
nodes: &'a NodeList,
offset: u32,
}
impl<'a> Iterator for NodeListIterator<'a> {
type Item = Root<Node>;
fn next(&mut self) -> Option<Root<Node>> {
let result = self.nodes.Item(self.offset);
self.offset = self.offset + 1;
result
}
}

View file

@ -13,7 +13,6 @@ use dom::bindings::str::DOMString;
use dom::event::{Event, EventBubbles, EventCancelable}; use dom::event::{Event, EventBubbles, EventCancelable};
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use dom::storageevent::StorageEvent; use dom::storageevent::StorageEvent;
use dom::urlhelper::UrlHelper;
use ipc_channel::ipc::{self, IpcSender}; use ipc_channel::ipc::{self, IpcSender};
use net_traits::IpcSend; use net_traits::IpcSend;
use net_traits::storage_thread::{StorageThreadMsg, StorageType}; use net_traits::storage_thread::{StorageThreadMsg, StorageType};
@ -193,14 +192,16 @@ impl Runnable for StorageEventRunnable {
Some(&storage) Some(&storage)
); );
let root_context = script_thread.root_browsing_context(); // TODO: This is only iterating over documents in the current script
for it_context in root_context.iter() { // thread, so we are not firing events to other script threads.
let it_window = it_context.active_window(); // NOTE: once that is fixed, we can remove borrow_documents from ScriptThread.
assert!(UrlHelper::SameOrigin(&ev_url, &it_window.get_url())); for document in script_thread.borrow_documents().iter() {
// TODO: Such a Document object is not necessarily fully active, but events fired on such if ev_url.origin() == document.window().get_url().origin() {
// objects are ignored by the event loop until the Document becomes fully active again. // TODO: Such a Document object is not necessarily fully active, but events fired on such
if global.pipeline_id() != it_window.upcast::<GlobalScope>().pipeline_id() { // objects are ignored by the event loop until the Document becomes fully active again.
storage_event.upcast::<Event>().fire(it_window.upcast()); if global.pipeline_id() != document.window().upcast::<GlobalScope>().pipeline_id() {
storage_event.upcast::<Event>().fire(document.window().upcast());
}
} }
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -10,20 +10,18 @@ use dom::bindings::codegen::Bindings::HTMLElementBinding::HTMLElementMethods;
use dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods; use dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods;
use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods; use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::Bindings::NodeListBinding::NodeListMethods;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, StringificationBehavior}; use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, StringificationBehavior};
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root; use dom::bindings::js::Root;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::browsingcontext::BrowsingContext;
use dom::element::Element; use dom::element::Element;
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use dom::htmlelement::HTMLElement; use dom::htmlelement::HTMLElement;
use dom::htmliframeelement::HTMLIFrameElement; use dom::htmliframeelement::HTMLIFrameElement;
use dom::htmlinputelement::HTMLInputElement; use dom::htmlinputelement::HTMLInputElement;
use dom::htmloptionelement::HTMLOptionElement; use dom::htmloptionelement::HTMLOptionElement;
use dom::node::Node; use dom::node::{Node, window_from_node};
use euclid::point::Point2D; use euclid::point::Point2D;
use euclid::rect::Rect; use euclid::rect::Rect;
use euclid::size::Size2D; use euclid::size::Size2D;
@ -35,21 +33,19 @@ use msg::constellation_msg::PipelineId;
use net_traits::CookieSource::{HTTP, NonHTTP}; use net_traits::CookieSource::{HTTP, NonHTTP};
use net_traits::CoreResourceMsg::{GetCookiesDataForUrl, SetCookiesForUrlWithData}; use net_traits::CoreResourceMsg::{GetCookiesDataForUrl, SetCookiesForUrlWithData};
use net_traits::IpcSend; use net_traits::IpcSend;
use script_thread::Documents;
use script_traits::webdriver_msg::{WebDriverFrameId, WebDriverJSError, WebDriverJSResult, WebDriverJSValue}; use script_traits::webdriver_msg::{WebDriverFrameId, WebDriverJSError, WebDriverJSResult, WebDriverJSValue};
use script_traits::webdriver_msg::WebDriverCookieError; use script_traits::webdriver_msg::WebDriverCookieError;
use url::Url; use url::Url;
fn find_node_by_unique_id(context: &BrowsingContext, fn find_node_by_unique_id(documents: &Documents,
pipeline: PipelineId, pipeline: PipelineId,
node_id: String) node_id: String)
-> Option<Root<Node>> { -> Option<Root<Node>> {
let context = match context.find(pipeline) { documents.find_document(pipeline)
Some(context) => context, .and_then(|document| document.upcast::<Node>()
None => return None .traverse_preorder()
}; .find(|candidate| candidate.unique_id() == node_id))
let document = context.active_document();
document.upcast::<Node>().traverse_preorder().find(|candidate| candidate.unique_id() == node_id)
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
@ -79,16 +75,15 @@ pub unsafe fn jsval_to_webdriver(cx: *mut JSContext, val: HandleValue) -> WebDri
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn handle_execute_script(context: &BrowsingContext, pub fn handle_execute_script(documents: &Documents,
pipeline: PipelineId, pipeline: PipelineId,
eval: String, eval: String,
reply: IpcSender<WebDriverJSResult>) { reply: IpcSender<WebDriverJSResult>) {
let context = match context.find(pipeline) { let window = match documents.find_window(pipeline) {
Some(context) => context, Some(window) => window,
None => return reply.send(Err(WebDriverJSError::BrowsingContextNotFound)).unwrap() None => return reply.send(Err(WebDriverJSError::BrowsingContextNotFound)).unwrap()
}; };
let window = context.active_window();
let result = unsafe { let result = unsafe {
let cx = window.get_cx(); let cx = window.get_cx();
rooted!(in(cx) let mut rval = UndefinedValue()); rooted!(in(cx) let mut rval = UndefinedValue());
@ -96,27 +91,26 @@ pub fn handle_execute_script(context: &BrowsingContext,
&eval, rval.handle_mut()); &eval, rval.handle_mut());
jsval_to_webdriver(cx, rval.handle()) jsval_to_webdriver(cx, rval.handle())
}; };
reply.send(result).unwrap(); reply.send(result).unwrap();
} }
pub fn handle_execute_async_script(context: &BrowsingContext, pub fn handle_execute_async_script(documents: &Documents,
pipeline: PipelineId, pipeline: PipelineId,
eval: String, eval: String,
reply: IpcSender<WebDriverJSResult>) { reply: IpcSender<WebDriverJSResult>) {
let context = match context.find(pipeline) { let window = match documents.find_window(pipeline) {
Some(context) => context, Some(window) => window,
None => return reply.send(Err(WebDriverJSError::BrowsingContextNotFound)).unwrap() None => return reply.send(Err(WebDriverJSError::BrowsingContextNotFound)).unwrap()
}; };
let window = context.active_window();
let cx = window.get_cx(); let cx = window.get_cx();
window.set_webdriver_script_chan(Some(reply)); window.set_webdriver_script_chan(Some(reply));
rooted!(in(cx) let mut rval = UndefinedValue()); rooted!(in(cx) let mut rval = UndefinedValue());
window.upcast::<GlobalScope>().evaluate_js_on_global_with_result( window.upcast::<GlobalScope>().evaluate_js_on_global_with_result(&eval, rval.handle_mut());
&eval, rval.handle_mut());
} }
pub fn handle_get_frame_id(context: &BrowsingContext, pub fn handle_get_frame_id(documents: &Documents,
pipeline: PipelineId, pipeline: PipelineId,
webdriver_frame_id: WebDriverFrameId, webdriver_frame_id: WebDriverFrameId,
reply: IpcSender<Result<Option<PipelineId>, ()>>) { reply: IpcSender<Result<Option<PipelineId>, ()>>) {
@ -126,7 +120,7 @@ pub fn handle_get_frame_id(context: &BrowsingContext,
Ok(None) Ok(None)
}, },
WebDriverFrameId::Element(x) => { WebDriverFrameId::Element(x) => {
match find_node_by_unique_id(context, pipeline, x) { match find_node_by_unique_id(documents, pipeline, x) {
Some(ref node) => { Some(ref node) => {
match node.downcast::<HTMLIFrameElement>() { match node.downcast::<HTMLIFrameElement>() {
Some(ref elem) => Ok(elem.get_content_window()), Some(ref elem) => Ok(elem.get_content_window()),
@ -137,8 +131,9 @@ pub fn handle_get_frame_id(context: &BrowsingContext,
} }
}, },
WebDriverFrameId::Parent => { WebDriverFrameId::Parent => {
let window = context.active_window(); documents.find_window(pipeline)
Ok(window.parent()) .map(|window| Ok(window.parent()))
.unwrap_or(Err(()))
} }
}; };
@ -146,41 +141,31 @@ pub fn handle_get_frame_id(context: &BrowsingContext,
reply.send(frame_id).unwrap() reply.send(frame_id).unwrap()
} }
pub fn handle_find_element_css(context: &BrowsingContext, _pipeline: PipelineId, selector: String, pub fn handle_find_element_css(documents: &Documents, pipeline: PipelineId, selector: String,
reply: IpcSender<Result<Option<String>, ()>>) { reply: IpcSender<Result<Option<String>, ()>>) {
reply.send(match context.active_document().QuerySelector(DOMString::from(selector)) { let node_id = documents.find_document(pipeline)
Ok(node) => { .map(|doc| doc.QuerySelector(DOMString::from(selector)).map_err(|_| ()))
Ok(node.map(|x| x.upcast::<Node>().unique_id())) .unwrap_or(Err(()))
} .map(|node| node.map(|x| x.upcast::<Node>().unique_id()));
Err(_) => Err(()) reply.send(node_id).unwrap();
}).unwrap();
} }
pub fn handle_find_elements_css(context: &BrowsingContext, pub fn handle_find_elements_css(documents: &Documents,
_pipeline: PipelineId, pipeline: PipelineId,
selector: String, selector: String,
reply: IpcSender<Result<Vec<String>, ()>>) { reply: IpcSender<Result<Vec<String>, ()>>) {
reply.send(match context.active_document().QuerySelectorAll(DOMString::from(selector)) { let node_ids = documents.find_document(pipeline)
Ok(ref nodes) => { .map(|doc| doc.QuerySelectorAll(DOMString::from(selector)).map_err(|_| ()))
let mut result = Vec::with_capacity(nodes.Length() as usize); .unwrap_or(Err(()))
for i in 0..nodes.Length() { .map(|nodes| nodes.iter().map(|x| x.upcast::<Node>().unique_id()).collect());
if let Some(ref node) = nodes.Item(i) { reply.send(node_ids).unwrap();
result.push(node.unique_id());
}
}
Ok(result)
},
Err(_) => {
Err(())
}
}).unwrap();
} }
pub fn handle_focus_element(context: &BrowsingContext, pub fn handle_focus_element(documents: &Documents,
pipeline: PipelineId, pipeline: PipelineId,
element_id: String, element_id: String,
reply: IpcSender<Result<(), ()>>) { reply: IpcSender<Result<(), ()>>) {
reply.send(match find_node_by_unique_id(context, pipeline, element_id) { reply.send(match find_node_by_unique_id(documents, pipeline, element_id) {
Some(ref node) => { Some(ref node) => {
match node.downcast::<HTMLElement>() { match node.downcast::<HTMLElement>() {
Some(ref elem) => { Some(ref elem) => {
@ -195,47 +180,62 @@ pub fn handle_focus_element(context: &BrowsingContext,
}).unwrap(); }).unwrap();
} }
pub fn handle_get_active_element(context: &BrowsingContext, pub fn handle_get_active_element(documents: &Documents,
_pipeline: PipelineId, pipeline: PipelineId,
reply: IpcSender<Option<String>>) { reply: IpcSender<Option<String>>) {
reply.send(context.active_document().GetActiveElement().map( reply.send(documents.find_document(pipeline)
|elem| elem.upcast::<Node>().unique_id())).unwrap(); .and_then(|doc| doc.GetActiveElement())
.map(|elem| elem.upcast::<Node>().unique_id())).unwrap();
} }
pub fn handle_get_cookies(context: &BrowsingContext, pub fn handle_get_cookies(documents: &Documents,
_pipeline: PipelineId, pipeline: PipelineId,
reply: IpcSender<Vec<Serde<Cookie>>>) { reply: IpcSender<Vec<Serde<Cookie>>>) {
let document = context.active_document(); // TODO: Return an error if the pipeline doesn't exist?
let url = document.url(); let cookies: Vec<Serde<Cookie>> = match documents.find_document(pipeline) {
let (sender, receiver) = ipc::channel().unwrap(); None => Vec::new(),
let _ = document.window().upcast::<GlobalScope>().resource_threads().send( Some(document) => {
GetCookiesDataForUrl(url.clone(), sender, NonHTTP) let url = document.url();
); let (sender, receiver) = ipc::channel().unwrap();
let cookies = receiver.recv().unwrap(); let _ = document.window().upcast::<GlobalScope>().resource_threads().send(
GetCookiesDataForUrl(url.clone(), sender, NonHTTP)
);
receiver.recv().unwrap()
},
};
reply.send(cookies).unwrap(); reply.send(cookies).unwrap();
} }
// https://w3c.github.io/webdriver/webdriver-spec.html#get-cookie // https://w3c.github.io/webdriver/webdriver-spec.html#get-cookie
pub fn handle_get_cookie(context: &BrowsingContext, pub fn handle_get_cookie(documents: &Documents,
_pipeline: PipelineId, pipeline: PipelineId,
name: String, name: String,
reply: IpcSender<Vec<Serde<Cookie>>>) { reply: IpcSender<Vec<Serde<Cookie>>>) {
let document = context.active_document(); // TODO: Return an error if the pipeline doesn't exist?
let url = document.url(); let cookies: Vec<Serde<Cookie>> = match documents.find_document(pipeline) {
let (sender, receiver) = ipc::channel().unwrap(); None => Vec::new(),
let _ = document.window().upcast::<GlobalScope>().resource_threads().send( Some(document) => {
GetCookiesDataForUrl(url.clone(), sender, NonHTTP) let url = document.url();
); let (sender, receiver) = ipc::channel().unwrap();
let cookies = receiver.recv().unwrap(); let _ = document.window().upcast::<GlobalScope>().resource_threads().send(
GetCookiesDataForUrl(url.clone(), sender, NonHTTP)
);
receiver.recv().unwrap()
},
};
reply.send(cookies.into_iter().filter(|c| c.name == &*name).collect()).unwrap(); reply.send(cookies.into_iter().filter(|c| c.name == &*name).collect()).unwrap();
} }
// https://w3c.github.io/webdriver/webdriver-spec.html#add-cookie // https://w3c.github.io/webdriver/webdriver-spec.html#add-cookie
pub fn handle_add_cookie(context: &BrowsingContext, pub fn handle_add_cookie(documents: &Documents,
_pipeline: PipelineId, pipeline: PipelineId,
cookie: Cookie, cookie: Cookie,
reply: IpcSender<Result<(), WebDriverCookieError>>) { reply: IpcSender<Result<(), WebDriverCookieError>>) {
let document = context.active_document(); // TODO: Return a different error if the pipeline doesn't exist?
let document = match documents.find_document(pipeline) {
Some(document) => document,
None => return reply.send(Err(WebDriverCookieError::UnableToSetCookie)).unwrap(),
};
let url = document.url(); let url = document.url();
let method = if cookie.httponly { let method = if cookie.httponly {
HTTP HTTP
@ -262,15 +262,19 @@ pub fn handle_add_cookie(context: &BrowsingContext,
}).unwrap(); }).unwrap();
} }
pub fn handle_get_title(context: &BrowsingContext, _pipeline: PipelineId, reply: IpcSender<String>) { pub fn handle_get_title(documents: &Documents, pipeline: PipelineId, reply: IpcSender<String>) {
reply.send(String::from(context.active_document().Title())).unwrap(); // TODO: Return an error if the pipeline doesn't exist.
let title = documents.find_document(pipeline)
.map(|doc| String::from(doc.Title()))
.unwrap_or_default();
reply.send(title).unwrap();
} }
pub fn handle_get_rect(context: &BrowsingContext, pub fn handle_get_rect(documents: &Documents,
pipeline: PipelineId, pipeline: PipelineId,
element_id: String, element_id: String,
reply: IpcSender<Result<Rect<f64>, ()>>) { reply: IpcSender<Result<Rect<f64>, ()>>) {
reply.send(match find_node_by_unique_id(context, pipeline, element_id) { reply.send(match find_node_by_unique_id(documents, pipeline, element_id) {
Some(elem) => { Some(elem) => {
// https://w3c.github.io/webdriver/webdriver-spec.html#dfn-calculate-the-absolute-position // https://w3c.github.io/webdriver/webdriver-spec.html#dfn-calculate-the-absolute-position
match elem.downcast::<HTMLElement>() { match elem.downcast::<HTMLElement>() {
@ -304,11 +308,11 @@ pub fn handle_get_rect(context: &BrowsingContext,
}).unwrap(); }).unwrap();
} }
pub fn handle_get_text(context: &BrowsingContext, pub fn handle_get_text(documents: &Documents,
pipeline: PipelineId, pipeline: PipelineId,
node_id: String, node_id: String,
reply: IpcSender<Result<String, ()>>) { reply: IpcSender<Result<String, ()>>) {
reply.send(match find_node_by_unique_id(context, pipeline, node_id) { reply.send(match find_node_by_unique_id(documents, pipeline, node_id) {
Some(ref node) => { Some(ref node) => {
Ok(node.GetTextContent().map_or("".to_owned(), String::from)) Ok(node.GetTextContent().map_or("".to_owned(), String::from))
}, },
@ -316,11 +320,11 @@ pub fn handle_get_text(context: &BrowsingContext,
}).unwrap(); }).unwrap();
} }
pub fn handle_get_name(context: &BrowsingContext, pub fn handle_get_name(documents: &Documents,
pipeline: PipelineId, pipeline: PipelineId,
node_id: String, node_id: String,
reply: IpcSender<Result<String, ()>>) { reply: IpcSender<Result<String, ()>>) {
reply.send(match find_node_by_unique_id(context, pipeline, node_id) { reply.send(match find_node_by_unique_id(documents, pipeline, node_id) {
Some(node) => { Some(node) => {
Ok(String::from(node.downcast::<Element>().unwrap().TagName())) Ok(String::from(node.downcast::<Element>().unwrap().TagName()))
}, },
@ -328,12 +332,12 @@ pub fn handle_get_name(context: &BrowsingContext,
}).unwrap(); }).unwrap();
} }
pub fn handle_get_attribute(context: &BrowsingContext, pub fn handle_get_attribute(documents: &Documents,
pipeline: PipelineId, pipeline: PipelineId,
node_id: String, node_id: String,
name: String, name: String,
reply: IpcSender<Result<Option<String>, ()>>) { reply: IpcSender<Result<Option<String>, ()>>) {
reply.send(match find_node_by_unique_id(context, pipeline, node_id) { reply.send(match find_node_by_unique_id(documents, pipeline, node_id) {
Some(node) => { Some(node) => {
Ok(node.downcast::<Element>().unwrap().GetAttribute(DOMString::from(name)) Ok(node.downcast::<Element>().unwrap().GetAttribute(DOMString::from(name))
.map(String::from)) .map(String::from))
@ -342,14 +346,14 @@ pub fn handle_get_attribute(context: &BrowsingContext,
}).unwrap(); }).unwrap();
} }
pub fn handle_get_css(context: &BrowsingContext, pub fn handle_get_css(documents: &Documents,
pipeline: PipelineId, pipeline: PipelineId,
node_id: String, node_id: String,
name: String, name: String,
reply: IpcSender<Result<String, ()>>) { reply: IpcSender<Result<String, ()>>) {
reply.send(match find_node_by_unique_id(context, pipeline, node_id) { reply.send(match find_node_by_unique_id(documents, pipeline, node_id) {
Some(node) => { Some(node) => {
let window = context.active_window(); let window = window_from_node(&*node);
let elem = node.downcast::<Element>().unwrap(); let elem = node.downcast::<Element>().unwrap();
Ok(String::from( Ok(String::from(
window.GetComputedStyle(&elem, None).GetPropertyValue(DOMString::from(name)))) window.GetComputedStyle(&elem, None).GetPropertyValue(DOMString::from(name))))
@ -358,19 +362,21 @@ pub fn handle_get_css(context: &BrowsingContext,
}).unwrap(); }).unwrap();
} }
pub fn handle_get_url(context: &BrowsingContext, pub fn handle_get_url(documents: &Documents,
_pipeline: PipelineId, pipeline: PipelineId,
reply: IpcSender<Url>) { reply: IpcSender<Url>) {
let document = context.active_document(); // TODO: Return an error if the pipeline doesn't exist.
let url = document.url(); let url = documents.find_document(pipeline)
reply.send((*url).clone()).unwrap(); .map(|document| document.url().clone())
.unwrap_or_else(|| Url::parse("about:blank").expect("infallible"));
reply.send(url).unwrap();
} }
pub fn handle_is_enabled(context: &BrowsingContext, pub fn handle_is_enabled(documents: &Documents,
pipeline: PipelineId, pipeline: PipelineId,
element_id: String, element_id: String,
reply: IpcSender<Result<bool, ()>>) { reply: IpcSender<Result<bool, ()>>) {
reply.send(match find_node_by_unique_id(&context, pipeline, element_id) { reply.send(match find_node_by_unique_id(&documents, pipeline, element_id) {
Some(ref node) => { Some(ref node) => {
match node.downcast::<Element>() { match node.downcast::<Element>() {
Some(elem) => Ok(elem.enabled_state()), Some(elem) => Ok(elem.enabled_state()),
@ -381,11 +387,11 @@ pub fn handle_is_enabled(context: &BrowsingContext,
}).unwrap(); }).unwrap();
} }
pub fn handle_is_selected(context: &BrowsingContext, pub fn handle_is_selected(documents: &Documents,
pipeline: PipelineId, pipeline: PipelineId,
element_id: String, element_id: String,
reply: IpcSender<Result<bool, ()>>) { reply: IpcSender<Result<bool, ()>>) {
reply.send(match find_node_by_unique_id(context, pipeline, element_id) { reply.send(match find_node_by_unique_id(documents, pipeline, element_id) {
Some(ref node) => { Some(ref node) => {
if let Some(input_element) = node.downcast::<HTMLInputElement>() { if let Some(input_element) = node.downcast::<HTMLInputElement>() {
Ok(input_element.Checked()) Ok(input_element.Checked())

View file

@ -83,8 +83,9 @@ pub enum ScriptMsg {
/// A new load has been requested, with an option to replace the current entry once loaded /// A new load has been requested, with an option to replace the current entry once loaded
/// instead of adding a new entry. /// instead of adding a new entry.
LoadUrl(PipelineId, LoadData, bool), LoadUrl(PipelineId, LoadData, bool),
/// Dispatch a mozbrowser event to the parent of this pipeline. /// Dispatch a mozbrowser event to a given iframe,
/// The first PipelineId is for the parent, the second is for the originating pipeline. /// or to the window if no subpage id is provided.
/// First PipelineId is for the parent, second PipelineId is in the frame.
MozBrowserEvent(PipelineId, PipelineId, MozBrowserEvent), MozBrowserEvent(PipelineId, PipelineId, MozBrowserEvent),
/// HTMLIFrameElement Forward or Back traversal. /// HTMLIFrameElement Forward or Back traversal.
TraverseHistory(Option<PipelineId>, TraversalDirection), TraverseHistory(Option<PipelineId>, TraversalDirection),