Skip to main content

embedder_traits/
webdriver.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5#![allow(missing_docs)]
6
7use cookie::Cookie;
8use crossbeam_channel::Sender;
9use euclid::default::Rect as UntypedRect;
10use euclid::{Rect, Size2D};
11use hyper_serde::Serde;
12use image::RgbaImage;
13use malloc_size_of_derive::MallocSizeOf;
14use rustc_hash::FxHashMap;
15use serde::{Deserialize, Serialize};
16use servo_base::generic_channel::{GenericOneshotSender, GenericSender};
17use servo_base::id::{BrowsingContextId, WebViewId};
18use servo_geometry::{DeviceIndependentIntRect, DeviceIndependentPixel};
19use style_traits::CSSPixel;
20use url::Url;
21use webdriver::command::SetPermissionState;
22use webdriver::error::ErrorStatus;
23
24use crate::{InputEvent, JSValue, JavaScriptEvaluationError, ScreenshotCaptureError};
25
26#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
27pub enum WebDriverUserPrompt {
28    Alert,
29    BeforeUnload,
30    Confirm,
31    Default,
32    File,
33    Prompt,
34    FallbackDefault,
35}
36
37impl WebDriverUserPrompt {
38    pub fn new_from_str(s: &str) -> Option<Self> {
39        match s {
40            "alert" => Some(WebDriverUserPrompt::Alert),
41            "beforeUnload" => Some(WebDriverUserPrompt::BeforeUnload),
42            "confirm" => Some(WebDriverUserPrompt::Confirm),
43            "default" => Some(WebDriverUserPrompt::Default),
44            "file" => Some(WebDriverUserPrompt::File),
45            "prompt" => Some(WebDriverUserPrompt::Prompt),
46            "fallbackDefault" => Some(WebDriverUserPrompt::FallbackDefault),
47            _ => None,
48        }
49    }
50}
51
52#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
53pub enum WebDriverUserPromptAction {
54    Accept,
55    Dismiss,
56    Ignore,
57}
58
59impl WebDriverUserPromptAction {
60    pub fn new_from_str(s: &str) -> Option<Self> {
61        match s {
62            "accept" => Some(WebDriverUserPromptAction::Accept),
63            "dismiss" => Some(WebDriverUserPromptAction::Dismiss),
64            "ignore" => Some(WebDriverUserPromptAction::Ignore),
65            _ => None,
66        }
67    }
68}
69
70/// <https://html.spec.whatwg.org/multipage/#registerprotocolhandler()-automation-mode>
71#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
72pub enum CustomHandlersAutomationMode {
73    AutoAccept,
74    AutoReject,
75    #[default]
76    None,
77}
78
79/// <https://w3c.github.io/webdriver/#new-window>
80#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
81pub enum NewWindowTypeHint {
82    Auto,
83    Tab,
84    Window,
85}
86
87/// Messages to the constellation originating from the WebDriver server.
88#[derive(Debug)]
89pub enum WebDriverCommandMsg {
90    /// Get the window rectangle.
91    GetWindowRect(WebViewId, GenericOneshotSender<DeviceIndependentIntRect>),
92    /// Get the viewport size.
93    GetViewportSize(
94        WebViewId,
95        GenericOneshotSender<Size2D<f32, DeviceIndependentPixel>>,
96    ),
97    /// Load a URL in the top-level browsing context with the given ID.
98    LoadUrl(WebViewId, Url),
99    /// Refresh the top-level browsing context with the given ID.
100    Refresh(WebViewId),
101    /// Navigate the webview with the given ID to the previous page in the browsing context's history.
102    GoBack(WebViewId),
103    /// Navigate the webview with the given ID to the next page in the browsing context's history.
104    GoForward(WebViewId),
105    /// Pass a webdriver command to the script thread of the current pipeline
106    /// of a browsing context.
107    ScriptCommand(BrowsingContextId, WebDriverScriptCommand),
108    /// Dispatch an input event to the given [`WebView`]. Once the event has been handled in the
109    /// page DOM a single message should be sent through the [`Sender`], if provided, informing the
110    /// WebDriver server that the inpute event has been handled.
111    InputEvent(WebViewId, InputEvent, Option<Sender<()>>),
112    /// Set the outer window rectangle.
113    SetWindowRect(
114        WebViewId,
115        DeviceIndependentIntRect,
116        GenericOneshotSender<DeviceIndependentIntRect>,
117    ),
118    /// Maximize the window. Send back result window rectangle.
119    MaximizeWebView(WebViewId, GenericOneshotSender<DeviceIndependentIntRect>),
120    /// Take a screenshot of the viewport.
121    TakeScreenshot(
122        WebViewId,
123        Option<Rect<f32, CSSPixel>>,
124        Sender<Result<RgbaImage, ScreenshotCaptureError>>,
125    ),
126    /// Create a new webview that loads about:blank. The embedder will use
127    /// the provided channels to return the top level browsing context id
128    /// associated with the new webview.
129    NewWindow(NewWindowTypeHint, GenericOneshotSender<WebViewId>),
130    /// Close the webview associated with the provided id.
131    CloseWebView(WebViewId, GenericOneshotSender<()>),
132    /// Make the given WebView the WebView to use for input event interaction.
133    SelectWebViewForInteraction(WebViewId),
134    /// Get the WebView selected for user interaction. For now, this is only used when
135    /// starting new sessions.
136    GetWebViewSelectedForInteraction(GenericOneshotSender<Option<WebViewId>>),
137    /// Get webviews state
138    GetAllWebViews(GenericOneshotSender<Vec<WebViewId>>),
139    /// Check whether top-level browsing context is open.
140    IsWebViewOpen(WebViewId, GenericOneshotSender<bool>),
141    /// Check whether browsing context is open.
142    IsBrowsingContextOpen(BrowsingContextId, GenericOneshotSender<bool>),
143    /// Check whether the given webview has a navigation attempt in progress. This is
144    /// ordered with navigation commands, so it also synchronizes the WebDriver server.
145    IsNavigationInProgress(WebViewId, GenericOneshotSender<bool>),
146    CurrentUserPrompt(WebViewId, GenericOneshotSender<Option<WebDriverUserPrompt>>),
147    HandleUserPrompt(
148        WebViewId,
149        WebDriverUserPromptAction,
150        GenericOneshotSender<Result<String, ()>>,
151    ),
152    GetAlertText(WebViewId, GenericOneshotSender<Result<String, ()>>),
153    SendAlertText(WebViewId, String),
154    AddLoadStatusSender(WebViewId, GenericSender<WebDriverLoadStatusMessage>),
155    RemoveLoadStatusSender(WebViewId),
156    FocusBrowsingContext(BrowsingContextId),
157    Shutdown,
158    ResetAllCookies(Sender<()>),
159}
160
161#[derive(Debug, Deserialize, Serialize)]
162pub enum WebDriverScriptCommand {
163    AddCookie(
164        #[serde(
165            deserialize_with = "::hyper_serde::deserialize",
166            serialize_with = "::hyper_serde::serialize"
167        )]
168        Cookie<'static>,
169        GenericSender<Result<(), ErrorStatus>>,
170    ),
171    DeleteCookies(GenericSender<Result<(), ErrorStatus>>),
172    DeleteCookie(String, GenericSender<Result<(), ErrorStatus>>),
173    ElementClear(String, GenericSender<Result<(), ErrorStatus>>),
174    ExecuteScriptWithCallback(String, GenericSender<WebDriverJSResult>),
175    FindElementsCSSSelector(String, GenericSender<Result<Vec<String>, ErrorStatus>>),
176    FindElementsLinkText(
177        String,
178        bool,
179        GenericSender<Result<Vec<String>, ErrorStatus>>,
180    ),
181    FindElementsTagName(String, GenericSender<Result<Vec<String>, ErrorStatus>>),
182    FindElementsXpathSelector(String, GenericSender<Result<Vec<String>, ErrorStatus>>),
183    FindElementElementsCSSSelector(
184        String,
185        String,
186        GenericSender<Result<Vec<String>, ErrorStatus>>,
187    ),
188    FindElementElementsLinkText(
189        String,
190        String,
191        bool,
192        GenericSender<Result<Vec<String>, ErrorStatus>>,
193    ),
194    FindElementElementsTagName(
195        String,
196        String,
197        GenericSender<Result<Vec<String>, ErrorStatus>>,
198    ),
199    FindElementElementsXPathSelector(
200        String,
201        String,
202        GenericSender<Result<Vec<String>, ErrorStatus>>,
203    ),
204    FindShadowElementsCSSSelector(
205        String,
206        String,
207        GenericSender<Result<Vec<String>, ErrorStatus>>,
208    ),
209    FindShadowElementsLinkText(
210        String,
211        String,
212        bool,
213        GenericSender<Result<Vec<String>, ErrorStatus>>,
214    ),
215    FindShadowElementsTagName(
216        String,
217        String,
218        GenericSender<Result<Vec<String>, ErrorStatus>>,
219    ),
220    FindShadowElementsXPathSelector(
221        String,
222        String,
223        GenericSender<Result<Vec<String>, ErrorStatus>>,
224    ),
225    GetElementShadowRoot(String, GenericSender<Result<Option<String>, ErrorStatus>>),
226    ElementClick(String, GenericSender<Result<Option<String>, ErrorStatus>>),
227    GetKnownElement(String, GenericSender<Result<(), ErrorStatus>>),
228    GetKnownShadowRoot(String, GenericSender<Result<(), ErrorStatus>>),
229    GetKnownWindow(String, GenericSender<Result<(), ErrorStatus>>),
230    GetActiveElement(GenericSender<Option<String>>),
231    GetComputedRole(String, GenericSender<Result<Option<String>, ErrorStatus>>),
232    GetCookie(
233        String,
234        GenericSender<Result<Vec<Serde<Cookie<'static>>>, ErrorStatus>>,
235    ),
236    GetCookies(GenericSender<Result<Vec<Serde<Cookie<'static>>>, ErrorStatus>>),
237    GetElementAttribute(
238        String,
239        String,
240        GenericSender<Result<Option<String>, ErrorStatus>>,
241    ),
242    GetElementProperty(String, String, GenericSender<Result<JSValue, ErrorStatus>>),
243    GetElementCSS(String, String, GenericSender<Result<String, ErrorStatus>>),
244    GetElementRect(String, GenericSender<Result<UntypedRect<f64>, ErrorStatus>>),
245    GetElementTagName(String, GenericSender<Result<String, ErrorStatus>>),
246    GetElementText(String, GenericSender<Result<String, ErrorStatus>>),
247    GetElementInViewCenterPoint(
248        String,
249        GenericOneshotSender<Result<Option<(i64, i64)>, ErrorStatus>>,
250    ),
251    ScrollAndGetBoundingClientRect(String, GenericSender<Result<UntypedRect<f32>, ErrorStatus>>),
252    GetBrowsingContextId(
253        WebDriverFrameId,
254        GenericSender<Result<BrowsingContextId, ErrorStatus>>,
255    ),
256    GetParentFrameId(GenericSender<Result<BrowsingContextId, ErrorStatus>>),
257    GetUrl(GenericSender<String>),
258    GetPageSource(GenericSender<Result<String, ErrorStatus>>),
259    IsEnabled(String, GenericSender<Result<bool, ErrorStatus>>),
260    IsSelected(String, GenericSender<Result<bool, ErrorStatus>>),
261    GetTitle(GenericSender<String>),
262    /// Deal with the case of input element for Element Send Keys, which does not send keys.
263    WillSendKeys(
264        String,
265        String,
266        bool,
267        GenericSender<Result<bool, ErrorStatus>>,
268    ),
269    SetProtocolHandlerAutomationMode(CustomHandlersAutomationMode),
270    SetPermission(
271        String,
272        SetPermissionState,
273        GenericOneshotSender<Result<(), ErrorStatus>>,
274    ),
275}
276
277pub type WebDriverJSResult = Result<JSValue, JavaScriptEvaluationError>;
278
279#[derive(Debug, Deserialize, Serialize)]
280pub enum WebDriverFrameId {
281    Short(u16),
282    Element(String),
283}
284
285#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
286pub enum WebDriverLoadStatus {
287    /// A navigation has started in the top-level browsing context.
288    NavigationStart,
289    /// A navigation stopped for any reason other than completing successfully.
290    NavigationStop,
291    /// The document's `readyState` is complete.
292    Complete,
293    /// The navigation is blocked by a user prompt.
294    Blocked,
295}
296
297#[derive(Clone, Debug, Deserialize, Serialize)]
298pub struct WebDriverLoadStatusMessage {
299    pub webview_id: WebViewId,
300    pub status: WebDriverLoadStatus,
301}
302
303/// A collection of [`GenericSender`]s that are used to asynchronously communicate
304/// to a WebDriver server with information about application state.
305#[derive(Clone, Default)]
306pub struct WebDriverSenders {
307    pub load_status_senders: FxHashMap<WebViewId, GenericSender<WebDriverLoadStatusMessage>>,
308    pub script_evaluation_interrupt_sender: Option<GenericSender<WebDriverJSResult>>,
309}