Auto merge of #6022 - jgraham:webdriver_execute_async_script, r=jdm

<!-- Reviewable:start -->
[<img src="https://reviewable.io/review_button.png" height=40 alt="Review on Reviewable"/>](https://reviewable.io/reviews/servo/servo/6022)
<!-- Reviewable:end -->
This commit is contained in:
bors-servo 2015-05-14 05:02:27 -05:00
commit b05c3fc0c0
9 changed files with 247 additions and 92 deletions

View file

@ -29,6 +29,7 @@ use msg::constellation_msg::{IFrameSandboxState, MozBrowserEvent, NavigationDire
use msg::constellation_msg::{Key, KeyState, KeyModifiers, LoadData};
use msg::constellation_msg::{SubpageId, WindowSizeData};
use msg::constellation_msg::{self, ConstellationChan, Failure};
use msg::constellation_msg::{WebDriverCommandMsg};
use net_traits::{self, ResourceTask};
use net_traits::image_cache_task::ImageCacheTask;
use net_traits::storage_task::{StorageTask, StorageTaskMsg};
@ -49,7 +50,7 @@ use util::geometry::PagePx;
use util::opts;
use util::task::spawn_named;
use clipboard::ClipboardContext;
use webdriver_traits::WebDriverScriptCommand;
use webdriver_traits;
/// Maintains the pipelines and navigation context and grants permission to composite.
///
@ -122,6 +123,9 @@ pub struct Constellation<LTF, STF> {
/// Means of accessing the clipboard
clipboard_ctx: ClipboardContext,
/// Bits of state used to interact with the webdriver implementation
webdriver: WebDriverData
}
/// Stores the navigation context for a single frame in the frame tree.
@ -185,6 +189,18 @@ pub struct SendableFrameTree {
pub children: Vec<SendableFrameTree>,
}
struct WebDriverData {
load_channel: Option<Sender<webdriver_traits::LoadComplete>>
}
impl WebDriverData {
pub fn new() -> WebDriverData {
WebDriverData {
load_channel: None
}
}
}
#[derive(Clone, Copy)]
enum ExitPipelineMode {
Normal,
@ -233,6 +249,7 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> {
},
phantom: PhantomData,
clipboard_ctx: ClipboardContext::new().unwrap(),
webdriver: WebDriverData::new()
};
constellation.run();
});
@ -376,7 +393,7 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> {
// script, and reflow messages have been sent.
ConstellationMsg::LoadComplete => {
debug!("constellation got load complete message");
self.compositor_proxy.send(CompositorMsg::LoadComplete);
self.handle_load_complete_msg()
}
// Handle a forward or back request
ConstellationMsg::Navigate(pipeline_info, direction) => {
@ -426,14 +443,9 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> {
};
sender.send(result).unwrap();
}
ConstellationMsg::CompositePng(reply) => {
self.compositor_proxy.send(CompositorMsg::CreatePng(reply));
}
ConstellationMsg::WebDriverCommand(pipeline_id,
command) => {
ConstellationMsg::WebDriverCommand(command) => {
debug!("constellation got webdriver command message");
self.handle_webdriver_command_msg(pipeline_id,
command);
self.handle_webdriver_msg(command);
}
ConstellationMsg::ViewportConstrained(pipeline_id, constraints) => {
debug!("constellation got viewport-constrained event message");
@ -649,6 +661,14 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> {
}
}
fn handle_load_complete_msg(&mut self) {
self.compositor_proxy.send(CompositorMsg::LoadComplete);
if let Some(ref reply_chan) = self.webdriver.load_channel {
reply_chan.send(webdriver_traits::LoadComplete).unwrap();
}
self.webdriver.load_channel = None;
}
fn handle_navigate_msg(&mut self,
pipeline_info: Option<(PipelineId, SubpageId)>,
direction: constellation_msg::NavigationDirection) {
@ -814,15 +834,24 @@ impl<LTF: LayoutTaskFactory, STF: ScriptTaskFactory> Constellation<LTF, STF> {
}
}
fn handle_webdriver_command_msg(&mut self,
pipeline_id: PipelineId,
msg: WebDriverScriptCommand) {
fn handle_webdriver_msg(&mut self, msg: WebDriverCommandMsg) {
// Find the script channel for the given parent pipeline,
// and pass the event to that script task.
let pipeline = self.pipeline(pipeline_id);
let control_msg = ConstellationControlMsg::WebDriverCommand(pipeline_id, msg);
let ScriptControlChan(ref script_channel) = pipeline.script_chan;
script_channel.send(control_msg).unwrap();
match msg {
WebDriverCommandMsg::LoadUrl(pipeline_id, load_data, reply) => {
self.handle_load_url_msg(pipeline_id, load_data);
self.webdriver.load_channel = Some(reply);
},
WebDriverCommandMsg::ScriptCommand(pipeline_id, cmd) => {
let pipeline = self.pipeline(pipeline_id);
let control_msg = ConstellationControlMsg::WebDriverScriptCommand(pipeline_id, cmd);
let ScriptControlChan(ref script_channel) = pipeline.script_chan;
script_channel.send(control_msg).unwrap();
},
WebDriverCommandMsg::TakeScreenshot(reply) => {
self.compositor_proxy.send(CompositorMsg::CreatePng(reply));
},
}
}
fn add_or_replace_pipeline_in_frame_tree(&mut self, frame_change: FrameChange) {

View file

@ -18,7 +18,7 @@ use util::geometry::{PagePx, ViewportPx};
use std::collections::HashMap;
use std::sync::mpsc::{channel, Sender, Receiver};
use style::viewport::ViewportConstraints;
use webdriver_traits::WebDriverScriptCommand;
use webdriver_traits::{WebDriverScriptCommand, LoadComplete};
use url::Url;
#[derive(Clone)]
@ -237,11 +237,9 @@ pub enum Msg {
/// Requests that the constellation retrieve the current contents of the clipboard
GetClipboardContents(Sender<String>),
/// Dispatch a webdriver command
WebDriverCommand(PipelineId, WebDriverScriptCommand),
WebDriverCommand(WebDriverCommandMsg),
/// Notifies the constellation that the viewport has been constrained in some manner
ViewportConstrained(PipelineId, ViewportConstraints),
/// Create a PNG of the window contents
CompositePng(Sender<Option<png::Image>>),
/// Query the constellation to see if the current compositor output is stable
IsReadyToSaveImage(HashMap<PipelineId, Epoch>),
/// Notification that this iframe should be removed.
@ -319,6 +317,11 @@ impl MozBrowserEvent {
}
}
pub enum WebDriverCommandMsg {
LoadUrl(PipelineId, LoadData, Sender<LoadComplete>),
ScriptCommand(PipelineId, WebDriverScriptCommand),
TakeScreenshot(Sender<Option<png::Image>>)
}
/// Similar to net::resource_task::LoadData
/// can be passed to LoadUrl to load a page with GET/POST

View file

@ -128,6 +128,13 @@ partial interface Window {
};
Window implements OnErrorEventHandlerForWindow;
// WebDriver extensions
partial interface Window {
// Shouldn't be public, but just to make things work for now
void webdriverCallback(optional any result);
void webdriverTimeout();
};
// https://html.spec.whatwg.org/multipage/#dom-sessionstorage
[NoInterfaceObject]
interface WindowSessionStorage {

View file

@ -35,8 +35,10 @@ use script_task::{TimerSource, ScriptChan, ScriptPort, NonWorkerScriptChan};
use script_task::ScriptMsg;
use script_traits::ScriptControlChan;
use timers::{IsInterval, TimerId, TimerManager, TimerCallback};
use webdriver_handlers::jsval_to_webdriver;
use devtools_traits::{DevtoolsControlChan, TimelineMarker, TimelineMarkerType, TracingMetadata};
use webdriver_traits::{WebDriverJSError, WebDriverJSResult};
use msg::compositor_msg::ScriptListener;
use msg::constellation_msg::{LoadData, PipelineId, SubpageId, ConstellationChan, WindowSizeData, WorkerId};
use net_traits::ResourceTask;
@ -166,6 +168,9 @@ pub struct Window {
/// A counter of the number of pending reflows for this window.
pending_reflow_count: Cell<u32>,
/// A channel for communicating results of async scripts back to the webdriver server
webdriver_script_chan: RefCell<Option<Sender<WebDriverJSResult>>>
}
impl Window {
@ -483,6 +488,21 @@ impl<'a> WindowMethods for JSRef<'a, Window> {
let doc = self.Document().root();
doc.r().cancel_animation_frame(ident);
}
fn WebdriverCallback(self, cx: *mut JSContext, val: JSVal) {
let rv = jsval_to_webdriver(cx, val);
let opt_chan = self.webdriver_script_chan.borrow_mut().take();
if let Some(chan) = opt_chan {
chan.send(rv).unwrap();
}
}
fn WebdriverTimeout(self) {
let opt_chan = self.webdriver_script_chan.borrow_mut().take();
if let Some(chan) = opt_chan {
chan.send(Err(WebDriverJSError::Timeout)).unwrap();
}
}
}
pub trait WindowHelpers {
@ -523,6 +543,7 @@ pub trait WindowHelpers {
fn emit_timeline_marker(self, marker: TimelineMarker);
fn set_devtools_timeline_marker(self, marker: TimelineMarkerType, reply: Sender<TimelineMarker>);
fn drop_devtools_timeline_markers(self);
fn set_webdriver_script_chan(self, chan: Option<Sender<WebDriverJSResult>>);
}
pub trait ScriptHelpers {
@ -880,6 +901,10 @@ impl<'a> WindowHelpers for JSRef<'a, Window> {
self.devtools_markers.borrow_mut().clear();
*self.devtools_marker_sender.borrow_mut() = None;
}
fn set_webdriver_script_chan(self, chan: Option<Sender<WebDriverJSResult>>) {
*self.webdriver_script_chan.borrow_mut() = chan;
}
}
impl Window {
@ -947,6 +972,7 @@ impl Window {
devtools_marker_sender: RefCell::new(None),
devtools_markers: RefCell::new(HashSet::new()),
devtools_wants_updates: Cell::new(false),
webdriver_script_chan: RefCell::new(None),
};
WindowBinding::Wrap(runtime.cx(), win)

View file

@ -316,7 +316,7 @@ pub struct ScriptTask {
/// The JavaScript runtime.
js_runtime: Rc<Runtime>,
mouse_over_targets: DOMRefCell<Vec<JS<Node>>>
mouse_over_targets: DOMRefCell<Vec<JS<Node>>>,
}
/// In the event of task failure, all data on the stack runs its destructor. However, there
@ -726,7 +726,7 @@ impl ScriptTask {
self.handle_update_subpage_id(containing_pipeline_id, old_subpage_id, new_subpage_id),
ConstellationControlMsg::FocusIFrame(containing_pipeline_id, subpage_id) =>
self.handle_focus_iframe_msg(containing_pipeline_id, subpage_id),
ConstellationControlMsg::WebDriverCommand(pipeline_id, msg) =>
ConstellationControlMsg::WebDriverScriptCommand(pipeline_id, msg) =>
self.handle_webdriver_msg(pipeline_id, msg),
ConstellationControlMsg::TickAllAnimations(pipeline_id) =>
self.handle_tick_all_animations(pipeline_id),
@ -801,8 +801,8 @@ impl ScriptTask {
fn handle_webdriver_msg(&self, pipeline_id: PipelineId, msg: WebDriverScriptCommand) {
let page = self.root_page();
match msg {
WebDriverScriptCommand::EvaluateJS(script, reply) =>
webdriver_handlers::handle_evaluate_js(&page, pipeline_id, script, reply),
WebDriverScriptCommand::ExecuteScript(script, reply) =>
webdriver_handlers::handle_execute_script(&page, pipeline_id, script, reply),
WebDriverScriptCommand::FindElementCSS(selector, reply) =>
webdriver_handlers::handle_find_element_css(&page, pipeline_id, selector, reply),
WebDriverScriptCommand::FindElementsCSS(selector, reply) =>
@ -814,7 +814,9 @@ impl ScriptTask {
WebDriverScriptCommand::GetElementText(node_id, reply) =>
webdriver_handlers::handle_get_text(&page, pipeline_id, node_id, reply),
WebDriverScriptCommand::GetTitle(reply) =>
webdriver_handlers::handle_get_title(&page, pipeline_id, reply)
webdriver_handlers::handle_get_title(&page, pipeline_id, reply),
WebDriverScriptCommand::ExecuteAsyncScript(script, reply) =>
webdriver_handlers::handle_execute_async_script(&page, pipeline_id, script, reply),
}
}

View file

@ -2,7 +2,7 @@
* 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 webdriver_traits::{EvaluateJSReply};
use webdriver_traits::{WebDriverJSValue, WebDriverJSError, WebDriverJSResult};
use dom::bindings::conversions::FromJSValConvertible;
use dom::bindings::conversions::StringificationBehavior;
use dom::bindings::codegen::InheritTypes::{NodeCast, ElementCast};
@ -12,8 +12,10 @@ use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::Bindings::NodeListBinding::NodeListMethods;
use dom::bindings::js::{OptionalRootable, Rootable, Temporary};
use dom::node::{Node, NodeHelpers};
use dom::window::ScriptHelpers;
use dom::window::{ScriptHelpers, WindowHelpers};
use dom::document::DocumentHelpers;
use js::jsapi::JSContext;
use js::jsval::JSVal;
use page::Page;
use msg::constellation_msg::PipelineId;
use script_task::get_page;
@ -35,26 +37,37 @@ fn find_node_by_unique_id(page: &Rc<Page>, pipeline: PipelineId, node_id: String
None
}
pub fn handle_evaluate_js(page: &Rc<Page>, pipeline: PipelineId, eval: String, reply: Sender<Result<EvaluateJSReply, ()>>) {
pub fn jsval_to_webdriver(cx: *mut JSContext, val: JSVal) -> WebDriverJSResult {
if val.is_undefined() {
Ok(WebDriverJSValue::Undefined)
} else if val.is_boolean() {
Ok(WebDriverJSValue::Boolean(val.to_boolean()))
} else if val.is_double() {
Ok(WebDriverJSValue::Number(FromJSValConvertible::from_jsval(cx, val, ()).unwrap()))
} else if val.is_string() {
//FIXME: use jsstring_to_str when jsval grows to_jsstring
Ok(WebDriverJSValue::String(FromJSValConvertible::from_jsval(cx, val, StringificationBehavior::Default).unwrap()))
} else if val.is_null() {
Ok(WebDriverJSValue::Null)
} else {
Err(WebDriverJSError::UnknownType)
}
}
pub fn handle_execute_script(page: &Rc<Page>, pipeline: PipelineId, eval: String, reply: Sender<WebDriverJSResult>) {
let page = get_page(&*page, pipeline);
let window = page.window().root();
let cx = window.r().get_cx();
let rval = window.r().evaluate_js_on_global_with_result(&eval);
reply.send(if rval.is_undefined() {
Ok(EvaluateJSReply::VoidValue)
} else if rval.is_boolean() {
Ok(EvaluateJSReply::BooleanValue(rval.to_boolean()))
} else if rval.is_double() {
Ok(EvaluateJSReply::NumberValue(FromJSValConvertible::from_jsval(cx, rval, ()).unwrap()))
} else if rval.is_string() {
//FIXME: use jsstring_to_str when jsval grows to_jsstring
Ok(EvaluateJSReply::StringValue(FromJSValConvertible::from_jsval(cx, rval, StringificationBehavior::Default).unwrap()))
} else if rval.is_null() {
Ok(EvaluateJSReply::NullValue)
} else {
Err(())
}).unwrap();
reply.send(jsval_to_webdriver(cx, rval)).unwrap();
}
pub fn handle_execute_async_script(page: &Rc<Page>, pipeline: PipelineId, eval: String, reply: Sender<WebDriverJSResult>) {
let page = get_page(&*page, pipeline);
let window = page.window().root();
window.r().set_webdriver_script_chan(Some(reply));
window.r().evaluate_js_on_global_with_result(&eval);
}
pub fn handle_find_element_css(page: &Rc<Page>, _pipeline: PipelineId, selector: String, reply: Sender<Result<Option<String>, ()>>) {

View file

@ -98,7 +98,7 @@ pub enum ConstellationControlMsg {
/// Set an iframe to be focused. Used when an element in an iframe gains focus.
FocusIFrame(PipelineId, SubpageId),
// Passes a webdriver command to the script task for execution
WebDriverCommand(PipelineId, WebDriverScriptCommand),
WebDriverScriptCommand(PipelineId, WebDriverScriptCommand),
/// Notifies script task that all animations are done
TickAllAnimations(PipelineId),
/// Notifies script that a stylesheet has finished loading.

View file

@ -19,14 +19,14 @@ extern crate rustc_serialize;
extern crate uuid;
extern crate webdriver_traits;
use msg::constellation_msg::{ConstellationChan, LoadData, PipelineId, NavigationDirection};
use msg::constellation_msg::{ConstellationChan, LoadData, PipelineId, NavigationDirection, WebDriverCommandMsg};
use msg::constellation_msg::Msg as ConstellationMsg;
use std::sync::mpsc::channel;
use webdriver_traits::WebDriverScriptCommand;
use std::sync::mpsc::{channel, Receiver};
use webdriver_traits::{WebDriverScriptCommand, WebDriverJSError, WebDriverJSResult};
use url::Url;
use webdriver::command::{WebDriverMessage, WebDriverCommand};
use webdriver::command::{GetParameters, JavascriptCommandParameters, LocatorParameters};
use webdriver::command::{GetParameters, JavascriptCommandParameters, LocatorParameters, TimeoutsParameters};
use webdriver::common::{LocatorStrategy, WebElement};
use webdriver::response::{
WebDriverResponse, NewSessionResponse, ValueResponse};
@ -58,6 +58,9 @@ struct WebdriverSession {
struct Handler {
session: Option<WebdriverSession>,
constellation_chan: ConstellationChan,
script_timeout: u32,
load_timeout: u32,
implicit_wait_timeout: u32
}
impl WebdriverSession {
@ -72,16 +75,32 @@ impl Handler {
pub fn new(constellation_chan: ConstellationChan) -> Handler {
Handler {
session: None,
constellation_chan: constellation_chan
constellation_chan: constellation_chan,
script_timeout: 30_000,
load_timeout: 300_000,
implicit_wait_timeout: 0
}
}
fn get_root_pipeline(&self) -> PipelineId {
let (sender, reciever) = channel();
let ConstellationChan(ref const_chan) = self.constellation_chan;
const_chan.send(ConstellationMsg::GetRootPipeline(sender)).unwrap();
fn get_root_pipeline(&self) -> WebDriverResult<PipelineId> {
let interval = 20;
let iterations = 30_000 / interval;
reciever.recv().unwrap().unwrap()
for _ in 0..iterations {
let (sender, reciever) = channel();
let ConstellationChan(ref const_chan) = self.constellation_chan;
const_chan.send(ConstellationMsg::GetRootPipeline(sender)).unwrap();
if let Some(x) = reciever.recv().unwrap() {
return Ok(x);
};
sleep_ms(interval)
};
Err(WebDriverError::new(ErrorStatus::Timeout,
"Failed to get root window handle"))
}
fn handle_new_session(&mut self) -> WebDriverResult<WebDriverResponse> {
@ -109,12 +128,18 @@ impl Handler {
"Invalid URL"))
};
let pipeline_id = self.get_root_pipeline();
let pipeline_id = try!(self.get_root_pipeline());
let (sender, reciever) = channel();
let load_data = LoadData::new(url);
let ConstellationChan(ref const_chan) = self.constellation_chan;
const_chan.send(ConstellationMsg::LoadUrl(pipeline_id, load_data)).unwrap();
//TODO: Now we ought to wait until we get a load event
let cmd_msg = WebDriverCommandMsg::LoadUrl(pipeline_id, load_data, sender);
const_chan.send(ConstellationMsg::WebDriverCommand(cmd_msg)).unwrap();
//Wait to get a load event
reciever.recv().unwrap();
Ok(WebDriverResponse::Void)
}
@ -131,12 +156,13 @@ impl Handler {
}
fn handle_get_title(&self) -> WebDriverResult<WebDriverResponse> {
let pipeline_id = self.get_root_pipeline();
let pipeline_id = try!(self.get_root_pipeline());
let (sender, reciever) = channel();
let ConstellationChan(ref const_chan) = self.constellation_chan;
const_chan.send(ConstellationMsg::WebDriverCommand(pipeline_id,
WebDriverScriptCommand::GetTitle(sender))).unwrap();
let cmd_msg = WebDriverCommandMsg::ScriptCommand(pipeline_id,
WebDriverScriptCommand::GetTitle(sender));
const_chan.send(ConstellationMsg::WebDriverCommand(cmd_msg)).unwrap();
let value = reciever.recv().unwrap();
Ok(WebDriverResponse::Generic(ValueResponse::new(value.to_json())))
}
@ -156,7 +182,7 @@ impl Handler {
}
fn handle_find_element(&self, parameters: &LocatorParameters) -> WebDriverResult<WebDriverResponse> {
let pipeline_id = self.get_root_pipeline();
let pipeline_id = try!(self.get_root_pipeline());
if parameters.using != LocatorStrategy::CSSSelector {
return Err(WebDriverError::new(ErrorStatus::UnsupportedOperation,
@ -166,7 +192,8 @@ impl Handler {
let (sender, reciever) = channel();
let ConstellationChan(ref const_chan) = self.constellation_chan;
let cmd = WebDriverScriptCommand::FindElementCSS(parameters.value.clone(), sender);
const_chan.send(ConstellationMsg::WebDriverCommand(pipeline_id, cmd)).unwrap();
let cmd_msg = WebDriverCommandMsg::ScriptCommand(pipeline_id, cmd);
const_chan.send(ConstellationMsg::WebDriverCommand(cmd_msg)).unwrap();
match reciever.recv().unwrap() {
Ok(value) => {
Ok(WebDriverResponse::Generic(ValueResponse::new(value.map(|x| WebElement::new(x).to_json()).to_json())))
@ -177,7 +204,7 @@ impl Handler {
}
fn handle_find_elements(&self, parameters: &LocatorParameters) -> WebDriverResult<WebDriverResponse> {
let pipeline_id = self.get_root_pipeline();
let pipeline_id = try!(self.get_root_pipeline());
if parameters.using != LocatorStrategy::CSSSelector {
return Err(WebDriverError::new(ErrorStatus::UnsupportedOperation,
@ -187,7 +214,8 @@ impl Handler {
let (sender, reciever) = channel();
let ConstellationChan(ref const_chan) = self.constellation_chan;
let cmd = WebDriverScriptCommand::FindElementsCSS(parameters.value.clone(), sender);
const_chan.send(ConstellationMsg::WebDriverCommand(pipeline_id, cmd)).unwrap();
let cmd_msg = WebDriverCommandMsg::ScriptCommand(pipeline_id, cmd);
const_chan.send(ConstellationMsg::WebDriverCommand(cmd_msg)).unwrap();
match reciever.recv().unwrap() {
Ok(value) => {
let resp_value: Vec<Json> = value.into_iter().map(
@ -200,12 +228,13 @@ impl Handler {
}
fn handle_get_element_text(&self, element: &WebElement) -> WebDriverResult<WebDriverResponse> {
let pipeline_id = self.get_root_pipeline();
let pipeline_id = try!(self.get_root_pipeline());
let (sender, reciever) = channel();
let ConstellationChan(ref const_chan) = self.constellation_chan;
let cmd = WebDriverScriptCommand::GetElementText(element.id.clone(), sender);
const_chan.send(ConstellationMsg::WebDriverCommand(pipeline_id, cmd)).unwrap();
let cmd_msg = WebDriverCommandMsg::ScriptCommand(pipeline_id, cmd);
const_chan.send(ConstellationMsg::WebDriverCommand(cmd_msg)).unwrap();
match reciever.recv().unwrap() {
Ok(value) => Ok(WebDriverResponse::Generic(ValueResponse::new(value.to_json()))),
Err(_) => Err(WebDriverError::new(ErrorStatus::StaleElementReference,
@ -214,23 +243,25 @@ impl Handler {
}
fn handle_get_active_element(&self) -> WebDriverResult<WebDriverResponse> {
let pipeline_id = self.get_root_pipeline();
let pipeline_id = try!(self.get_root_pipeline());
let (sender, reciever) = channel();
let ConstellationChan(ref const_chan) = self.constellation_chan;
let cmd = WebDriverScriptCommand::GetActiveElement(sender);
const_chan.send(ConstellationMsg::WebDriverCommand(pipeline_id, cmd)).unwrap();
let cmd_msg = WebDriverCommandMsg::ScriptCommand(pipeline_id, cmd);
const_chan.send(ConstellationMsg::WebDriverCommand(cmd_msg)).unwrap();
let value = reciever.recv().unwrap().map(|x| WebElement::new(x).to_json());
Ok(WebDriverResponse::Generic(ValueResponse::new(value.to_json())))
}
fn handle_get_element_tag_name(&self, element: &WebElement) -> WebDriverResult<WebDriverResponse> {
let pipeline_id = self.get_root_pipeline();
let pipeline_id = try!(self.get_root_pipeline());
let (sender, reciever) = channel();
let ConstellationChan(ref const_chan) = self.constellation_chan;
let cmd = WebDriverScriptCommand::GetElementTagName(element.id.clone(), sender);
const_chan.send(ConstellationMsg::WebDriverCommand(pipeline_id, cmd)).unwrap();
let cmd_msg = WebDriverCommandMsg::ScriptCommand(pipeline_id, cmd);
const_chan.send(ConstellationMsg::WebDriverCommand(cmd_msg)).unwrap();
match reciever.recv().unwrap() {
Ok(value) => Ok(WebDriverResponse::Generic(ValueResponse::new(value.to_json()))),
Err(_) => Err(WebDriverError::new(ErrorStatus::StaleElementReference,
@ -238,11 +269,20 @@ impl Handler {
}
}
fn handle_execute_script(&self, parameters: &JavascriptCommandParameters) -> WebDriverResult<WebDriverResponse> {
// TODO: This isn't really right because it always runs the script in the
// root window
let pipeline_id = self.get_root_pipeline();
fn handle_set_timeouts(&mut self, parameters: &TimeoutsParameters) -> WebDriverResult<WebDriverResponse> {
//TODO: this conversion is crazy, spec should limit these to u32 and check upstream
let value = parameters.ms as u32;
match &parameters.type_[..] {
"implicit" => self.implicit_wait_timeout = value,
"page load" => self.load_timeout = value,
"script" => self.script_timeout = value,
x @ _ => return Err(WebDriverError::new(ErrorStatus::InvalidSelector,
&format!("Unknown timeout type {}", x)))
}
Ok(WebDriverResponse::Void)
}
fn handle_execute_script(&self, parameters: &JavascriptCommandParameters) -> WebDriverResult<WebDriverResponse> {
let func_body = &parameters.script;
let args_string = "";
@ -252,18 +292,40 @@ impl Handler {
let script = format!("(function() {{ {} }})({})", func_body, args_string);
let (sender, reciever) = channel();
let command = WebDriverScriptCommand::ExecuteScript(script, sender);
self.execute_script(command, reciever)
}
fn handle_execute_async_script(&self, parameters: &JavascriptCommandParameters) -> WebDriverResult<WebDriverResponse> {
let func_body = &parameters.script;
let args_string = "window.webdriverCallback";
let script = format!(
"setTimeout(webdriverTimeout, {}); (function(callback) {{ {} }})({})",
self.script_timeout, func_body, args_string);
let (sender, reciever) = channel();
let command = WebDriverScriptCommand::ExecuteAsyncScript(script, sender);
self.execute_script(command, reciever)
}
fn execute_script(&self, command: WebDriverScriptCommand, reciever: Receiver<WebDriverJSResult>) -> WebDriverResult<WebDriverResponse> {
// TODO: This isn't really right because it always runs the script in the
// root window
let pipeline_id = try!(self.get_root_pipeline());
let ConstellationChan(ref const_chan) = self.constellation_chan;
const_chan.send(ConstellationMsg::WebDriverCommand(pipeline_id,
WebDriverScriptCommand::EvaluateJS(script, sender))).unwrap();
let cmd_msg = WebDriverCommandMsg::ScriptCommand(pipeline_id, command);
const_chan.send(ConstellationMsg::WebDriverCommand(cmd_msg)).unwrap();
match reciever.recv().unwrap() {
Ok(value) => Ok(WebDriverResponse::Generic(ValueResponse::new(value.to_json()))),
Err(_) => Err(WebDriverError::new(ErrorStatus::UnsupportedOperation,
"Unsupported return type"))
Err(WebDriverJSError::Timeout) => Err(WebDriverError::new(ErrorStatus::Timeout, "")),
Err(WebDriverJSError::UnknownType) => Err(WebDriverError::new(
ErrorStatus::UnsupportedOperation, "Unsupported return type"))
}
}
fn handle_take_screenshot(&self) -> WebDriverResult<WebDriverResponse> {
let mut img = None;
@ -273,7 +335,8 @@ impl Handler {
for _ in 0..iterations {
let (sender, reciever) = channel();
let ConstellationChan(ref const_chan) = self.constellation_chan;
const_chan.send(ConstellationMsg::CompositePng(sender)).unwrap();
let cmd_msg = WebDriverCommandMsg::TakeScreenshot(sender);
const_chan.send(ConstellationMsg::WebDriverCommand(cmd_msg)).unwrap();
if let Some(x) = reciever.recv().unwrap() {
img = Some(x);
@ -321,6 +384,8 @@ impl WebDriverHandler for Handler {
WebDriverCommand::GetElementText(ref element) => self.handle_get_element_text(element),
WebDriverCommand::GetElementTagName(ref element) => self.handle_get_element_tag_name(element),
WebDriverCommand::ExecuteScript(ref x) => self.handle_execute_script(x),
WebDriverCommand::ExecuteAsyncScript(ref x) => self.handle_execute_async_script(x),
WebDriverCommand::SetTimeouts(ref x) => self.handle_set_timeouts(x),
WebDriverCommand::TakeScreenshot => self.handle_take_screenshot(),
_ => Err(WebDriverError::new(ErrorStatus::UnsupportedOperation,
"Command not implemented"))

View file

@ -11,7 +11,8 @@ use rustc_serialize::json::{Json, ToJson};
use std::sync::mpsc::Sender;
pub enum WebDriverScriptCommand {
EvaluateJS(String, Sender<Result<EvaluateJSReply, ()>>),
ExecuteScript(String, Sender<WebDriverJSResult>),
ExecuteAsyncScript(String, Sender<WebDriverJSResult>),
FindElementCSS(String, Sender<Result<Option<String>, ()>>),
FindElementsCSS(String, Sender<Result<Vec<String>, ()>>),
GetActiveElement(Sender<Option<String>>),
@ -20,23 +21,32 @@ pub enum WebDriverScriptCommand {
GetTitle(Sender<String>)
}
pub enum EvaluateJSReply {
VoidValue,
NullValue,
BooleanValue(bool),
NumberValue(f64),
StringValue(String),
pub enum WebDriverJSValue {
Undefined,
Null,
Boolean(bool),
Number(f64),
String(String),
// TODO: ObjectValue and WebElementValue
}
impl ToJson for EvaluateJSReply {
pub enum WebDriverJSError {
Timeout,
UnknownType
}
pub type WebDriverJSResult = Result<WebDriverJSValue, WebDriverJSError>;
impl ToJson for WebDriverJSValue {
fn to_json(&self) -> Json {
match self {
&EvaluateJSReply::VoidValue => Json::Null,
&EvaluateJSReply::NullValue => Json::Null,
&EvaluateJSReply::BooleanValue(ref x) => x.to_json(),
&EvaluateJSReply::NumberValue(ref x) => x.to_json(),
&EvaluateJSReply::StringValue(ref x) => x.to_json()
&WebDriverJSValue::Undefined => Json::Null,
&WebDriverJSValue::Null => Json::Null,
&WebDriverJSValue::Boolean(ref x) => x.to_json(),
&WebDriverJSValue::Number(ref x) => x.to_json(),
&WebDriverJSValue::String(ref x) => x.to_json()
}
}
}
pub struct LoadComplete;