-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebdriver_handlers.rs
More file actions
2221 lines (2058 loc) · 80.1 KB
/
Copy pathwebdriver_handlers.rs
File metadata and controls
2221 lines (2058 loc) · 80.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::collections::{HashMap, HashSet};
use std::ffi::CString;
use std::ptr::NonNull;
use cookie::Cookie;
use embedder_traits::{
CustomHandlersAutomationMode, JSValue, JavaScriptEvaluationError,
JavaScriptEvaluationResultSerializationError, WebDriverFrameId, WebDriverJSResult,
WebDriverLoadStatus,
};
use euclid::default::{Point2D, Rect, Size2D};
use hyper_serde::Serde;
use js::context::JSContext;
use js::conversions::jsstr_to_string;
use js::jsapi::{
self, GetPropertyKeys, HandleValueArray, JS_GetOwnPropertyDescriptorById, JS_GetPropertyById,
JS_IsExceptionPending, JSAutoRealm, JSObject, JSType, PropertyDescriptor,
};
use js::jsval::UndefinedValue;
use js::realm::CurrentRealm;
use js::rust::wrappers::{JS_CallFunctionName, JS_GetProperty, JS_HasOwnProperty, JS_TypeOfValue};
use js::rust::{Handle, HandleObject, HandleValue, IdVector, ToString};
use net_traits::CookieSource::{HTTP, NonHTTP};
use net_traits::CoreResourceMsg::{
DeleteCookie, DeleteCookies, GetCookiesDataForUrl, SetCookieForUrl,
};
use script_bindings::codegen::GenericBindings::ShadowRootBinding::ShadowRootMethods;
use script_bindings::conversions::is_array_like;
use script_bindings::num::Finite;
use script_bindings::settings_stack::run_a_script;
use servo_base::generic_channel::{self, GenericOneshotSender, GenericSend, GenericSender};
use servo_base::id::{BrowsingContextId, PipelineId};
use webdriver::error::ErrorStatus;
use crate::DomTypeHolder;
use crate::document_collection::DocumentCollection;
use crate::dom::attr::is_boolean_attribute;
use crate::dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::CSSStyleDeclarationMethods;
use crate::dom::bindings::codegen::Bindings::DOMRectBinding::DOMRectMethods;
use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
use crate::dom::bindings::codegen::Bindings::ElementBinding::{
ElementMethods, ScrollIntoViewOptions, ScrollLogicalPosition,
};
use crate::dom::bindings::codegen::Bindings::HTMLElementBinding::HTMLElementMethods;
use crate::dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods;
use crate::dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods;
use crate::dom::bindings::codegen::Bindings::HTMLOrSVGElementBinding::FocusOptions;
use crate::dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods;
use crate::dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding::HTMLTextAreaElementMethods;
use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use crate::dom::bindings::codegen::Bindings::WindowBinding::{
ScrollBehavior, ScrollOptions, WindowMethods,
};
use crate::dom::bindings::codegen::Bindings::XMLSerializerBinding::XMLSerializerMethods;
use crate::dom::bindings::codegen::Bindings::XPathResultBinding::{
XPathResultConstants, XPathResultMethods,
};
use crate::dom::bindings::codegen::UnionTypes::BooleanOrScrollIntoViewOptions;
use crate::dom::bindings::conversions::{
ConversionBehavior, ConversionResult, FromJSValConvertible, get_property, get_property_jsval,
jsid_to_string, root_from_object,
};
use crate::dom::bindings::error::{Error, report_pending_exception, throw_dom_exception};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::reflector::{DomGlobal, DomObject};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::document::Document;
use crate::dom::domrect::DOMRect;
use crate::dom::element::Element;
use crate::dom::eventtarget::EventTarget;
use crate::dom::globalscope::GlobalScope;
use crate::dom::html::htmlbodyelement::HTMLBodyElement;
use crate::dom::html::htmldatalistelement::HTMLDataListElement;
use crate::dom::html::htmlelement::HTMLElement;
use crate::dom::html::htmlformelement::FormControl;
use crate::dom::html::htmliframeelement::HTMLIFrameElement;
use crate::dom::html::htmloptgroupelement::HTMLOptGroupElement;
use crate::dom::html::htmloptionelement::HTMLOptionElement;
use crate::dom::html::htmlselectelement::HTMLSelectElement;
use crate::dom::html::htmltextareaelement::HTMLTextAreaElement;
use crate::dom::html::input_element::HTMLInputElement;
use crate::dom::input_element::input_type::InputType;
use crate::dom::node::{Node, NodeTraits, ShadowIncluding};
use crate::dom::nodelist::NodeList;
use crate::dom::types::ShadowRoot;
use crate::dom::validitystate::ValidationFlags;
use crate::dom::window::Window;
use crate::dom::xmlserializer::XMLSerializer;
use crate::realms::{InRealm, enter_auto_realm, enter_realm};
use crate::script_runtime::{CanGc, JSContext as SafeJSContext};
use crate::script_thread::ScriptThread;
/// <https://w3c.github.io/webdriver/#dfn-is-stale>
fn is_stale(element: &Element) -> bool {
// An element is stale if its node document is not the active document
// or if it is not connected.
!element.owner_document().is_active() || !element.is_connected()
}
/// <https://w3c.github.io/webdriver/#dfn-is-detached>
fn is_detached(shadow_root: &ShadowRoot) -> bool {
// A shadow root is detached if its node document is not the active document
// or if the element node referred to as its host is stale.
!shadow_root.owner_document().is_active() || is_stale(&shadow_root.Host())
}
/// <https://w3c.github.io/webdriver/#dfn-disabled>
fn is_disabled(element: &Element) -> bool {
// Step 1. If element is an option element or element is an optgroup element
if element.is::<HTMLOptionElement>() || element.is::<HTMLOptGroupElement>() {
// Step 1.1. For each inclusive ancestor `ancestor` of element
let disabled = element
.upcast::<Node>()
.inclusive_ancestors(ShadowIncluding::No)
.any(|node| {
if node.is::<HTMLOptGroupElement>() || node.is::<HTMLSelectElement>() {
// Step 1.1.1. If `ancestor` is an optgroup element or `ancestor` is a select element,
// and `ancestor` is actually disabled, return true.
node.downcast::<Element>().unwrap().is_actually_disabled()
} else {
false
}
});
// Step 1.2
// The spec suggests that we immediately return false if the above is not true.
// However, it causes disabled option element to not be considered as disabled.
// Hence, here we also check if the element itself is actually disabled.
if disabled {
return true;
}
}
// Step 2. Return element is actually disabled.
element.is_actually_disabled()
}
pub(crate) fn handle_get_known_window(
documents: &DocumentCollection,
pipeline: PipelineId,
webview_id: String,
reply: GenericSender<Result<(), ErrorStatus>>,
) {
if reply
.send(
documents
.find_window(pipeline)
.map_or(Err(ErrorStatus::NoSuchWindow), |window| {
let window_proxy = window.window_proxy();
// Step 3-4: Window must be top level browsing context.
if window_proxy.browsing_context_id() != window_proxy.webview_id() ||
window_proxy.webview_id().to_string() != webview_id
{
Err(ErrorStatus::NoSuchWindow)
} else {
Ok(())
}
}),
)
.is_err()
{
error!("Webdriver get known window reply failed");
}
}
pub(crate) fn handle_get_known_shadow_root(
documents: &DocumentCollection,
pipeline: PipelineId,
shadow_root_id: String,
reply: GenericSender<Result<(), ErrorStatus>>,
) {
let result = get_known_shadow_root(documents, pipeline, shadow_root_id).map(|_| ());
if reply.send(result).is_err() {
error!("Webdriver get known shadow root reply failed");
}
}
/// <https://w3c.github.io/webdriver/#dfn-get-a-known-shadow-root>
fn get_known_shadow_root(
documents: &DocumentCollection,
pipeline: PipelineId,
node_id: String,
) -> Result<DomRoot<ShadowRoot>, ErrorStatus> {
let doc = documents
.find_document(pipeline)
.ok_or(ErrorStatus::NoSuchWindow)?;
// Step 1. If not node reference is known with session, session's current browsing context,
// and reference return error with error code no such shadow root.
if !ScriptThread::has_node_id(pipeline, &node_id) {
return Err(ErrorStatus::NoSuchShadowRoot);
}
// Step 2. Let node be the result of get a node with session,
// session's current browsing context, and reference.
let node = find_node_by_unique_id_in_document(&doc, node_id);
// Step 3. If node is not null and node does not implement ShadowRoot
// return error with error code no such shadow root.
if let Some(ref node) = node {
if !node.is::<ShadowRoot>() {
return Err(ErrorStatus::NoSuchShadowRoot);
}
}
// Step 4.1. If node is null return error with error code detached shadow root.
let Some(node) = node else {
return Err(ErrorStatus::DetachedShadowRoot);
};
// Step 4.2. If node is detached return error with error code detached shadow root.
// A shadow root is detached if its node document is not the active document
// or if the element node referred to as its host is stale.
let shadow_root = DomRoot::downcast::<ShadowRoot>(node).unwrap();
if is_detached(&shadow_root) {
return Err(ErrorStatus::DetachedShadowRoot);
}
// Step 5. Return success with data node.
Ok(shadow_root)
}
pub(crate) fn handle_get_known_element(
documents: &DocumentCollection,
pipeline: PipelineId,
element_id: String,
reply: GenericSender<Result<(), ErrorStatus>>,
) {
let result = get_known_element(documents, pipeline, element_id).map(|_| ());
if reply.send(result).is_err() {
error!("Webdriver get known element reply failed");
}
}
/// <https://w3c.github.io/webdriver/#dfn-get-a-known-element>
fn get_known_element(
documents: &DocumentCollection,
pipeline: PipelineId,
node_id: String,
) -> Result<DomRoot<Element>, ErrorStatus> {
let doc = documents
.find_document(pipeline)
.ok_or(ErrorStatus::NoSuchWindow)?;
// Step 1. If not node reference is known with session, session's current browsing context,
// and reference return error with error code no such element.
if !ScriptThread::has_node_id(pipeline, &node_id) {
return Err(ErrorStatus::NoSuchElement);
}
// Step 2.Let node be the result of get a node with session,
// session's current browsing context, and reference.
let node = find_node_by_unique_id_in_document(&doc, node_id);
// Step 3. If node is not null and node does not implement Element
// return error with error code no such element.
if let Some(ref node) = node {
if !node.is::<Element>() {
return Err(ErrorStatus::NoSuchElement);
}
}
// Step 4.1. If node is null return error with error code stale element reference.
let Some(node) = node else {
return Err(ErrorStatus::StaleElementReference);
};
// Step 4.2. If node is stale return error with error code stale element reference.
let element = DomRoot::downcast::<Element>(node).unwrap();
if is_stale(&element) {
return Err(ErrorStatus::StaleElementReference);
}
// Step 5. Return success with data node.
Ok(element)
}
// This is also used by `dom/window.rs`
pub(crate) fn find_node_by_unique_id_in_document(
document: &Document,
node_id: String,
) -> Option<DomRoot<Node>> {
let pipeline = document.window().pipeline_id();
document
.upcast::<Node>()
.traverse_preorder(ShadowIncluding::Yes)
.find(|node| node.unique_id(pipeline) == node_id)
}
/// <https://w3c.github.io/webdriver/#dfn-link-text-selector>
fn matching_links(
links: &NodeList,
link_text: String,
partial: bool,
) -> impl Iterator<Item = String> + '_ {
links
.iter()
.filter(move |node| {
let content = node
.downcast::<HTMLElement>()
.map(|element| element.InnerText())
.map_or("".to_owned(), String::from)
.trim()
.to_owned();
if partial {
content.contains(&link_text)
} else {
content == link_text
}
})
.map(|node| node.unique_id(node.owner_doc().window().pipeline_id()))
}
fn all_matching_links(
root_node: &Node,
link_text: String,
partial: bool,
) -> Result<Vec<String>, ErrorStatus> {
// <https://w3c.github.io/webdriver/#dfn-find>
// Step 7.2. If a DOMException, SyntaxError, XPathException, or other error occurs
// during the execution of the element location strategy, return error invalid selector.
root_node
.query_selector_all(DOMString::from("a"))
.map_err(|_| ErrorStatus::InvalidSelector)
.map(|nodes| matching_links(&nodes, link_text, partial).collect())
}
#[expect(unsafe_code)]
fn object_has_to_json_property(
cx: SafeJSContext,
global_scope: &GlobalScope,
object: HandleObject,
) -> bool {
let name = CString::new("toJSON").unwrap();
let mut found = false;
if unsafe { JS_HasOwnProperty(*cx, object, name.as_ptr(), &mut found) } && found {
rooted!(in(*cx) let mut value = UndefinedValue());
let result = unsafe { JS_GetProperty(*cx, object, name.as_ptr(), value.handle_mut()) };
if !result {
throw_dom_exception(cx, global_scope, Error::JSFailed, CanGc::note());
false
} else {
result && unsafe { JS_TypeOfValue(*cx, value.handle()) } == JSType::JSTYPE_FUNCTION
}
} else if unsafe { JS_IsExceptionPending(*cx) } {
throw_dom_exception(cx, global_scope, Error::JSFailed, CanGc::note());
false
} else {
false
}
}
#[expect(unsafe_code)]
/// <https://w3c.github.io/webdriver/#dfn-collection>
fn is_arguments_object(cx: SafeJSContext, value: HandleValue) -> bool {
rooted!(in(*cx) let class_name = unsafe { ToString(*cx, value) });
let Some(class_name) = NonNull::new(class_name.get()) else {
return false;
};
let class_name = unsafe { jsstr_to_string(*cx, class_name) };
class_name == "[object Arguments]"
}
#[derive(Clone, Eq, Hash, PartialEq)]
struct HashableJSVal(u64);
impl From<HandleValue<'_>> for HashableJSVal {
fn from(v: HandleValue<'_>) -> HashableJSVal {
HashableJSVal(v.get().asBits_)
}
}
/// <https://w3c.github.io/webdriver/#dfn-json-clone>
pub(crate) fn jsval_to_webdriver(
cx: &mut CurrentRealm,
global_scope: &GlobalScope,
val: HandleValue,
) -> WebDriverJSResult {
run_a_script::<DomTypeHolder, _>(global_scope, || {
let mut seen = HashSet::new();
let result = jsval_to_webdriver_inner(cx.into(), global_scope, val, &mut seen);
let in_realm_proof = cx.into();
let in_realm = InRealm::Already(&in_realm_proof);
if result.is_err() {
report_pending_exception(cx.into(), in_realm, CanGc::from_cx(cx));
}
result
})
}
#[expect(unsafe_code)]
/// <https://w3c.github.io/webdriver/#dfn-internal-json-clone>
fn jsval_to_webdriver_inner(
cx: SafeJSContext,
global_scope: &GlobalScope,
val: HandleValue,
seen: &mut HashSet<HashableJSVal>,
) -> WebDriverJSResult {
let _ac = enter_realm(global_scope);
if val.get().is_undefined() {
Ok(JSValue::Undefined)
} else if val.get().is_null() {
Ok(JSValue::Null)
} else if val.get().is_boolean() {
Ok(JSValue::Boolean(val.get().to_boolean()))
} else if val.get().is_number() {
Ok(JSValue::Number(val.to_number()))
} else if val.get().is_string() {
let string = NonNull::new(val.to_string()).expect("Should have a non-Null String");
let string = unsafe { jsstr_to_string(*cx, string) };
Ok(JSValue::String(string))
} else if val.get().is_object() {
rooted!(in(*cx) let object = match unsafe { FromJSValConvertible::from_jsval(*cx, val, ())}.unwrap() {
ConversionResult::Success(object) => object,
_ => unreachable!(),
});
let _ac = JSAutoRealm::new(*cx, *object);
if let Ok(element) = unsafe { root_from_object::<Element>(*object, *cx) } {
// If the element is stale, return error with error code stale element reference.
if is_stale(&element) {
Err(JavaScriptEvaluationError::SerializationError(
JavaScriptEvaluationResultSerializationError::StaleElementReference,
))
} else {
Ok(JSValue::Element(
element
.upcast::<Node>()
.unique_id(element.owner_window().pipeline_id()),
))
}
} else if let Ok(shadow_root) = unsafe { root_from_object::<ShadowRoot>(*object, *cx) } {
// If the shadow root is detached, return error with error code detached shadow root.
if is_detached(&shadow_root) {
Err(JavaScriptEvaluationError::SerializationError(
JavaScriptEvaluationResultSerializationError::DetachedShadowRoot,
))
} else {
Ok(JSValue::ShadowRoot(
shadow_root
.upcast::<Node>()
.unique_id(shadow_root.owner_window().pipeline_id()),
))
}
} else if let Ok(window) = unsafe { root_from_object::<Window>(*object, *cx) } {
let window_proxy = window.window_proxy();
if window_proxy.is_browsing_context_discarded() {
Err(JavaScriptEvaluationError::SerializationError(
JavaScriptEvaluationResultSerializationError::StaleElementReference,
))
} else if window_proxy.browsing_context_id() == window_proxy.webview_id() {
Ok(JSValue::Window(window.webview_id().to_string()))
} else {
Ok(JSValue::Frame(
window_proxy.browsing_context_id().to_string(),
))
}
} else if object_has_to_json_property(cx, global_scope, object.handle()) {
let name = CString::new("toJSON").unwrap();
rooted!(in(*cx) let mut value = UndefinedValue());
let call_result = unsafe {
JS_CallFunctionName(
*cx,
object.handle(),
name.as_ptr(),
&HandleValueArray::empty(),
value.handle_mut(),
)
};
if call_result {
Ok(jsval_to_webdriver_inner(
cx,
global_scope,
value.handle(),
seen,
)?)
} else {
throw_dom_exception(cx, global_scope, Error::JSFailed, CanGc::note());
Err(JavaScriptEvaluationError::SerializationError(
JavaScriptEvaluationResultSerializationError::OtherJavaScriptError,
))
}
} else {
clone_an_object(cx, global_scope, val, seen, object.handle())
}
} else {
Err(JavaScriptEvaluationError::SerializationError(
JavaScriptEvaluationResultSerializationError::UnknownType,
))
}
}
#[expect(unsafe_code)]
/// <https://w3c.github.io/webdriver/#dfn-clone-an-object>
fn clone_an_object(
cx: SafeJSContext,
global_scope: &GlobalScope,
val: HandleValue,
seen: &mut HashSet<HashableJSVal>,
object_handle: Handle<'_, *mut JSObject>,
) -> WebDriverJSResult {
let hashable = val.into();
// Step 1. If value is in `seen`, return error with error code javascript error.
if seen.contains(&hashable) {
return Err(JavaScriptEvaluationError::SerializationError(
JavaScriptEvaluationResultSerializationError::OtherJavaScriptError,
));
}
// Step 2. Append value to `seen`.
seen.insert(hashable.clone());
let return_val = if unsafe {
is_array_like::<crate::DomTypeHolder>(*cx, val) || is_arguments_object(cx, val)
} {
let mut result: Vec<JSValue> = Vec::new();
let get_property_result =
get_property::<u32>(cx, object_handle, c"length", ConversionBehavior::Default);
let length = match get_property_result {
Ok(length) => match length {
Some(length) => length,
_ => {
return Err(JavaScriptEvaluationError::SerializationError(
JavaScriptEvaluationResultSerializationError::UnknownType,
));
},
},
Err(error) => {
throw_dom_exception(cx, global_scope, error, CanGc::note());
return Err(JavaScriptEvaluationError::SerializationError(
JavaScriptEvaluationResultSerializationError::OtherJavaScriptError,
));
},
};
// Step 4. For each enumerable property in value, run the following substeps:
for i in 0..length {
rooted!(in(*cx) let mut item = UndefinedValue());
let cname = CString::new(i.to_string()).unwrap();
let get_property_result =
get_property_jsval(cx, object_handle, &cname, item.handle_mut());
match get_property_result {
Ok(_) => {
let conversion_result =
jsval_to_webdriver_inner(cx, global_scope, item.handle(), seen);
match conversion_result {
Ok(converted_item) => result.push(converted_item),
err @ Err(_) => return err,
}
},
Err(error) => {
throw_dom_exception(cx, global_scope, error, CanGc::note());
return Err(JavaScriptEvaluationError::SerializationError(
JavaScriptEvaluationResultSerializationError::OtherJavaScriptError,
));
},
}
}
Ok(JSValue::Array(result))
} else {
let mut result = HashMap::new();
let mut ids = unsafe { IdVector::new(*cx) };
let succeeded = unsafe {
GetPropertyKeys(
*cx,
object_handle.into(),
jsapi::JSITER_OWNONLY,
ids.handle_mut(),
)
};
if !succeeded {
return Err(JavaScriptEvaluationError::SerializationError(
JavaScriptEvaluationResultSerializationError::OtherJavaScriptError,
));
}
for id in ids.iter() {
rooted!(in(*cx) let id = *id);
rooted!(in(*cx) let mut desc = PropertyDescriptor::default());
let mut is_none = false;
let succeeded = unsafe {
JS_GetOwnPropertyDescriptorById(
*cx,
object_handle.into(),
id.handle().into(),
desc.handle_mut().into(),
&mut is_none,
)
};
if !succeeded {
return Err(JavaScriptEvaluationError::SerializationError(
JavaScriptEvaluationResultSerializationError::OtherJavaScriptError,
));
}
rooted!(in(*cx) let mut property = UndefinedValue());
let succeeded = unsafe {
JS_GetPropertyById(
*cx,
object_handle.into(),
id.handle().into(),
property.handle_mut().into(),
)
};
if !succeeded {
return Err(JavaScriptEvaluationError::SerializationError(
JavaScriptEvaluationResultSerializationError::OtherJavaScriptError,
));
}
if !property.is_undefined() {
let name = unsafe { jsid_to_string(*cx, id.handle()) };
let Some(name) = name else {
return Err(JavaScriptEvaluationError::SerializationError(
JavaScriptEvaluationResultSerializationError::OtherJavaScriptError,
));
};
let value = jsval_to_webdriver_inner(cx, global_scope, property.handle(), seen)?;
result.insert(name.into(), value);
}
}
Ok(JSValue::Object(result))
};
// Step 5. Remove the last element of `seen`.
seen.remove(&hashable);
// Step 6. Return success with data `result`.
return_val
}
pub(crate) fn handle_execute_async_script(
window: Option<DomRoot<Window>>,
eval: String,
reply: GenericSender<WebDriverJSResult>,
cx: &mut JSContext,
) {
match window {
Some(window) => {
let reply_sender = reply.clone();
window.set_webdriver_script_chan(Some(reply));
let global_scope = window.as_global_scope();
let mut realm = enter_auto_realm(cx, global_scope);
let mut realm = realm.current_realm();
if let Err(error) = global_scope.evaluate_js_on_global(
&mut realm,
eval.into(),
"",
None, // No known `introductionType` for JS code from WebDriver
None,
) {
reply_sender.send(Err(error)).unwrap_or_else(|error| {
error!("ExecuteAsyncScript Failed to send reply: {error}");
});
}
},
None => {
reply
.send(Err(JavaScriptEvaluationError::DocumentNotFound))
.unwrap_or_else(|error| {
error!("ExecuteAsyncScript Failed to send reply: {error}");
});
},
}
}
/// Get BrowsingContextId for <https://w3c.github.io/webdriver/#switch-to-parent-frame>
pub(crate) fn handle_get_parent_frame_id(
documents: &DocumentCollection,
pipeline: PipelineId,
reply: GenericSender<Result<BrowsingContextId, ErrorStatus>>,
) {
// Step 2. If session's current parent browsing context is no longer open,
// return error with error code no such window.
reply
.send(
documents
.find_window(pipeline)
.and_then(|window| {
window
.window_proxy()
.parent()
.map(|parent| parent.browsing_context_id())
})
.ok_or(ErrorStatus::NoSuchWindow),
)
.unwrap();
}
/// Get the BrowsingContextId for <https://w3c.github.io/webdriver/#dfn-switch-to-frame>
pub(crate) fn handle_get_browsing_context_id(
documents: &DocumentCollection,
pipeline: PipelineId,
webdriver_frame_id: WebDriverFrameId,
reply: GenericSender<Result<BrowsingContextId, ErrorStatus>>,
) {
reply
.send(match webdriver_frame_id {
WebDriverFrameId::Short(id) => {
// Step 5. If id is not a supported property index of window,
// return error with error code no such frame.
documents
.find_document(pipeline)
.ok_or(ErrorStatus::NoSuchWindow)
.and_then(|document| {
document
.iframes()
.iter()
.nth(id as usize)
.and_then(|iframe| iframe.browsing_context_id())
.ok_or(ErrorStatus::NoSuchFrame)
})
},
WebDriverFrameId::Element(element_id) => {
get_known_element(documents, pipeline, element_id).and_then(|element| {
element
.downcast::<HTMLIFrameElement>()
.and_then(|element| element.browsing_context_id())
.ok_or(ErrorStatus::NoSuchFrame)
})
},
})
.unwrap();
}
/// <https://w3c.github.io/webdriver/#dfn-center-point>
fn get_element_in_view_center_point(element: &Element, can_gc: CanGc) -> Option<Point2D<i64>> {
let doc = element.owner_document();
// Step 1: Let rectangle be the first element of the DOMRect sequence
// returned by calling getClientRects() on element.
element.GetClientRects(can_gc).first().map(|rectangle| {
let x = rectangle.X();
let y = rectangle.Y();
let width = rectangle.Width();
let height = rectangle.Height();
debug!(
"get_element_in_view_center_point: Element rectangle at \
(x: {x}, y: {y}, width: {width}, height: {height})",
);
let window = doc.window();
// Steps 2. Let left be max(0, min(x coordinate, x coordinate + width dimension)).
let left = (x.min(x + width)).max(0.0);
// Step 3. Let right be min(innerWidth, max(x coordinate, x coordinate + width dimension)).
let right = f64::min(window.InnerWidth() as f64, x.max(x + width));
// Step 4. Let top be max(0, min(y coordinate, y coordinate + height dimension)).
let top = (y.min(y + height)).max(0.0);
// Step 5. Let bottom be
// min(innerHeight, max(y coordinate, y coordinate + height dimension)).
let bottom = f64::min(window.InnerHeight() as f64, y.max(y + height));
debug!(
"get_element_in_view_center_point: Computed rectangle is \
(left: {left}, right: {right}, top: {top}, bottom: {bottom})",
);
// Step 6. Let x be floor((left + right) ÷ 2.0).
let center_x = ((left + right) / 2.0).floor() as i64;
// Step 7. Let y be floor((top + bottom) ÷ 2.0).
let center_y = ((top + bottom) / 2.0).floor() as i64;
debug!(
"get_element_in_view_center_point: Element center point at ({center_x}, {center_y})",
);
// Step 8
Point2D::new(center_x, center_y)
})
}
pub(crate) fn handle_get_element_in_view_center_point(
documents: &DocumentCollection,
pipeline: PipelineId,
element_id: String,
reply: GenericOneshotSender<Result<Option<(i64, i64)>, ErrorStatus>>,
can_gc: CanGc,
) {
reply
.send(
get_known_element(documents, pipeline, element_id).map(|element| {
get_element_in_view_center_point(&element, can_gc).map(|point| (point.x, point.y))
}),
)
.unwrap();
}
fn retrieve_document_and_check_root_existence(
documents: &DocumentCollection,
pipeline: PipelineId,
) -> Result<DomRoot<Document>, ErrorStatus> {
let document = documents
.find_document(pipeline)
.ok_or(ErrorStatus::NoSuchWindow)?;
// <https://w3c.github.io/webdriver/#find-element>
// <https://w3c.github.io/webdriver/#find-elements>
// Step 7 - 8. If current browsing context's document element is null,
// return error with error code no such element.
if document.GetDocumentElement().is_none() {
Err(ErrorStatus::NoSuchElement)
} else {
Ok(document)
}
}
pub(crate) fn handle_find_elements_css_selector(
documents: &DocumentCollection,
pipeline: PipelineId,
selector: String,
reply: GenericSender<Result<Vec<String>, ErrorStatus>>,
) {
match retrieve_document_and_check_root_existence(documents, pipeline) {
Ok(document) => reply
.send(
document
.QuerySelectorAll(DOMString::from(selector))
.map_err(|_| ErrorStatus::InvalidSelector)
.map(|nodes| {
nodes
.iter()
.map(|x| x.upcast::<Node>().unique_id(pipeline))
.collect()
}),
)
.unwrap(),
Err(error) => reply.send(Err(error)).unwrap(),
}
}
pub(crate) fn handle_find_elements_link_text(
documents: &DocumentCollection,
pipeline: PipelineId,
selector: String,
partial: bool,
reply: GenericSender<Result<Vec<String>, ErrorStatus>>,
) {
match retrieve_document_and_check_root_existence(documents, pipeline) {
Ok(document) => reply
.send(all_matching_links(
document.upcast::<Node>(),
selector,
partial,
))
.unwrap(),
Err(error) => reply.send(Err(error)).unwrap(),
}
}
pub(crate) fn handle_find_elements_tag_name(
documents: &DocumentCollection,
pipeline: PipelineId,
selector: String,
reply: GenericSender<Result<Vec<String>, ErrorStatus>>,
can_gc: CanGc,
) {
match retrieve_document_and_check_root_existence(documents, pipeline) {
Ok(document) => reply
.send(Ok(document
.GetElementsByTagName(DOMString::from(selector), can_gc)
.elements_iter()
.map(|x| x.upcast::<Node>().unique_id(pipeline))
.collect::<Vec<String>>()))
.unwrap(),
Err(error) => reply.send(Err(error)).unwrap(),
}
}
/// <https://w3c.github.io/webdriver/#xpath>
fn find_elements_xpath_strategy(
document: &Document,
start_node: &Node,
selector: String,
pipeline: PipelineId,
can_gc: CanGc,
) -> Result<Vec<String>, ErrorStatus> {
// Step 1. Let evaluateResult be the result of calling evaluate,
// with arguments selector, start node, null, ORDERED_NODE_SNAPSHOT_TYPE, and null.
// A snapshot is used to promote operation atomicity.
let evaluate_result = match document.Evaluate(
DOMString::from(selector),
start_node,
None,
XPathResultConstants::ORDERED_NODE_SNAPSHOT_TYPE,
None,
can_gc,
) {
Ok(res) => res,
Err(_) => return Err(ErrorStatus::InvalidSelector),
};
// Step 2. Let index be 0. (Handled altogether in Step 5.)
// Step 3: Let length be the result of getting the property "snapshotLength"
// from evaluateResult.
let length = match evaluate_result.GetSnapshotLength() {
Ok(len) => len,
Err(_) => return Err(ErrorStatus::InvalidSelector),
};
// Step 4: Prepare result vector
let mut result = Vec::new();
// Step 5: Repeat, while index is less than length:
for index in 0..length {
// Step 5.1. Let node be the result of calling snapshotItem with
// evaluateResult as this and index as the argument.
let node = match evaluate_result.SnapshotItem(index) {
Ok(node) => node.expect(
"Node should always exist as ORDERED_NODE_SNAPSHOT_TYPE \
gives static result and we verified the length!",
),
Err(_) => return Err(ErrorStatus::InvalidSelector),
};
// Step 5.2. If node is not an element return an error with error code invalid selector.
if !node.is::<Element>() {
return Err(ErrorStatus::InvalidSelector);
}
// Step 5.3. Append node to result.
result.push(node.unique_id(pipeline));
}
// Step 6. Return success with data result.
Ok(result)
}
pub(crate) fn handle_find_elements_xpath_selector(
documents: &DocumentCollection,
pipeline: PipelineId,
selector: String,
reply: GenericSender<Result<Vec<String>, ErrorStatus>>,
can_gc: CanGc,
) {
match retrieve_document_and_check_root_existence(documents, pipeline) {
Ok(document) => reply
.send(find_elements_xpath_strategy(
&document,
document.upcast::<Node>(),
selector,
pipeline,
can_gc,
))
.unwrap(),
Err(error) => reply.send(Err(error)).unwrap(),
}
}
pub(crate) fn handle_find_element_elements_css_selector(
documents: &DocumentCollection,
pipeline: PipelineId,
element_id: String,
selector: String,
reply: GenericSender<Result<Vec<String>, ErrorStatus>>,
) {
reply
.send(
get_known_element(documents, pipeline, element_id).and_then(|element| {
element
.upcast::<Node>()
.query_selector_all(DOMString::from(selector))
.map_err(|_| ErrorStatus::InvalidSelector)
.map(|nodes| {
nodes
.iter()
.map(|x| x.upcast::<Node>().unique_id(pipeline))
.collect()
})
}),
)
.unwrap();
}
pub(crate) fn handle_find_element_elements_link_text(
documents: &DocumentCollection,
pipeline: PipelineId,
element_id: String,
selector: String,
partial: bool,
reply: GenericSender<Result<Vec<String>, ErrorStatus>>,
) {
reply
.send(
get_known_element(documents, pipeline, element_id).and_then(|element| {
all_matching_links(element.upcast::<Node>(), selector.clone(), partial)
}),
)
.unwrap();
}
pub(crate) fn handle_find_element_elements_tag_name(
documents: &DocumentCollection,
pipeline: PipelineId,
element_id: String,
selector: String,
reply: GenericSender<Result<Vec<String>, ErrorStatus>>,
can_gc: CanGc,
) {
reply
.send(
get_known_element(documents, pipeline, element_id).map(|element| {
element
.GetElementsByTagName(DOMString::from(selector), can_gc)