1use std::collections::HashMap;
6use std::ffi::CString;
7use std::ptr::NonNull;
8
9use cookie::Cookie;
10use embedder_traits::{
11 CustomHandlersAutomationMode, JSValue, JavaScriptEvaluationError,
12 JavaScriptEvaluationResultSerializationError, WebDriverFrameId, WebDriverJSResult,
13};
14use euclid::default::{Point2D, Rect, Size2D};
15use hyper_serde::Serde;
16use js::context::JSContext;
17use js::conversions::{FromJSValConvertible, jsstr_to_string};
18use js::gc::RootedVec;
19use js::jsapi::{HandleValueArray, Heap, JSITER_OWNONLY, JSType, PropertyDescriptor};
20use js::jsval::{JSVal, UndefinedValue};
21use js::realm::CurrentRealm;
22use js::rust::wrappers2::{
23 IsArgumentsObject, JS_CallFunctionName, JS_HasOwnProperty, JS_TypeOfValue,
24};
25use js::rust::{HandleObject, HandleValue, IdVector};
26use net_traits::CookieSource::{HTTP, NonHTTP};
27use net_traits::CoreResourceMsg::{DeleteCookie, DeleteCookies, GetCookiesForUrl, SetCookieForUrl};
28use script_bindings::codegen::GenericBindings::PermissionStatusBinding::{
29 PermissionName, PermissionState,
30};
31use script_bindings::codegen::GenericBindings::ShadowRootBinding::ShadowRootMethods;
32use script_bindings::conversions::is_array_like;
33use script_bindings::js::{
34 GetPropertyKeys, JS_GetOwnPropertyDescriptorById, JS_GetProperty, JS_GetPropertyById,
35 JS_IsExceptionPending,
36};
37use script_bindings::num::Finite;
38use script_bindings::reflector::DomObject;
39use script_bindings::settings_stack::run_a_script;
40use servo_base::Epoch;
41use servo_base::generic_channel::{self, GenericOneshotSender, GenericSend, GenericSender};
42use servo_base::id::{BrowsingContextId, PipelineId};
43use servo_config::pref;
44use webdriver::command::SetPermissionState;
45use webdriver::error::ErrorStatus;
46
47use crate::DomTypeHolder;
48use crate::dom::Promise;
49use crate::dom::attr::is_boolean_attribute;
50use crate::dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::CSSStyleDeclarationMethods;
51use crate::dom::bindings::codegen::Bindings::DOMRectBinding::DOMRectMethods;
52use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
53use crate::dom::bindings::codegen::Bindings::ElementBinding::{
54 ElementMethods, ScrollIntoViewOptions, ScrollLogicalPosition,
55};
56use crate::dom::bindings::codegen::Bindings::HTMLElementBinding::HTMLElementMethods;
57use crate::dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods;
58use crate::dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods;
59use crate::dom::bindings::codegen::Bindings::HTMLOrSVGOrMathMLElementBinding::FocusOptions;
60use crate::dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods;
61use crate::dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding::HTMLTextAreaElementMethods;
62use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
63use crate::dom::bindings::codegen::Bindings::WindowBinding::{
64 ScrollBehavior, ScrollOptions, WindowMethods,
65};
66use crate::dom::bindings::codegen::Bindings::XMLSerializerBinding::XMLSerializerMethods;
67use crate::dom::bindings::codegen::Bindings::XPathResultBinding::{
68 XPathResultConstants, XPathResultMethods,
69};
70use crate::dom::bindings::codegen::UnionTypes::BooleanOrScrollIntoViewOptions;
71use crate::dom::bindings::conversions::{
72 ConversionBehavior, ConversionResult, get_property, get_property_jsval, jsid_to_string,
73 root_from_object,
74};
75use crate::dom::bindings::error::{
76 Error, ErrorInfo, javascript_error_info_from_error_info, report_pending_exception,
77 throw_dom_exception,
78};
79use crate::dom::bindings::inheritance::Castable;
80use crate::dom::bindings::reflector::DomGlobal;
81use crate::dom::bindings::root::DomRoot;
82use crate::dom::bindings::str::DOMString;
83use crate::dom::document::Document;
84use crate::dom::domrect::DOMRect;
85use crate::dom::element::Element;
86use crate::dom::eventtarget::EventTarget;
87use crate::dom::globalscope::GlobalScope;
88use crate::dom::html::form_controls::htmlinputelement::HTMLInputElement;
89use crate::dom::html::form_controls::input_type::InputType;
90use crate::dom::html::htmlbodyelement::HTMLBodyElement;
91use crate::dom::html::htmldatalistelement::HTMLDataListElement;
92use crate::dom::html::htmlelement::HTMLElement;
93use crate::dom::html::htmlformelement::FormControl;
94use crate::dom::html::htmliframeelement::HTMLIFrameElement;
95use crate::dom::html::htmloptgroupelement::HTMLOptGroupElement;
96use crate::dom::html::htmloptionelement::HTMLOptionElement;
97use crate::dom::html::htmlselectelement::HTMLSelectElement;
98use crate::dom::html::htmltextareaelement::HTMLTextAreaElement;
99use crate::dom::iterators::ShadowIncluding;
100use crate::dom::node::{Node, NodeTraits};
101use crate::dom::nodelist::NodeList;
102use crate::dom::promisenativehandler::Callback;
103use crate::dom::types::{PromiseNativeHandler, ShadowRoot};
104use crate::dom::validitystate::ValidationFlags;
105use crate::dom::window::Window;
106use crate::dom::xmlserializer::XMLSerializer;
107use crate::event_loop::document_collection::DocumentCollection;
108use crate::event_loop::script_thread::ScriptThread;
109use crate::realms::enter_auto_realm;
110
111fn is_stale(element: &Element) -> bool {
113 !element.owner_document().is_active() || !element.is_connected()
116}
117
118fn is_detached(shadow_root: &ShadowRoot) -> bool {
120 !shadow_root.owner_document().is_active() || is_stale(&shadow_root.Host())
123}
124
125fn is_disabled(element: &Element) -> bool {
127 if element.is::<HTMLOptionElement>() || element.is::<HTMLOptGroupElement>() {
129 let disabled = element
131 .upcast::<Node>()
132 .inclusive_ancestors(ShadowIncluding::No)
133 .any(|node| {
134 if node.is::<HTMLOptGroupElement>() || node.is::<HTMLSelectElement>() {
135 node.downcast::<Element>().unwrap().is_actually_disabled()
138 } else {
139 false
140 }
141 });
142
143 if disabled {
148 return true;
149 }
150 }
151 element.is_actually_disabled()
153}
154
155pub(crate) fn handle_get_known_window(
156 documents: &DocumentCollection,
157 pipeline: PipelineId,
158 webview_id: String,
159 reply: GenericSender<Result<(), ErrorStatus>>,
160) {
161 if reply
162 .send(
163 documents
164 .find_window(pipeline)
165 .map_or(Err(ErrorStatus::NoSuchWindow), |window| {
166 let window_proxy = window.window_proxy();
167 if window_proxy.browsing_context_id() != window_proxy.webview_id() ||
169 window_proxy.webview_id().to_string() != webview_id
170 {
171 Err(ErrorStatus::NoSuchWindow)
172 } else {
173 Ok(())
174 }
175 }),
176 )
177 .is_err()
178 {
179 error!("Webdriver get known window reply failed");
180 }
181}
182
183pub(crate) fn handle_get_known_shadow_root(
184 documents: &DocumentCollection,
185 pipeline: PipelineId,
186 shadow_root_id: String,
187 reply: GenericSender<Result<(), ErrorStatus>>,
188) {
189 let result = get_known_shadow_root(documents, pipeline, shadow_root_id).map(|_| ());
190 if reply.send(result).is_err() {
191 error!("Webdriver get known shadow root reply failed");
192 }
193}
194
195fn get_known_shadow_root(
197 documents: &DocumentCollection,
198 pipeline: PipelineId,
199 node_id: String,
200) -> Result<DomRoot<ShadowRoot>, ErrorStatus> {
201 let doc = documents
202 .find_document(pipeline)
203 .ok_or(ErrorStatus::NoSuchWindow)?;
204 if !ScriptThread::has_node_id(pipeline, &node_id) {
207 return Err(ErrorStatus::NoSuchShadowRoot);
208 }
209
210 let node = find_node_by_unique_id_in_document(&doc, node_id);
213
214 if let Some(ref node) = node &&
217 !node.is::<ShadowRoot>()
218 {
219 return Err(ErrorStatus::NoSuchShadowRoot);
220 }
221
222 let Some(node) = node else {
224 return Err(ErrorStatus::DetachedShadowRoot);
225 };
226
227 let shadow_root = DomRoot::downcast::<ShadowRoot>(node).unwrap();
231 if is_detached(&shadow_root) {
232 return Err(ErrorStatus::DetachedShadowRoot);
233 }
234 Ok(shadow_root)
236}
237
238pub(crate) fn handle_get_known_element(
239 documents: &DocumentCollection,
240 pipeline: PipelineId,
241 element_id: String,
242 reply: GenericSender<Result<(), ErrorStatus>>,
243) {
244 let result = get_known_element(documents, pipeline, element_id).map(|_| ());
245 if reply.send(result).is_err() {
246 error!("Webdriver get known element reply failed");
247 }
248}
249
250fn get_known_element(
252 documents: &DocumentCollection,
253 pipeline: PipelineId,
254 node_id: String,
255) -> Result<DomRoot<Element>, ErrorStatus> {
256 let doc = documents
257 .find_document(pipeline)
258 .ok_or(ErrorStatus::NoSuchWindow)?;
259 if !ScriptThread::has_node_id(pipeline, &node_id) {
262 return Err(ErrorStatus::NoSuchElement);
263 }
264 let node = find_node_by_unique_id_in_document(&doc, node_id);
267
268 if let Some(ref node) = node &&
271 !node.is::<Element>()
272 {
273 return Err(ErrorStatus::NoSuchElement);
274 }
275 let Some(node) = node else {
277 return Err(ErrorStatus::StaleElementReference);
278 };
279 let element = DomRoot::downcast::<Element>(node).unwrap();
281 if is_stale(&element) {
282 return Err(ErrorStatus::StaleElementReference);
283 }
284 Ok(element)
286}
287
288pub(crate) fn find_node_by_unique_id_in_document(
290 document: &Document,
291 node_id: String,
292) -> Option<DomRoot<Node>> {
293 let pipeline = document.window().pipeline_id();
294 document
295 .upcast::<Node>()
296 .traverse_preorder(ShadowIncluding::Yes)
297 .find(|node| node.unique_id(pipeline) == node_id)
298}
299
300fn matching_links(
302 cx: &mut JSContext,
303 links: &NodeList,
304 link_text: String,
305 partial: bool,
306) -> Vec<String> {
307 let links: Vec<_> = links.iter(cx).map(|node| node.as_rooted()).collect();
308 links
309 .into_iter()
310 .filter(|node| {
311 let content = node
312 .downcast::<HTMLElement>()
313 .map(|element| element.InnerText(cx))
314 .map_or(String::new(), String::from)
315 .trim()
316 .to_owned();
317 if partial {
318 content.contains(&link_text)
319 } else {
320 content == link_text
321 }
322 })
323 .map(|node| node.unique_id(node.owner_doc().window().pipeline_id()))
324 .collect()
325}
326
327fn all_matching_links(
328 cx: &mut JSContext,
329 root_node: &Node,
330 link_text: String,
331 partial: bool,
332) -> Result<Vec<String>, ErrorStatus> {
333 root_node
337 .query_selector_all(cx, DOMString::from_static("a"))
338 .map_err(|_| ErrorStatus::InvalidSelector)
339 .map(|nodes| matching_links(cx, &nodes, link_text, partial))
340}
341
342#[expect(unsafe_code)]
343fn object_has_to_json_property(
344 cx: &mut JSContext,
345 global_scope: &GlobalScope,
346 object: HandleObject,
347) -> bool {
348 let name = CString::new("toJSON").unwrap();
349 let mut found = false;
350 if unsafe { JS_HasOwnProperty(cx, object, name.as_ptr(), &mut found) } && found {
351 rooted!(&in(cx) let mut value = UndefinedValue());
352 let result = JS_GetProperty(cx, object, &name, value.handle_mut());
353 if !result {
354 throw_dom_exception(cx, global_scope, Error::JSFailed);
355 false
356 } else {
357 result && unsafe { JS_TypeOfValue(cx, value.handle()) } == JSType::JSTYPE_FUNCTION
358 }
359 } else if JS_IsExceptionPending(cx) {
360 throw_dom_exception(cx, global_scope, Error::JSFailed);
361 false
362 } else {
363 false
364 }
365}
366
367#[expect(unsafe_code)]
368fn is_arguments_object(object: HandleObject) -> bool {
370 unsafe { IsArgumentsObject(object) }
371}
372
373pub(crate) fn jsval_to_webdriver(
375 cx: &mut CurrentRealm,
376 global_scope: &GlobalScope,
377 val: HandleValue,
378) -> WebDriverJSResult {
379 run_a_script::<DomTypeHolder, _, _>(cx, global_scope, |cx| {
380 rooted_vec!(let mut seen);
382 let result = jsval_to_webdriver_inner(cx, global_scope, val, &mut seen);
383
384 if result.is_err() {
385 report_pending_exception(cx);
386 }
387 result
388 })
389}
390
391#[expect(unsafe_code)]
392fn jsval_to_webdriver_inner(
394 cx: &mut CurrentRealm,
395 global_scope: &GlobalScope,
396 val: HandleValue,
397 seen: &mut RootedVec<'_, Box<Heap<JSVal>>>,
398) -> WebDriverJSResult {
399 if val.get().is_undefined() {
400 Ok(JSValue::Undefined)
401 } else if val.get().is_null() {
402 Ok(JSValue::Null)
403 } else if val.get().is_boolean() {
404 Ok(JSValue::Boolean(val.get().to_boolean()))
405 } else if val.get().is_number() {
406 Ok(JSValue::Number(val.to_number()))
407 } else if val.get().is_string() {
408 let string = NonNull::new(val.to_string()).expect("Should have a non-Null String");
409 let string = unsafe { jsstr_to_string(cx, string) };
410 Ok(JSValue::String(string))
411 } else if val.get().is_object() {
412 rooted!(&in(cx) let object = match FromJSValConvertible::from_jsval(cx, val, ()).unwrap() {
413 ConversionResult::Success(object) => object,
414 _ => unreachable!(),
415 });
416
417 if let Ok(element) = unsafe { root_from_object::<Element>(cx, *object) } {
418 if is_stale(&element) {
420 Err(JavaScriptEvaluationError::SerializationError(
421 JavaScriptEvaluationResultSerializationError::StaleElementReference,
422 ))
423 } else {
424 Ok(JSValue::Element(
425 element
426 .upcast::<Node>()
427 .unique_id(element.owner_window().pipeline_id()),
428 ))
429 }
430 } else if let Ok(shadow_root) = unsafe { root_from_object::<ShadowRoot>(cx, *object) } {
431 if is_detached(&shadow_root) {
433 Err(JavaScriptEvaluationError::SerializationError(
434 JavaScriptEvaluationResultSerializationError::DetachedShadowRoot,
435 ))
436 } else {
437 Ok(JSValue::ShadowRoot(
438 shadow_root
439 .upcast::<Node>()
440 .unique_id(shadow_root.owner_window().pipeline_id()),
441 ))
442 }
443 } else if let Ok(window) = unsafe { root_from_object::<Window>(cx, *object) } {
444 let window_proxy = window.window_proxy();
445 if window_proxy.is_browsing_context_discarded() {
446 Err(JavaScriptEvaluationError::SerializationError(
447 JavaScriptEvaluationResultSerializationError::StaleElementReference,
448 ))
449 } else if window_proxy.browsing_context_id() == window_proxy.webview_id() {
450 Ok(JSValue::Window(window.webview_id().to_string()))
451 } else {
452 Ok(JSValue::Frame(
453 window_proxy.browsing_context_id().to_string(),
454 ))
455 }
456 } else if object_has_to_json_property(cx, global_scope, object.handle()) {
457 let name = CString::new("toJSON").unwrap();
458 rooted!(&in(cx) let mut value = UndefinedValue());
459 let call_result = unsafe {
460 JS_CallFunctionName(
461 cx,
462 object.handle(),
463 name.as_ptr(),
464 &HandleValueArray::empty(),
465 value.handle_mut(),
466 )
467 };
468
469 if call_result {
470 Ok(jsval_to_webdriver_inner(
471 cx,
472 global_scope,
473 value.handle(),
474 seen,
475 )?)
476 } else {
477 throw_dom_exception(cx, global_scope, Error::JSFailed);
478 Err(JavaScriptEvaluationError::SerializationError(
479 JavaScriptEvaluationResultSerializationError::OtherJavaScriptError,
480 ))
481 }
482 } else {
483 clone_an_object(cx, global_scope, val, seen, object.handle())
484 }
485 } else {
486 Err(JavaScriptEvaluationError::SerializationError(
487 JavaScriptEvaluationResultSerializationError::UnknownType,
488 ))
489 }
490}
491
492fn clone_an_object(
494 cx: &mut CurrentRealm,
495 global_scope: &GlobalScope,
496 val: HandleValue,
497 seen: &mut RootedVec<'_, Box<Heap<JSVal>>>,
498 object_handle: HandleObject,
499) -> WebDriverJSResult {
500 if seen
502 .iter()
503 .any(|seen_value| seen_value.get().asBits_ == val.get().asBits_)
504 {
505 return Err(JavaScriptEvaluationError::SerializationError(
506 JavaScriptEvaluationResultSerializationError::OtherJavaScriptError,
507 ));
508 }
509 seen.push(Heap::boxed(val.get()));
511
512 let return_val = if is_array_like::<crate::DomTypeHolder>(cx, val) ||
513 is_arguments_object(object_handle)
514 {
515 let mut result: Vec<JSValue> = Vec::new();
516
517 let get_property_result =
518 get_property::<u32>(cx, object_handle, c"length", ConversionBehavior::Default);
519 let length = match get_property_result {
520 Ok(length) => match length {
521 Some(length) => length,
522 _ => {
523 return Err(JavaScriptEvaluationError::SerializationError(
524 JavaScriptEvaluationResultSerializationError::UnknownType,
525 ));
526 },
527 },
528 Err(error) => {
529 throw_dom_exception(cx, global_scope, error);
530 return Err(JavaScriptEvaluationError::SerializationError(
531 JavaScriptEvaluationResultSerializationError::OtherJavaScriptError,
532 ));
533 },
534 };
535 for i in 0..length {
537 rooted!(&in(cx) let mut item = UndefinedValue());
538 let cname = CString::new(i.to_string()).unwrap();
539 let get_property_result =
540 get_property_jsval(cx, object_handle, &cname, item.handle_mut());
541 match get_property_result {
542 Ok(_) => {
543 let converted_item =
544 jsval_to_webdriver_inner(cx, global_scope, item.handle(), seen)?;
545
546 result.push(converted_item);
547 },
548 Err(error) => {
549 throw_dom_exception(cx, global_scope, error);
550 return Err(JavaScriptEvaluationError::SerializationError(
551 JavaScriptEvaluationResultSerializationError::OtherJavaScriptError,
552 ));
553 },
554 }
555 }
556 Ok(JSValue::Array(result))
557 } else {
558 let mut result = HashMap::new();
559
560 let mut ids = IdVector::new(cx);
561 let succeeded = GetPropertyKeys(cx, object_handle, JSITER_OWNONLY, ids.handle_mut());
562 if !succeeded {
563 return Err(JavaScriptEvaluationError::SerializationError(
564 JavaScriptEvaluationResultSerializationError::OtherJavaScriptError,
565 ));
566 }
567 for id in ids.iter() {
568 rooted!(&in(cx) let id = *id);
569 rooted!(&in(cx) let mut desc = PropertyDescriptor::default());
570
571 let mut is_none = false;
572 let succeeded = JS_GetOwnPropertyDescriptorById(
573 cx,
574 object_handle,
575 id.handle(),
576 desc.handle_mut(),
577 &mut is_none,
578 );
579 if !succeeded {
580 return Err(JavaScriptEvaluationError::SerializationError(
581 JavaScriptEvaluationResultSerializationError::OtherJavaScriptError,
582 ));
583 }
584
585 rooted!(&in(cx) let mut property = UndefinedValue());
586 let succeeded =
587 JS_GetPropertyById(cx, object_handle, id.handle(), property.handle_mut());
588 if !succeeded {
589 return Err(JavaScriptEvaluationError::SerializationError(
590 JavaScriptEvaluationResultSerializationError::OtherJavaScriptError,
591 ));
592 }
593
594 if !property.is_undefined() {
595 let name = jsid_to_string(cx, id.handle());
596 let Some(name) = name else {
597 return Err(JavaScriptEvaluationError::SerializationError(
598 JavaScriptEvaluationResultSerializationError::OtherJavaScriptError,
599 ));
600 };
601
602 let value = jsval_to_webdriver_inner(cx, global_scope, property.handle(), seen)?;
603 result.insert(name.into(), value);
604 }
605 }
606 Ok(JSValue::Object(result))
607 };
608 seen.pop();
610 return_val
612}
613
614#[derive(MallocSizeOf, JSTraceable)]
615struct WebDriverExecuteScriptFulfillmentHandler {
616 #[no_trace]
617 reply_sender: GenericSender<WebDriverJSResult>,
618}
619
620impl Callback for WebDriverExecuteScriptFulfillmentHandler {
621 fn callback(&self, cx: &mut CurrentRealm, return_value: HandleValue) {
622 let global_scope = GlobalScope::from_current_realm(cx);
623 let result = jsval_to_webdriver(cx, &global_scope, return_value);
624 let _ = self.reply_sender.send(result);
625 }
626}
627
628#[derive(MallocSizeOf, JSTraceable)]
629struct WebDriverExecuteScriptRejectionHandler {
630 #[no_trace]
631 reply_sender: GenericSender<WebDriverJSResult>,
632}
633
634impl Callback for WebDriverExecuteScriptRejectionHandler {
635 fn callback(&self, cx: &mut CurrentRealm, return_value: HandleValue) {
636 let error_info = ErrorInfo::from_value(cx, return_value);
637 let _ = self
638 .reply_sender
639 .send(Err(JavaScriptEvaluationError::EvaluationFailure(Some(
640 javascript_error_info_from_error_info(cx, &error_info, return_value),
641 ))));
642 }
643}
644
645pub(crate) fn handle_execute_script(
646 cx: &mut JSContext,
647 window: Option<DomRoot<Window>>,
648 eval: String,
649 reply_sender: GenericSender<WebDriverJSResult>,
650) {
651 let Some(window) = window else {
652 reply_sender
653 .send(Err(JavaScriptEvaluationError::DocumentNotFound))
654 .unwrap_or_else(|error| {
655 error!("ExecuteAsyncScript Failed to send reply: {error}");
656 });
657 return;
658 };
659
660 let global_scope = window.as_global_scope();
661 let mut realm = enter_auto_realm(cx, global_scope);
662 let mut realm = realm.current_realm();
663 let cx = &mut realm;
664
665 rooted!(&in(cx) let mut return_value = UndefinedValue());
666 if let Err(error) = global_scope.evaluate_js_on_global(
667 cx,
668 eval.into(),
669 "",
670 None, Some(return_value.handle_mut()),
672 ) {
673 reply_sender.send(Err(error)).unwrap_or_else(|error| {
674 error!("ExecuteAsyncScript Failed to send reply: {error}");
675 });
676 return;
677 }
678
679 let promise = Promise::new_resolved(cx, global_scope, return_value.handle());
680 let fulfillment_handler = WebDriverExecuteScriptFulfillmentHandler {
681 reply_sender: reply_sender.clone(),
682 };
683 let rejection_handler = WebDriverExecuteScriptRejectionHandler { reply_sender };
684
685 let handler = PromiseNativeHandler::new(
686 cx,
687 global_scope,
688 Some(Box::new(fulfillment_handler)),
689 Some(Box::new(rejection_handler)),
690 );
691 promise.append_native_handler(cx, &handler);
692}
693
694pub(crate) fn handle_get_parent_frame_id(
696 documents: &DocumentCollection,
697 pipeline: PipelineId,
698 reply: GenericSender<Result<BrowsingContextId, ErrorStatus>>,
699) {
700 reply
703 .send(
704 documents
705 .find_window(pipeline)
706 .and_then(|window| {
707 window
708 .window_proxy()
709 .parent()
710 .map(|parent| parent.browsing_context_id())
711 })
712 .ok_or(ErrorStatus::NoSuchWindow),
713 )
714 .unwrap();
715}
716
717pub(crate) fn handle_get_browsing_context_id(
719 documents: &DocumentCollection,
720 pipeline: PipelineId,
721 webdriver_frame_id: WebDriverFrameId,
722 reply: GenericSender<Result<BrowsingContextId, ErrorStatus>>,
723) {
724 reply
725 .send(match webdriver_frame_id {
726 WebDriverFrameId::Short(id) => {
727 documents
730 .find_document(pipeline)
731 .ok_or(ErrorStatus::NoSuchWindow)
732 .and_then(|document| {
733 document
734 .iframes()
735 .iter()
736 .nth(id as usize)
737 .and_then(|iframe| iframe.browsing_context_id())
738 .ok_or(ErrorStatus::NoSuchFrame)
739 })
740 },
741 WebDriverFrameId::Element(element_id) => {
742 get_known_element(documents, pipeline, element_id).and_then(|element| {
743 element
744 .downcast::<HTMLIFrameElement>()
745 .and_then(|element| element.browsing_context_id())
746 .ok_or(ErrorStatus::NoSuchFrame)
747 })
748 },
749 })
750 .unwrap();
751}
752
753fn get_element_in_view_center_point(cx: &mut JSContext, element: &Element) -> Option<Point2D<i64>> {
755 let doc = element.owner_document();
756 element.GetClientRects(cx).first().map(|rectangle| {
759 let x = rectangle.X();
760 let y = rectangle.Y();
761 let width = rectangle.Width();
762 let height = rectangle.Height();
763 debug!(
764 "get_element_in_view_center_point: Element rectangle at \
765 (x: {x}, y: {y}, width: {width}, height: {height})",
766 );
767 let window = doc.window();
768 let left = (x.min(x + width)).max(0.0);
770 let right = f64::min(window.InnerWidth() as f64, x.max(x + width));
772 let top = (y.min(y + height)).max(0.0);
774 let bottom = f64::min(window.InnerHeight() as f64, y.max(y + height));
777 debug!(
778 "get_element_in_view_center_point: Computed rectangle is \
779 (left: {left}, right: {right}, top: {top}, bottom: {bottom})",
780 );
781 let center_x = ((left + right) / 2.0).floor() as i64;
783 let center_y = ((top + bottom) / 2.0).floor() as i64;
785
786 debug!(
787 "get_element_in_view_center_point: Element center point at ({center_x}, {center_y})",
788 );
789 Point2D::new(center_x, center_y)
791 })
792}
793
794pub(crate) fn handle_get_element_in_view_center_point(
795 cx: &mut JSContext,
796 documents: &DocumentCollection,
797 pipeline: PipelineId,
798 element_id: String,
799 reply: GenericOneshotSender<Result<Option<(i64, i64)>, ErrorStatus>>,
800) {
801 reply
802 .send(
803 get_known_element(documents, pipeline, element_id).map(|element| {
804 get_element_in_view_center_point(cx, &element).map(|point| (point.x, point.y))
805 }),
806 )
807 .unwrap();
808}
809
810fn retrieve_document_and_check_root_existence(
811 documents: &DocumentCollection,
812 pipeline: PipelineId,
813) -> Result<DomRoot<Document>, ErrorStatus> {
814 let document = documents
815 .find_document(pipeline)
816 .ok_or(ErrorStatus::NoSuchWindow)?;
817
818 if document.GetDocumentElement().is_none() {
823 Err(ErrorStatus::NoSuchElement)
824 } else {
825 Ok(document)
826 }
827}
828
829pub(crate) fn handle_find_elements_css_selector(
830 cx: &mut JSContext,
831 documents: &DocumentCollection,
832 pipeline: PipelineId,
833 selector: String,
834 reply: GenericSender<Result<Vec<String>, ErrorStatus>>,
835) {
836 match retrieve_document_and_check_root_existence(documents, pipeline) {
837 Ok(document) => reply
838 .send(
839 document
840 .QuerySelectorAll(cx, DOMString::from(selector))
841 .map_err(|_| ErrorStatus::InvalidSelector)
842 .map(|nodes| {
843 nodes
844 .iter(cx)
845 .map(|x| x.upcast::<Node>().unique_id(pipeline))
846 .collect()
847 }),
848 )
849 .unwrap(),
850 Err(error) => reply.send(Err(error)).unwrap(),
851 }
852}
853
854pub(crate) fn handle_find_elements_link_text(
855 cx: &mut JSContext,
856 documents: &DocumentCollection,
857 pipeline: PipelineId,
858 selector: String,
859 partial: bool,
860 reply: GenericSender<Result<Vec<String>, ErrorStatus>>,
861) {
862 match retrieve_document_and_check_root_existence(documents, pipeline) {
863 Ok(document) => reply
864 .send(all_matching_links(
865 cx,
866 document.upcast::<Node>(),
867 selector,
868 partial,
869 ))
870 .unwrap(),
871 Err(error) => reply.send(Err(error)).unwrap(),
872 }
873}
874
875pub(crate) fn handle_find_elements_tag_name(
876 cx: &mut JSContext,
877 documents: &DocumentCollection,
878 pipeline: PipelineId,
879 selector: String,
880 reply: GenericSender<Result<Vec<String>, ErrorStatus>>,
881) {
882 match retrieve_document_and_check_root_existence(documents, pipeline) {
883 Ok(document) => reply
884 .send(Ok(document
885 .GetElementsByTagName(cx, DOMString::from(selector))
886 .elements_iter(cx.no_gc())
887 .map(|x| x.upcast::<Node>().unique_id(pipeline))
888 .collect::<Vec<String>>()))
889 .unwrap(),
890 Err(error) => reply.send(Err(error)).unwrap(),
891 }
892}
893
894fn find_elements_xpath_strategy(
896 cx: &mut JSContext,
897 document: &Document,
898 start_node: &Node,
899 selector: String,
900 pipeline: PipelineId,
901) -> Result<Vec<String>, ErrorStatus> {
902 let evaluate_result = match document.Evaluate(
907 cx,
908 DOMString::from(selector),
909 start_node,
910 None,
911 XPathResultConstants::ORDERED_NODE_SNAPSHOT_TYPE,
912 None,
913 ) {
914 Ok(res) => res,
915 Err(_) => return Err(ErrorStatus::InvalidSelector),
916 };
917 let length = match evaluate_result.GetSnapshotLength() {
923 Ok(len) => len,
924 Err(_) => return Err(ErrorStatus::InvalidSelector),
925 };
926
927 let mut result = Vec::new();
929
930 for index in 0..length {
932 let node = match evaluate_result.SnapshotItem(index) {
935 Ok(node) => node.expect(
936 "Node should always exist as ORDERED_NODE_SNAPSHOT_TYPE \
937 gives static result and we verified the length!",
938 ),
939 Err(_) => return Err(ErrorStatus::InvalidSelector),
940 };
941
942 if !node.is::<Element>() {
944 return Err(ErrorStatus::InvalidSelector);
945 }
946
947 result.push(node.unique_id(pipeline));
949 }
950 Ok(result)
952}
953
954pub(crate) fn handle_find_elements_xpath_selector(
955 cx: &mut JSContext,
956 documents: &DocumentCollection,
957 pipeline: PipelineId,
958 selector: String,
959 reply: GenericSender<Result<Vec<String>, ErrorStatus>>,
960) {
961 match retrieve_document_and_check_root_existence(documents, pipeline) {
962 Ok(document) => reply
963 .send(find_elements_xpath_strategy(
964 cx,
965 &document,
966 document.upcast::<Node>(),
967 selector,
968 pipeline,
969 ))
970 .unwrap(),
971 Err(error) => reply.send(Err(error)).unwrap(),
972 }
973}
974
975pub(crate) fn handle_find_element_elements_css_selector(
976 cx: &mut JSContext,
977 documents: &DocumentCollection,
978 pipeline: PipelineId,
979 element_id: String,
980 selector: String,
981 reply: GenericSender<Result<Vec<String>, ErrorStatus>>,
982) {
983 reply
984 .send(
985 get_known_element(documents, pipeline, element_id).and_then(|element| {
986 element
987 .upcast::<Node>()
988 .query_selector_all(cx, DOMString::from(selector))
989 .map_err(|_| ErrorStatus::InvalidSelector)
990 .map(|nodes| {
991 nodes
992 .iter(cx)
993 .map(|x| x.upcast::<Node>().unique_id(pipeline))
994 .collect()
995 })
996 }),
997 )
998 .unwrap();
999}
1000
1001pub(crate) fn handle_find_element_elements_link_text(
1002 cx: &mut JSContext,
1003 documents: &DocumentCollection,
1004 pipeline: PipelineId,
1005 element_id: String,
1006 selector: String,
1007 partial: bool,
1008 reply: GenericSender<Result<Vec<String>, ErrorStatus>>,
1009) {
1010 reply
1011 .send(
1012 get_known_element(documents, pipeline, element_id).and_then(|element| {
1013 all_matching_links(cx, element.upcast::<Node>(), selector.clone(), partial)
1014 }),
1015 )
1016 .unwrap();
1017}
1018
1019pub(crate) fn handle_find_element_elements_tag_name(
1020 cx: &mut JSContext,
1021 documents: &DocumentCollection,
1022 pipeline: PipelineId,
1023 element_id: String,
1024 selector: String,
1025 reply: GenericSender<Result<Vec<String>, ErrorStatus>>,
1026) {
1027 reply
1028 .send(
1029 get_known_element(documents, pipeline, element_id).map(|element| {
1030 element
1031 .GetElementsByTagName(cx, DOMString::from(selector))
1032 .elements_iter(cx.no_gc())
1033 .map(|x| x.upcast::<Node>().unique_id(pipeline))
1034 .collect::<Vec<String>>()
1035 }),
1036 )
1037 .unwrap();
1038}
1039
1040pub(crate) fn handle_find_element_elements_xpath_selector(
1041 cx: &mut JSContext,
1042 documents: &DocumentCollection,
1043 pipeline: PipelineId,
1044 element_id: String,
1045 selector: String,
1046 reply: GenericSender<Result<Vec<String>, ErrorStatus>>,
1047) {
1048 reply
1049 .send(
1050 get_known_element(documents, pipeline, element_id).and_then(|element| {
1051 find_elements_xpath_strategy(
1052 cx,
1053 &documents
1054 .find_document(pipeline)
1055 .expect("Document existence guaranteed by `get_known_element`"),
1056 element.upcast::<Node>(),
1057 selector,
1058 pipeline,
1059 )
1060 }),
1061 )
1062 .unwrap();
1063}
1064
1065pub(crate) fn handle_find_shadow_elements_css_selector(
1067 cx: &mut JSContext,
1068 documents: &DocumentCollection,
1069 pipeline: PipelineId,
1070 shadow_root_id: String,
1071 selector: String,
1072 reply: GenericSender<Result<Vec<String>, ErrorStatus>>,
1073) {
1074 reply
1075 .send(
1076 get_known_shadow_root(documents, pipeline, shadow_root_id).and_then(|shadow_root| {
1077 shadow_root
1078 .upcast::<Node>()
1079 .query_selector_all(cx, DOMString::from(selector))
1080 .map_err(|_| ErrorStatus::InvalidSelector)
1081 .map(|nodes| {
1082 nodes
1083 .iter(cx)
1084 .map(|x| x.upcast::<Node>().unique_id(pipeline))
1085 .collect()
1086 })
1087 }),
1088 )
1089 .unwrap();
1090}
1091
1092pub(crate) fn handle_find_shadow_elements_link_text(
1093 cx: &mut JSContext,
1094 documents: &DocumentCollection,
1095 pipeline: PipelineId,
1096 shadow_root_id: String,
1097 selector: String,
1098 partial: bool,
1099 reply: GenericSender<Result<Vec<String>, ErrorStatus>>,
1100) {
1101 reply
1102 .send(
1103 get_known_shadow_root(documents, pipeline, shadow_root_id).and_then(|shadow_root| {
1104 all_matching_links(cx, shadow_root.upcast::<Node>(), selector.clone(), partial)
1105 }),
1106 )
1107 .unwrap();
1108}
1109
1110pub(crate) fn handle_find_shadow_elements_tag_name(
1111 cx: &mut JSContext,
1112 documents: &DocumentCollection,
1113 pipeline: PipelineId,
1114 shadow_root_id: String,
1115 selector: String,
1116 reply: GenericSender<Result<Vec<String>, ErrorStatus>>,
1117) {
1118 reply
1124 .send(
1125 get_known_shadow_root(documents, pipeline, shadow_root_id).map(|shadow_root| {
1126 shadow_root
1127 .upcast::<Node>()
1128 .query_selector_all(cx, DOMString::from(selector))
1129 .map(|nodes| {
1130 nodes
1131 .iter(cx)
1132 .map(|x| x.upcast::<Node>().unique_id(pipeline))
1133 .collect()
1134 })
1135 .unwrap_or_default()
1136 }),
1137 )
1138 .unwrap();
1139}
1140
1141pub(crate) fn handle_find_shadow_elements_xpath_selector(
1142 cx: &mut JSContext,
1143 documents: &DocumentCollection,
1144 pipeline: PipelineId,
1145 shadow_root_id: String,
1146 selector: String,
1147 reply: GenericSender<Result<Vec<String>, ErrorStatus>>,
1148) {
1149 reply
1150 .send(
1151 get_known_shadow_root(documents, pipeline, shadow_root_id).and_then(|shadow_root| {
1152 find_elements_xpath_strategy(
1153 cx,
1154 &documents
1155 .find_document(pipeline)
1156 .expect("Document existence guaranteed by `get_known_shadow_root`"),
1157 shadow_root.upcast::<Node>(),
1158 selector,
1159 pipeline,
1160 )
1161 }),
1162 )
1163 .unwrap();
1164}
1165
1166pub(crate) fn handle_get_element_shadow_root(
1168 documents: &DocumentCollection,
1169 pipeline: PipelineId,
1170 element_id: String,
1171 reply: GenericSender<Result<Option<String>, ErrorStatus>>,
1172) {
1173 reply
1174 .send(
1175 get_known_element(documents, pipeline, element_id).map(|element| {
1176 element
1177 .shadow_root()
1178 .map(|x| x.upcast::<Node>().unique_id(pipeline))
1179 }),
1180 )
1181 .unwrap();
1182}
1183
1184impl Element {
1185 fn is_keyboard_interactable(&self, cx: &mut JSContext) -> bool {
1187 self.is_focusable_area(cx) || self.is::<HTMLBodyElement>() || self.is_document_element()
1188 }
1189}
1190
1191fn handle_send_keys_file(
1192 cx: &mut JSContext,
1193 file_input: &HTMLInputElement,
1194 text: &str,
1195 reply_sender: GenericSender<Result<bool, ErrorStatus>>,
1196) {
1197 let files: Vec<DOMString> = text
1202 .split("\n")
1203 .filter_map(|string| {
1204 if string.is_empty() {
1205 None
1206 } else {
1207 Some(string.into())
1208 }
1209 })
1210 .collect();
1211
1212 if files.is_empty() {
1214 let _ = reply_sender.send(Err(ErrorStatus::InvalidArgument));
1215 return;
1216 }
1217
1218 if !file_input.Multiple() && files.len() > 1 {
1222 let _ = reply_sender.send(Err(ErrorStatus::InvalidArgument));
1223 return;
1224 }
1225
1226 file_input.select_files_for_webdriver(cx, files, reply_sender);
1235}
1236
1237fn handle_send_keys_non_typeable(
1239 cx: &mut JSContext,
1240 input_element: &HTMLInputElement,
1241 text: &str,
1242) -> Result<bool, ErrorStatus> {
1243 if !input_element.is_mutable() {
1250 return Err(ErrorStatus::ElementNotInteractable);
1251 }
1252
1253 if let Err(error) = input_element.SetValue(cx, text.into()) {
1255 error!(
1256 "Failed to set value on non-typeable input element: {:?}",
1257 error
1258 );
1259 return Err(ErrorStatus::UnknownError);
1260 }
1261
1262 if input_element
1264 .Validity(cx)
1265 .invalid_flags()
1266 .contains(ValidationFlags::BAD_INPUT)
1267 {
1268 return Err(ErrorStatus::InvalidArgument);
1269 }
1270
1271 Ok(false)
1274}
1275
1276pub(crate) fn handle_will_send_keys(
1282 cx: &mut JSContext,
1283 documents: &DocumentCollection,
1284 pipeline: PipelineId,
1285 element_id: String,
1286 text: String,
1287 strict_file_interactability: bool,
1288 reply: GenericSender<Result<bool, ErrorStatus>>,
1289) {
1290 let element = match get_known_element(documents, pipeline, element_id) {
1292 Ok(element) => element,
1293 Err(error) => {
1294 let _ = reply.send(Err(error));
1295 return;
1296 },
1297 };
1298
1299 let input_element = element.downcast::<HTMLInputElement>();
1300 let mut element_has_focus = false;
1301
1302 let is_file_input =
1305 input_element.is_some_and(|e| matches!(*e.input_type(), InputType::File(_)));
1306
1307 if !is_file_input || strict_file_interactability {
1309 scroll_into_view(cx, &element);
1311
1312 if !element.is_keyboard_interactable(cx) {
1318 let _ = reply.send(Err(ErrorStatus::ElementNotInteractable));
1319 return;
1320 }
1321
1322 let Some(html_element) = element.downcast::<HTMLElement>() else {
1325 let _ = reply.send(Err(ErrorStatus::UnknownError));
1326 return;
1327 };
1328
1329 if !element.is_active_element() {
1330 html_element.Focus(
1331 cx,
1332 &FocusOptions {
1333 preventScroll: true,
1334 },
1335 );
1336 } else {
1337 element_has_focus = element.focus_state();
1338 }
1339 }
1340
1341 if let Some(input_element) = input_element {
1342 if is_file_input {
1344 handle_send_keys_file(cx, input_element, &text, reply);
1345 return;
1346 }
1347
1348 if input_element.is_nontypeable() {
1350 let _ = reply.send(handle_send_keys_non_typeable(cx, input_element, &text));
1351 return;
1352 }
1353 }
1354
1355 if !element_has_focus {
1363 if let Some(input_element) = input_element {
1364 let length = input_element.Value().len_utf16().0;
1365 let _ = input_element.SetSelectionRange(length, length, None);
1366 } else if let Some(textarea_element) = element.downcast::<HTMLTextAreaElement>() {
1367 let length = textarea_element.Value().len_utf16().0;
1368 let _ = textarea_element.SetSelectionRange(length, length, None);
1369 }
1370 }
1371
1372 let _ = reply.send(Ok(true));
1373}
1374
1375pub(crate) fn handle_get_active_element(
1376 documents: &DocumentCollection,
1377 pipeline: PipelineId,
1378 reply: GenericSender<Option<String>>,
1379) {
1380 reply
1381 .send(
1382 documents
1383 .find_document(pipeline)
1384 .and_then(|document| document.GetActiveElement())
1385 .map(|element| element.upcast::<Node>().unique_id(pipeline)),
1386 )
1387 .unwrap();
1388}
1389
1390pub(crate) fn handle_get_computed_role(
1391 cx: &mut JSContext,
1392 documents: &DocumentCollection,
1393 pipeline: PipelineId,
1394 node_id: String,
1395 reply: GenericSender<Result<Option<String>, ErrorStatus>>,
1396) {
1397 if !pref!(accessibility_enabled) {
1398 return reply.send(Err(ErrorStatus::UnsupportedOperation)).unwrap();
1399 }
1400 reply
1401 .send(
1402 get_known_element(documents, pipeline, node_id).map(|element| {
1403 let document = element.upcast::<Node>().owner_doc();
1404 let window = document.window();
1405 window
1406 .layout()
1407 .set_accessibility_active(true, Epoch::default());
1408 element.get_computed_role(cx).map(String::from)
1409 }),
1410 )
1411 .unwrap();
1412}
1413
1414pub(crate) fn handle_get_page_source(
1415 cx: &mut JSContext,
1416 documents: &DocumentCollection,
1417 pipeline: PipelineId,
1418 reply: GenericSender<Result<String, ErrorStatus>>,
1419) {
1420 reply
1421 .send(
1422 documents
1423 .find_document(pipeline)
1424 .ok_or(ErrorStatus::UnknownError)
1425 .and_then(|document| match document.GetDocumentElement() {
1426 Some(element) => match element.outer_html(cx) {
1427 Ok(source) => Ok(String::from(source)),
1428 Err(_) => {
1429 match XMLSerializer::new(cx, document.window(), None)
1430 .SerializeToString(element.upcast::<Node>())
1431 {
1432 Ok(source) => Ok(String::from(source)),
1433 Err(_) => Err(ErrorStatus::UnknownError),
1434 }
1435 },
1436 },
1437 None => Err(ErrorStatus::UnknownError),
1438 }),
1439 )
1440 .unwrap();
1441}
1442
1443pub(crate) fn handle_get_cookies(
1444 documents: &DocumentCollection,
1445 pipeline: PipelineId,
1446 reply: GenericSender<Result<Vec<Serde<Cookie<'static>>>, ErrorStatus>>,
1447) {
1448 reply
1449 .send(
1450 match documents.find_document(pipeline) {
1452 Some(document) => {
1453 let url = document.url();
1454 let (sender, receiver) = generic_channel::channel().unwrap();
1455 let _ = document
1456 .window()
1457 .as_global_scope()
1458 .resource_threads()
1459 .send(GetCookiesForUrl(url, sender, NonHTTP));
1460 Ok(receiver.recv().unwrap())
1461 },
1462 None => Ok(Vec::new()),
1463 },
1464 )
1465 .unwrap();
1466}
1467
1468pub(crate) fn handle_get_cookie(
1470 documents: &DocumentCollection,
1471 pipeline: PipelineId,
1472 name: String,
1473 reply: GenericSender<Result<Vec<Serde<Cookie<'static>>>, ErrorStatus>>,
1474) {
1475 reply
1476 .send(
1477 match documents.find_document(pipeline) {
1479 Some(document) => {
1480 let url = document.url();
1481 let (sender, receiver) = generic_channel::channel().unwrap();
1482 let _ = document
1483 .window()
1484 .as_global_scope()
1485 .resource_threads()
1486 .send(GetCookiesForUrl(url, sender, NonHTTP));
1487 let cookies = receiver.recv().unwrap();
1488 Ok(cookies
1489 .into_iter()
1490 .filter(|cookie| cookie.name() == &*name)
1491 .collect())
1492 },
1493 None => Ok(Vec::new()),
1494 },
1495 )
1496 .unwrap();
1497}
1498
1499pub(crate) fn handle_add_cookie(
1501 documents: &DocumentCollection,
1502 pipeline: PipelineId,
1503 cookie: Cookie<'static>,
1504 reply: GenericSender<Result<(), ErrorStatus>>,
1505) {
1506 let document = match documents.find_document(pipeline) {
1508 Some(document) => document,
1509 None => {
1510 return reply.send(Err(ErrorStatus::NoSuchWindow)).unwrap();
1511 },
1512 };
1513 let url = document.url();
1514 let method = if cookie.http_only().unwrap_or(false) {
1515 HTTP
1516 } else {
1517 NonHTTP
1518 };
1519
1520 let domain = cookie.domain().map(ToOwned::to_owned);
1521 reply
1523 .send(match (document.is_cookie_averse(), domain) {
1524 (true, _) => Err(ErrorStatus::InvalidCookieDomain),
1527 (false, Some(ref domain)) if url.host_str().is_some_and(|host| host == domain) => {
1528 let _ = document
1529 .window()
1530 .as_global_scope()
1531 .resource_threads()
1532 .send(SetCookieForUrl(url, Serde(cookie), method, None));
1533 Ok(())
1534 },
1535 (false, Some(_)) => Err(ErrorStatus::InvalidCookieDomain),
1538 (false, None) => {
1539 let _ = document
1540 .window()
1541 .as_global_scope()
1542 .resource_threads()
1543 .send(SetCookieForUrl(url, Serde(cookie), method, None));
1544 Ok(())
1545 },
1546 })
1547 .unwrap();
1548}
1549
1550pub(crate) fn handle_delete_cookies(
1552 documents: &DocumentCollection,
1553 pipeline: PipelineId,
1554 reply: GenericSender<Result<(), ErrorStatus>>,
1555) {
1556 let document = match documents.find_document(pipeline) {
1557 Some(document) => document,
1558 None => {
1559 return reply.send(Err(ErrorStatus::UnknownError)).unwrap();
1560 },
1561 };
1562 let url = document.url();
1563 document
1564 .window()
1565 .as_global_scope()
1566 .resource_threads()
1567 .send(DeleteCookies(Some(url), None))
1568 .unwrap();
1569 reply.send(Ok(())).unwrap();
1570}
1571
1572pub(crate) fn handle_delete_cookie(
1574 documents: &DocumentCollection,
1575 pipeline: PipelineId,
1576 name: String,
1577 reply: GenericSender<Result<(), ErrorStatus>>,
1578) {
1579 let document = match documents.find_document(pipeline) {
1580 Some(document) => document,
1581 None => {
1582 return reply.send(Err(ErrorStatus::UnknownError)).unwrap();
1583 },
1584 };
1585 let url = document.url();
1586 document
1587 .window()
1588 .as_global_scope()
1589 .resource_threads()
1590 .send(DeleteCookie(url, name))
1591 .unwrap();
1592 reply.send(Ok(())).unwrap();
1593}
1594
1595pub(crate) fn handle_get_title(
1596 documents: &DocumentCollection,
1597 pipeline: PipelineId,
1598 reply: GenericSender<String>,
1599) {
1600 reply
1601 .send(
1602 documents
1604 .find_document(pipeline)
1605 .map(|document| String::from(document.Title()))
1606 .unwrap_or_default(),
1607 )
1608 .unwrap();
1609}
1610
1611fn calculate_absolute_position(
1613 cx: &mut JSContext,
1614 documents: &DocumentCollection,
1615 pipeline: &PipelineId,
1616 rect: &DOMRect,
1617) -> Result<(f64, f64), ErrorStatus> {
1618 let document = match documents.find_document(*pipeline) {
1623 Some(document) => document,
1624 None => return Err(ErrorStatus::UnknownError),
1625 };
1626 let win = match document.GetDefaultView() {
1627 Some(win) => win,
1628 None => return Err(ErrorStatus::UnknownError),
1629 };
1630
1631 let x = win.ScrollX(cx) as f64 + rect.X();
1633 let y = win.ScrollY(cx) as f64 + rect.Y();
1634
1635 Ok((x, y))
1636}
1637
1638pub(crate) fn handle_get_rect(
1640 cx: &mut JSContext,
1641 documents: &DocumentCollection,
1642 pipeline: PipelineId,
1643 element_id: String,
1644 reply: GenericSender<Result<Rect<f64>, ErrorStatus>>,
1645) {
1646 reply
1647 .send(
1648 get_known_element(documents, pipeline, element_id).and_then(|element| {
1649 let rect = element.GetBoundingClientRect(cx);
1653 let (x, y) = calculate_absolute_position(cx, documents, &pipeline, &rect)?;
1654
1655 Ok(Rect::new(
1657 Point2D::new(x, y),
1658 Size2D::new(rect.Width(), rect.Height()),
1659 ))
1660 }),
1661 )
1662 .unwrap();
1663}
1664
1665pub(crate) fn handle_scroll_and_get_bounding_client_rect(
1666 cx: &mut JSContext,
1667 documents: &DocumentCollection,
1668 pipeline: PipelineId,
1669 element_id: String,
1670 reply: GenericSender<Result<Rect<f32>, ErrorStatus>>,
1671) {
1672 reply
1673 .send(
1674 get_known_element(documents, pipeline, element_id).map(|element| {
1675 scroll_into_view(cx, &element);
1676
1677 let rect = element.GetBoundingClientRect(cx);
1678 Rect::new(
1679 Point2D::new(rect.X() as f32, rect.Y() as f32),
1680 Size2D::new(rect.Width() as f32, rect.Height() as f32),
1681 )
1682 }),
1683 )
1684 .unwrap();
1685}
1686
1687pub(crate) fn handle_get_text(
1689 cx: &mut JSContext,
1690 documents: &DocumentCollection,
1691 pipeline: PipelineId,
1692 node_id: String,
1693 reply: GenericSender<Result<String, ErrorStatus>>,
1694) {
1695 reply
1696 .send(
1697 get_known_element(documents, pipeline, node_id).map(|element| {
1698 element
1699 .downcast::<HTMLElement>()
1700 .map(|htmlelement| String::from(htmlelement.InnerText(cx)))
1701 .unwrap_or_else(|| {
1702 element
1703 .upcast::<Node>()
1704 .GetTextContent()
1705 .map_or(String::new(), String::from)
1706 })
1707 }),
1708 )
1709 .unwrap();
1710}
1711
1712pub(crate) fn handle_get_name(
1714 documents: &DocumentCollection,
1715 pipeline: PipelineId,
1716 node_id: String,
1717 reply: GenericSender<Result<String, ErrorStatus>>,
1718) {
1719 reply
1720 .send(
1721 get_known_element(documents, pipeline, node_id)
1722 .map(|element| element.qualified_name().into_owned()),
1723 )
1724 .unwrap();
1725}
1726
1727pub(crate) fn handle_get_attribute(
1728 cx: &mut JSContext,
1729 documents: &DocumentCollection,
1730 pipeline: PipelineId,
1731 node_id: String,
1732 name: String,
1733 reply: GenericSender<Result<Option<String>, ErrorStatus>>,
1734) {
1735 reply
1736 .send(
1737 get_known_element(documents, pipeline, node_id).map(|element| {
1738 if is_boolean_attribute(&name) {
1739 if element.HasAttribute(cx, DOMString::from(name)) {
1740 Some(String::from("true"))
1741 } else {
1742 None
1743 }
1744 } else {
1745 element
1746 .GetAttribute(cx, DOMString::from(name))
1747 .map(String::from)
1748 }
1749 }),
1750 )
1751 .unwrap();
1752}
1753
1754pub(crate) fn handle_get_property(
1755 cx: &mut JSContext,
1756 documents: &DocumentCollection,
1757 pipeline: PipelineId,
1758 node_id: String,
1759 name: String,
1760 reply: GenericSender<Result<JSValue, ErrorStatus>>,
1761) {
1762 reply
1763 .send(
1764 get_known_element(documents, pipeline, node_id).map(|element| {
1765 let document = documents.find_document(pipeline).unwrap();
1766
1767 let Ok(cname) = CString::new(name) else {
1768 return JSValue::Undefined;
1769 };
1770
1771 let mut realm = enter_auto_realm(cx, &*document);
1772 let cx = &mut realm.current_realm();
1773
1774 rooted!(&in(cx) let mut property = UndefinedValue());
1775 match get_property_jsval(
1776 cx,
1777 element.reflector().get_jsobject(),
1778 &cname,
1779 property.handle_mut(),
1780 ) {
1781 Ok(_) => match jsval_to_webdriver(cx, &element.global(), property.handle()) {
1782 Ok(property) => property,
1783 Err(_) => JSValue::Undefined,
1784 },
1785 Err(error) => {
1786 throw_dom_exception(cx, &element.global(), error);
1787 JSValue::Undefined
1788 },
1789 }
1790 }),
1791 )
1792 .unwrap();
1793}
1794
1795pub(crate) fn handle_get_css(
1796 cx: &mut JSContext,
1797 documents: &DocumentCollection,
1798 pipeline: PipelineId,
1799 node_id: String,
1800 name: String,
1801 reply: GenericSender<Result<String, ErrorStatus>>,
1802) {
1803 reply
1804 .send(
1805 get_known_element(documents, pipeline, node_id).map(|element| {
1806 let window = element.owner_window();
1807 String::from(
1808 window
1809 .GetComputedStyle(cx, &element, None)
1810 .GetPropertyValue(DOMString::from(name)),
1811 )
1812 }),
1813 )
1814 .unwrap();
1815}
1816
1817pub(crate) fn handle_get_url(
1818 documents: &DocumentCollection,
1819 pipeline: PipelineId,
1820 reply: GenericSender<String>,
1821) {
1822 reply
1823 .send(
1824 documents
1826 .find_document(pipeline)
1827 .map(|document| document.url().into_string())
1828 .unwrap_or_else(|| "about:blank".to_string()),
1829 )
1830 .unwrap();
1831}
1832
1833fn element_is_mutable_form_control(element: &Element) -> bool {
1835 if let Some(input_element) = element.downcast::<HTMLInputElement>() {
1836 input_element.is_mutable() &&
1837 matches!(
1838 *input_element.input_type(),
1839 InputType::Text(_) |
1840 InputType::Search(_) |
1841 InputType::Url(_) |
1842 InputType::Tel(_) |
1843 InputType::Email(_) |
1844 InputType::Password(_) |
1845 InputType::Date(_) |
1846 InputType::Month(_) |
1847 InputType::Week(_) |
1848 InputType::Time(_) |
1849 InputType::DatetimeLocal(_) |
1850 InputType::Number(_) |
1851 InputType::Range(_) |
1852 InputType::Color(_) |
1853 InputType::File(_)
1854 )
1855 } else if let Some(textarea_element) = element.downcast::<HTMLTextAreaElement>() {
1856 textarea_element.is_mutable()
1857 } else {
1858 false
1859 }
1860}
1861
1862fn clear_a_resettable_element(cx: &mut JSContext, element: &Element) -> Result<(), ErrorStatus> {
1864 let html_element = element
1865 .downcast::<HTMLElement>()
1866 .ok_or(ErrorStatus::UnknownError)?;
1867
1868 if html_element.is_candidate_for_constraint_validation(cx.no_gc()) {
1871 if let Some(input_element) = element.downcast::<HTMLInputElement>() {
1872 if input_element.Value().is_empty() {
1873 return Ok(());
1874 }
1875 } else if let Some(textarea_element) = element.downcast::<HTMLTextAreaElement>() &&
1876 textarea_element.Value().is_empty()
1877 {
1878 return Ok(());
1879 }
1880 }
1881
1882 html_element.Focus(
1884 cx,
1885 &FocusOptions {
1886 preventScroll: true,
1887 },
1888 );
1889
1890 if let Some(input_element) = element.downcast::<HTMLInputElement>() {
1892 input_element.clear(cx);
1893 } else if let Some(textarea_element) = element.downcast::<HTMLTextAreaElement>() {
1894 textarea_element.clear();
1895 } else {
1896 unreachable!("We have confirm previously that element is mutable form control");
1897 }
1898
1899 let event_target = element.upcast::<EventTarget>();
1900 event_target.fire_bubbling_event(cx, atom!("input"));
1901 event_target.fire_bubbling_event(cx, atom!("change"));
1902
1903 html_element.Blur(cx);
1905
1906 Ok(())
1907}
1908
1909pub(crate) fn handle_element_clear(
1911 cx: &mut JSContext,
1912 documents: &DocumentCollection,
1913 pipeline: PipelineId,
1914 element_id: String,
1915 reply: GenericSender<Result<(), ErrorStatus>>,
1916) {
1917 reply
1918 .send(
1919 get_known_element(documents, pipeline, element_id).and_then(|element| {
1920 if !element_is_mutable_form_control(&element) {
1924 return Err(ErrorStatus::InvalidElementState);
1925 }
1926
1927 scroll_into_view(cx, &element);
1929
1930 if !element.is_keyboard_interactable(cx) {
1936 return Err(ErrorStatus::ElementNotInteractable);
1937 }
1938
1939 let paint_tree = get_element_pointer_interactable_paint_tree(cx, &element);
1940 if !is_element_in_view(cx, &element, &paint_tree) {
1941 return Err(ErrorStatus::ElementNotInteractable);
1942 }
1943
1944 clear_a_resettable_element(cx, &element)
1947 }),
1948 )
1949 .unwrap();
1950}
1951
1952fn get_option_parent(node: &Node) -> Option<DomRoot<Element>> {
1953 let mut candidate_select = None;
1961
1962 for ancestor in node.ancestors() {
1963 if ancestor.is::<HTMLDataListElement>() {
1964 return Some(DomRoot::downcast::<Element>(ancestor).unwrap());
1965 } else if candidate_select.is_none() && ancestor.is::<HTMLSelectElement>() {
1966 candidate_select = Some(ancestor);
1967 }
1968 }
1969
1970 candidate_select.map(|ancestor| DomRoot::downcast::<Element>(ancestor).unwrap())
1971}
1972
1973fn get_container(element: &Element) -> Option<DomRoot<Element>> {
1975 if element.is::<HTMLOptionElement>() {
1976 return get_option_parent(element.upcast::<Node>());
1977 }
1978 if element.is::<HTMLOptGroupElement>() {
1979 return get_option_parent(element.upcast::<Node>())
1980 .or_else(|| Some(DomRoot::from_ref(element)));
1981 }
1982 Some(DomRoot::from_ref(element))
1983}
1984
1985pub(crate) fn handle_element_click(
1987 cx: &mut JSContext,
1988 documents: &DocumentCollection,
1989 pipeline: PipelineId,
1990 element_id: String,
1991 reply: GenericSender<Result<Option<String>, ErrorStatus>>,
1992) {
1993 reply
1994 .send(
1995 get_known_element(documents, pipeline, element_id).and_then(|element| {
1997 if let Some(input_element) = element.downcast::<HTMLInputElement>() &&
2000 matches!(*input_element.input_type(), InputType::File(_))
2001 {
2002 return Err(ErrorStatus::InvalidArgument);
2003 }
2004
2005 let Some(container) = get_container(&element) else {
2006 return Err(ErrorStatus::UnknownError);
2007 };
2008
2009 scroll_into_view(cx, &container);
2011
2012 let paint_tree = get_element_pointer_interactable_paint_tree(cx, &container);
2015
2016 if !is_element_in_view(cx, &container, &paint_tree) {
2017 return Err(ErrorStatus::ElementNotInteractable);
2018 }
2019
2020 if !container
2027 .upcast::<Node>()
2028 .is_shadow_including_inclusive_ancestor_of(paint_tree[0].upcast::<Node>())
2029 {
2030 return Err(ErrorStatus::ElementClickIntercepted);
2031 }
2032
2033 match element.downcast::<HTMLOptionElement>() {
2035 Some(option_element) => {
2036 let event_target = container.upcast::<EventTarget>();
2038 event_target.fire_event(cx, atom!("mouseover"));
2039 event_target.fire_event(cx, atom!("mousemove"));
2040 event_target.fire_event(cx, atom!("mousedown"));
2041
2042 match container.downcast::<HTMLElement>() {
2044 Some(html_element) => {
2045 html_element.Focus(
2046 cx,
2047 &FocusOptions {
2048 preventScroll: true,
2049 },
2050 );
2051 },
2052 None => return Err(ErrorStatus::UnknownError),
2053 }
2054
2055 if !is_disabled(&element) {
2057 event_target.fire_event(cx, atom!("input"));
2059
2060 let previous_selectedness = option_element.Selected();
2062
2063 match container.downcast::<HTMLSelectElement>() {
2065 Some(select_element) => {
2066 if select_element.Multiple() {
2067 option_element.SetSelected(cx, !option_element.Selected());
2068 }
2069 },
2070 None => option_element.SetSelected(cx, true),
2071 }
2072
2073 if !previous_selectedness {
2075 event_target.fire_event(cx, atom!("change"));
2076 }
2077 }
2078
2079 event_target.fire_event(cx, atom!("mouseup"));
2081 event_target.fire_event(cx, atom!("click"));
2082
2083 Ok(None)
2084 },
2085 None => Ok(Some(element.upcast::<Node>().unique_id(pipeline))),
2086 }
2087 }),
2088 )
2089 .unwrap();
2090}
2091
2092fn is_element_in_view(
2094 cx: &mut JSContext,
2095 element: &Element,
2096 paint_tree: &[DomRoot<Element>],
2097) -> bool {
2098 if !paint_tree.iter().any(|e| &**e == element) {
2101 return false;
2102 }
2103 use style::computed_values::pointer_events::T as PointerEvents;
2104 element
2108 .style(cx)
2109 .is_none_or(|style| style.get_inherited_ui().pointer_events != PointerEvents::None)
2110}
2111
2112fn get_element_pointer_interactable_paint_tree(
2114 cx: &mut JSContext,
2115 element: &Element,
2116) -> Vec<DomRoot<Element>> {
2117 if !element.is_connected() {
2120 return Vec::new();
2121 }
2122
2123 get_element_in_view_center_point(cx, element).map_or(Vec::new(), |center_point| {
2129 if let Some(shadow_root) = element.containing_shadow_root() {
2130 shadow_root.ElementsFromPoint(
2131 cx,
2132 Finite::wrap(center_point.x as f64),
2133 Finite::wrap(center_point.y as f64),
2134 )
2135 } else {
2136 element.owner_document().ElementsFromPoint(
2137 cx,
2138 Finite::wrap(center_point.x as f64),
2139 Finite::wrap(center_point.y as f64),
2140 )
2141 }
2142 })
2143}
2144
2145pub(crate) fn handle_is_enabled(
2147 documents: &DocumentCollection,
2148 pipeline: PipelineId,
2149 element_id: String,
2150 reply: GenericSender<Result<bool, ErrorStatus>>,
2151) {
2152 reply
2153 .send(
2154 get_known_element(documents, pipeline, element_id).map(|element| {
2156 let document = documents.find_document(pipeline).unwrap();
2158
2159 if document.is_html_document() || document.is_xhtml_document() {
2165 !is_disabled(&element)
2166 } else {
2167 false
2168 }
2169 }),
2170 )
2171 .unwrap();
2172}
2173
2174pub(crate) fn handle_is_selected(
2175 documents: &DocumentCollection,
2176 pipeline: PipelineId,
2177 element_id: String,
2178 reply: GenericSender<Result<bool, ErrorStatus>>,
2179) {
2180 reply
2181 .send(
2182 get_known_element(documents, pipeline, element_id).and_then(|element| {
2183 if let Some(input_element) = element.downcast::<HTMLInputElement>() {
2184 Ok(input_element.Checked())
2185 } else if let Some(option_element) = element.downcast::<HTMLOptionElement>() {
2186 Ok(option_element.Selected())
2187 } else if element.is::<HTMLElement>() {
2188 Ok(false) } else {
2190 Err(ErrorStatus::UnknownError)
2191 }
2192 }),
2193 )
2194 .unwrap();
2195}
2196
2197fn scroll_into_view(cx: &mut JSContext, element: &Element) {
2199 let paint_tree = get_element_pointer_interactable_paint_tree(cx, element);
2201 if is_element_in_view(cx, element, &paint_tree) {
2202 return;
2203 }
2204
2205 let options = BooleanOrScrollIntoViewOptions::ScrollIntoViewOptions(ScrollIntoViewOptions {
2210 parent: ScrollOptions {
2211 behavior: ScrollBehavior::Instant,
2212 },
2213 block: ScrollLogicalPosition::End,
2214 inline: ScrollLogicalPosition::Nearest,
2215 container: Default::default(),
2216 });
2217 element.ScrollIntoView(cx, options);
2219}
2220
2221pub(crate) fn set_protocol_handler_automation_mode(
2222 documents: &DocumentCollection,
2223 pipeline: PipelineId,
2224 mode: CustomHandlersAutomationMode,
2225) {
2226 if let Some(document) = documents.find_document(pipeline) {
2227 document.set_protocol_handler_automation_mode(mode);
2228 }
2229}
2230
2231pub(crate) fn set_permission(
2233 documents: &DocumentCollection,
2234 pipeline: PipelineId,
2235 name: String,
2236 state: SetPermissionState,
2237 reply: GenericOneshotSender<Result<(), ErrorStatus>>,
2238) {
2239 let Ok(name) = name.parse::<PermissionName>() else {
2240 if let Err(err) = reply.send(Err(ErrorStatus::InvalidArgument)) {
2241 error!("SetPermission Failed to send reply: {err}");
2242 }
2243 return;
2244 };
2245 let state = match state {
2246 SetPermissionState::Denied => PermissionState::Denied,
2247 SetPermissionState::Granted => PermissionState::Granted,
2248 SetPermissionState::Prompt => PermissionState::Prompt,
2249 };
2250
2251 let Some(global) = documents.find_global(pipeline) else {
2252 if let Err(err) = reply.send(Err(ErrorStatus::NoSuchWindow)) {
2253 error!("SetPermission Failed to send reply: {err}");
2254 }
2255 return;
2256 };
2257
2258 global
2260 .permission_state_invocation_results()
2261 .borrow_mut()
2262 .insert(name, state);
2263
2264 if let Err(err) = reply.send(Ok(())) {
2268 error!("SetPermission Failed to send reply: {err}");
2269 }
2270}