WebDriverConnection.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  1. /*
  2. * Copyright (c) 2022, Florent Castelli <florent.castelli@gmail.com>
  3. * Copyright (c) 2022, Sam Atkins <atkinssj@serenityos.org>
  4. * Copyright (c) 2022, Tobias Christiansen <tobyase@serenityos.org>
  5. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  6. * Copyright (c) 2022, Tim Flynn <trflynn89@serenityos.org>
  7. *
  8. * SPDX-License-Identifier: BSD-2-Clause
  9. */
  10. #include <AK/JsonObject.h>
  11. #include <AK/JsonValue.h>
  12. #include <AK/Vector.h>
  13. #include <LibJS/Runtime/Value.h>
  14. #include <LibWeb/CSS/PropertyID.h>
  15. #include <LibWeb/CSS/StyleProperties.h>
  16. #include <LibWeb/CSS/StyleValue.h>
  17. #include <LibWeb/DOM/Document.h>
  18. #include <LibWeb/DOM/Element.h>
  19. #include <LibWeb/Geometry/DOMRect.h>
  20. #include <LibWeb/HTML/AttributeNames.h>
  21. #include <LibWeb/HTML/BrowsingContext.h>
  22. #include <LibWeb/HTML/HTMLInputElement.h>
  23. #include <LibWeb/HTML/HTMLOptionElement.h>
  24. #include <LibWeb/Page/Page.h>
  25. #include <LibWeb/Platform/EventLoopPlugin.h>
  26. #include <LibWeb/Platform/Timer.h>
  27. #include <WebContent/ConnectionFromClient.h>
  28. #include <WebContent/PageHost.h>
  29. #include <WebContent/WebDriverConnection.h>
  30. namespace WebContent {
  31. static JsonValue make_success_response(JsonValue value)
  32. {
  33. JsonObject result;
  34. result.set("value", move(value));
  35. return result;
  36. }
  37. static JsonValue serialize_rect(Gfx::IntRect const& rect)
  38. {
  39. JsonObject serialized_rect = {};
  40. serialized_rect.set("x", rect.x());
  41. serialized_rect.set("y", rect.y());
  42. serialized_rect.set("width", rect.width());
  43. serialized_rect.set("height", rect.height());
  44. return make_success_response(move(serialized_rect));
  45. }
  46. static Gfx::IntRect compute_window_rect(Web::Page const& page)
  47. {
  48. return {
  49. page.window_position().x(),
  50. page.window_position().y(),
  51. page.window_size().width(),
  52. page.window_size().height()
  53. };
  54. }
  55. // https://w3c.github.io/webdriver/#dfn-calculate-the-absolute-position
  56. static Gfx::IntPoint calculate_absolute_position_of_element(Web::Page const& page, JS::NonnullGCPtr<Web::Geometry::DOMRect> rect)
  57. {
  58. // 1. Let rect be the value returned by calling getBoundingClientRect().
  59. // 2. Let window be the associated window of current top-level browsing context.
  60. auto const* window = page.top_level_browsing_context().active_window();
  61. // 3. Let x be (scrollX of window + rect’s x coordinate).
  62. auto x = (window ? static_cast<int>(window->scroll_x()) : 0) + static_cast<int>(rect->x());
  63. // 4. Let y be (scrollY of window + rect’s y coordinate).
  64. auto y = (window ? static_cast<int>(window->scroll_y()) : 0) + static_cast<int>(rect->y());
  65. // 5. Return a pair of (x, y).
  66. return { x, y };
  67. }
  68. static Gfx::IntRect calculate_absolute_rect_of_element(Web::Page const& page, Web::DOM::Element const& element)
  69. {
  70. auto bounding_rect = element.get_bounding_client_rect();
  71. auto coordinates = calculate_absolute_position_of_element(page, bounding_rect);
  72. return {
  73. coordinates.x(),
  74. coordinates.y(),
  75. static_cast<int>(bounding_rect->width()),
  76. static_cast<int>(bounding_rect->height())
  77. };
  78. }
  79. // https://w3c.github.io/webdriver/#dfn-get-or-create-a-web-element-reference
  80. static String get_or_create_a_web_element_reference(Web::DOM::Node const& element)
  81. {
  82. // FIXME: 1. For each known element of the current browsing context’s list of known elements:
  83. // FIXME: 1. If known element equals element, return success with known element’s web element reference.
  84. // FIXME: 2. Add element to the list of known elements of the current browsing context.
  85. // FIXME: 3. Return success with the element’s web element reference.
  86. return String::number(element.id());
  87. }
  88. // https://w3c.github.io/webdriver/#dfn-web-element-reference-object
  89. static JsonObject web_element_reference_object(Web::DOM::Node const& element)
  90. {
  91. // https://w3c.github.io/webdriver/#dfn-web-element-identifier
  92. static String const web_element_identifier = "element-6066-11e4-a52e-4f735466cecf"sv;
  93. // 1. Let identifier be the web element identifier.
  94. auto identifier = web_element_identifier;
  95. // 2. Let reference be the result of get or create a web element reference given element.
  96. auto reference = get_or_create_a_web_element_reference(element);
  97. // 3. Return a JSON Object initialized with a property with name identifier and value reference.
  98. JsonObject object;
  99. object.set("name"sv, identifier);
  100. object.set("value"sv, reference);
  101. return object;
  102. }
  103. // https://w3c.github.io/webdriver/#dfn-get-a-known-connected-element
  104. static ErrorOr<Web::DOM::Element*, Web::WebDriver::Error> get_known_connected_element(StringView element_id)
  105. {
  106. // NOTE: The whole concept of "connected elements" is not implemented yet. See get_or_create_a_web_element_reference().
  107. // For now the element is only represented by its ID.
  108. auto element = element_id.to_int();
  109. if (!element.has_value())
  110. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Element ID is not an integer");
  111. auto* node = Web::DOM::Node::from_id(*element);
  112. if (!node || !node->is_element())
  113. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchElement, String::formatted("Could not find element with ID: {}", element_id));
  114. return static_cast<Web::DOM::Element*>(node);
  115. }
  116. static ErrorOr<String, Web::WebDriver::Error> get_property(JsonValue const& payload, StringView key)
  117. {
  118. if (!payload.is_object())
  119. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload is not a JSON object");
  120. auto const* property = payload.as_object().get_ptr(key);
  121. if (!property)
  122. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, String::formatted("No property called '{}' present", key));
  123. if (!property->is_string())
  124. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, String::formatted("Property '{}' is not a String", key));
  125. return property->as_string();
  126. }
  127. ErrorOr<NonnullRefPtr<WebDriverConnection>> WebDriverConnection::connect(ConnectionFromClient& web_content_client, PageHost& page_host, String const& webdriver_ipc_path)
  128. {
  129. dbgln_if(WEBDRIVER_DEBUG, "Trying to connect to {}", webdriver_ipc_path);
  130. auto socket = TRY(Core::Stream::LocalSocket::connect(webdriver_ipc_path));
  131. dbgln_if(WEBDRIVER_DEBUG, "Connected to WebDriver");
  132. return adopt_nonnull_ref_or_enomem(new (nothrow) WebDriverConnection(move(socket), web_content_client, page_host));
  133. }
  134. WebDriverConnection::WebDriverConnection(NonnullOwnPtr<Core::Stream::LocalSocket> socket, ConnectionFromClient& web_content_client, PageHost& page_host)
  135. : IPC::ConnectionToServer<WebDriverClientEndpoint, WebDriverServerEndpoint>(*this, move(socket))
  136. , m_web_content_client(web_content_client)
  137. , m_page_host(page_host)
  138. {
  139. }
  140. // https://w3c.github.io/webdriver/#dfn-close-the-session
  141. void WebDriverConnection::close_session()
  142. {
  143. // 1. Set the webdriver-active flag to false.
  144. set_is_webdriver_active(false);
  145. // 2. An endpoint node must close any top-level browsing contexts associated with the session, without prompting to unload.
  146. m_page_host.page().top_level_browsing_context().close();
  147. }
  148. void WebDriverConnection::set_is_webdriver_active(bool is_webdriver_active)
  149. {
  150. m_page_host.set_is_webdriver_active(is_webdriver_active);
  151. }
  152. // 10.1 Navigate To, https://w3c.github.io/webdriver/#navigate-to
  153. Messages::WebDriverClient::NavigateToResponse WebDriverConnection::navigate_to(JsonValue const& payload)
  154. {
  155. dbgln_if(WEBDRIVER_DEBUG, "WebDriverConnection::navigate_to {}", payload);
  156. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  157. TRY(ensure_open_top_level_browsing_context());
  158. // 2. Let url be the result of getting the property url from the parameters argument.
  159. if (!payload.is_object() || !payload.as_object().has_string("url"sv))
  160. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload doesn't have a string `url`"sv);
  161. URL url(payload.as_object().get_ptr("url"sv)->as_string());
  162. // FIXME: 3. If url is not an absolute URL or is not an absolute URL with fragment or not a local scheme, return error with error code invalid argument.
  163. // FIXME: 4. Handle any user prompts and return its value if it is an error.
  164. // FIXME: 5. Let current URL be the current top-level browsing context’s active document’s URL.
  165. // FIXME: 6. If current URL and url do not have the same absolute URL:
  166. // FIXME: a. If timer has not been started, start a timer. If this algorithm has not completed before timer reaches the session’s session page load timeout in milliseconds, return an error with error code timeout.
  167. // 7. Navigate the current top-level browsing context to url.
  168. m_page_host.page().load(url);
  169. // FIXME: 8. If url is special except for file and current URL and URL do not have the same absolute URL:
  170. // FIXME: a. Try to wait for navigation to complete.
  171. // FIXME: b. Try to run the post-navigation checks.
  172. // FIXME: 9. Set the current browsing context with the current top-level browsing context.
  173. // FIXME: 10. If the current top-level browsing context contains a refresh state pragma directive of time 1 second or less, wait until the refresh timeout has elapsed, a new navigate has begun, and return to the first step of this algorithm.
  174. // 11. Return success with data null.
  175. return make_success_response({});
  176. }
  177. // 10.2 Get Current URL, https://w3c.github.io/webdriver/#get-current-url
  178. Messages::WebDriverClient::GetCurrentUrlResponse WebDriverConnection::get_current_url()
  179. {
  180. dbgln_if(WEBDRIVER_DEBUG, "WebDriverConnection::get_current_url");
  181. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  182. TRY(ensure_open_top_level_browsing_context());
  183. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  184. // 3. Let url be the serialization of the current top-level browsing context’s active document’s document URL.
  185. auto url = m_page_host.page().top_level_browsing_context().active_document()->url().to_string();
  186. // 4. Return success with data url.
  187. return make_success_response(url);
  188. }
  189. // 11.8.1 Get Window Rect, https://w3c.github.io/webdriver/#dfn-get-window-rect
  190. Messages::WebDriverClient::GetWindowRectResponse WebDriverConnection::get_window_rect()
  191. {
  192. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  193. TRY(ensure_open_top_level_browsing_context());
  194. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  195. // 3. Return success with data set to the WindowRect object for the current top-level browsing context.
  196. return serialize_rect(compute_window_rect(m_page_host.page()));
  197. }
  198. // 11.8.2 Set Window Rect, https://w3c.github.io/webdriver/#dfn-set-window-rect
  199. Messages::WebDriverClient::SetWindowRectResponse WebDriverConnection::set_window_rect(JsonValue const& payload)
  200. {
  201. if (!payload.is_object())
  202. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload is not a JSON object");
  203. auto const& properties = payload.as_object();
  204. auto resolve_property = [](auto name, auto const* property, auto min, auto max) -> ErrorOr<Optional<i32>, Web::WebDriver::Error> {
  205. if (!property)
  206. return Optional<i32> {};
  207. if (!property->is_number())
  208. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, String::formatted("Property '{}' is not a Number", name));
  209. auto number = property->template to_number<i64>();
  210. if (number < min)
  211. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, String::formatted("Property '{}' value {} exceeds the minimum allowed value {}", name, number, min));
  212. if (number > max)
  213. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, String::formatted("Property '{}' value {} exceeds the maximum allowed value {}", name, number, max));
  214. return static_cast<i32>(number);
  215. };
  216. // 1. Let width be the result of getting a property named width from the parameters argument, else let it be null.
  217. auto const* width_property = properties.get_ptr("width"sv);
  218. // 2. Let height be the result of getting a property named height from the parameters argument, else let it be null.
  219. auto const* height_property = properties.get_ptr("height"sv);
  220. // 3. Let x be the result of getting a property named x from the parameters argument, else let it be null.
  221. auto const* x_property = properties.get_ptr("x"sv);
  222. // 4. Let y be the result of getting a property named y from the parameters argument, else let it be null.
  223. auto const* y_property = properties.get_ptr("y"sv);
  224. // 5. If width or height is neither null nor a Number from 0 to 2^31 − 1, return error with error code invalid argument.
  225. auto width = TRY(resolve_property("width"sv, width_property, 0, NumericLimits<i32>::max()));
  226. auto height = TRY(resolve_property("height"sv, height_property, 0, NumericLimits<i32>::max()));
  227. // 6. If x or y is neither null nor a Number from −(2^31) to 2^31 − 1, return error with error code invalid argument.
  228. auto x = TRY(resolve_property("x"sv, x_property, NumericLimits<i32>::min(), NumericLimits<i32>::max()));
  229. auto y = TRY(resolve_property("y"sv, y_property, NumericLimits<i32>::min(), NumericLimits<i32>::max()));
  230. // 7. If the remote end does not support the Set Window Rect command for the current top-level browsing context for any reason, return error with error code unsupported operation.
  231. // 8. If the current top-level browsing context is no longer open, return error with error code no such window.
  232. TRY(ensure_open_top_level_browsing_context());
  233. // FIXME: 9. Handle any user prompts and return its value if it is an error.
  234. // FIXME: 10. Fully exit fullscreen.
  235. // 11. Restore the window.
  236. restore_the_window();
  237. Gfx::IntRect window_rect;
  238. // 11. If width and height are not null:
  239. if (width.has_value() && height.has_value()) {
  240. // a. Set the width, in CSS pixels, of the operating system window containing the current top-level browsing context, including any browser chrome and externally drawn window decorations to a value that is as close as possible to width.
  241. // b. Set the height, in CSS pixels, of the operating system window containing the current top-level browsing context, including any browser chrome and externally drawn window decorations to a value that is as close as possible to height.
  242. auto size = m_web_content_client.did_request_resize_window({ *width, *height });
  243. window_rect.set_size(size);
  244. } else {
  245. window_rect.set_size(m_page_host.page().window_size());
  246. }
  247. // 12. If x and y are not null:
  248. if (x.has_value() && y.has_value()) {
  249. // a. Run the implementation-specific steps to set the position of the operating system level window containing the current top-level browsing context to the position given by the x and y coordinates.
  250. auto position = m_web_content_client.did_request_reposition_window({ *x, *y });
  251. window_rect.set_location(position);
  252. } else {
  253. window_rect.set_location(m_page_host.page().window_position());
  254. }
  255. // 14. Return success with data set to the WindowRect object for the current top-level browsing context.
  256. return serialize_rect(window_rect);
  257. }
  258. // 11.8.3 Maximize Window, https://w3c.github.io/webdriver/#dfn-maximize-window
  259. Messages::WebDriverClient::MaximizeWindowResponse WebDriverConnection::maximize_window()
  260. {
  261. // 1. If the remote end does not support the Maximize Window command for the current top-level browsing context for any reason, return error with error code unsupported operation.
  262. // 2. If the current top-level browsing context is no longer open, return error with error code no such window.
  263. TRY(ensure_open_top_level_browsing_context());
  264. // FIXME: 3. Handle any user prompts and return its value if it is an error.
  265. // FIXME: 4. Fully exit fullscreen.
  266. // 5. Restore the window.
  267. restore_the_window();
  268. // 6. Maximize the window of the current top-level browsing context.
  269. auto window_rect = maximize_the_window();
  270. // 7. Return success with data set to the WindowRect object for the current top-level browsing context.
  271. return serialize_rect(window_rect);
  272. }
  273. // 11.8.4 Minimize Window, https://w3c.github.io/webdriver/#minimize-window
  274. Messages::WebDriverClient::MinimizeWindowResponse WebDriverConnection::minimize_window()
  275. {
  276. // 1. If the remote end does not support the Minimize Window command for the current top-level browsing context for any reason, return error with error code unsupported operation.
  277. // 2. If the current top-level browsing context is no longer open, return error with error code no such window.
  278. TRY(ensure_open_top_level_browsing_context());
  279. // FIXME: 3. Handle any user prompts and return its value if it is an error.
  280. // FIXME: 4. Fully exit fullscreen.
  281. // 5. Iconify the window.
  282. auto window_rect = iconify_the_window();
  283. // 6. Return success with data set to the WindowRect object for the current top-level browsing context.
  284. return serialize_rect(window_rect);
  285. }
  286. // 12.3.2 Find Element, https://w3c.github.io/webdriver/#dfn-find-element
  287. Messages::WebDriverClient::FindElementResponse WebDriverConnection::find_element(JsonValue const& payload)
  288. {
  289. // 1. Let location strategy be the result of getting a property called "using".
  290. auto location_strategy_string = TRY(get_property(payload, "using"sv));
  291. auto location_strategy = Web::WebDriver::location_strategy_from_string(location_strategy_string);
  292. // 2. If location strategy is not present as a keyword in the table of location strategies, return error with error code invalid argument.
  293. if (!location_strategy.has_value())
  294. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, String::formatted("Location strategy '{}' is invalid", location_strategy_string));
  295. // 3. Let selector be the result of getting a property called "value".
  296. // 4. If selector is undefined, return error with error code invalid argument.
  297. auto selector = TRY(get_property(payload, "value"sv));
  298. // 5. If the current browsing context is no longer open, return error with error code no such window.
  299. TRY(ensure_open_top_level_browsing_context());
  300. // FIXME: 6. Handle any user prompts and return its value if it is an error.
  301. // 7. Let start node be the current browsing context’s document element.
  302. auto* start_node = m_page_host.page().top_level_browsing_context().active_document();
  303. // 8. If start node is null, return error with error code no such element.
  304. if (!start_node)
  305. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchElement, "document element does not exist"sv);
  306. // 9. Let result be the result of trying to Find with start node, location strategy, and selector.
  307. auto result = TRY(find(*start_node, *location_strategy, selector));
  308. // 10. If result is empty, return error with error code no such element. Otherwise, return the first element of result.
  309. if (result.is_empty())
  310. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchElement, "The requested element does not exist"sv);
  311. return make_success_response(result.at(0));
  312. }
  313. // 12.3.3 Find Elements, https://w3c.github.io/webdriver/#dfn-find-elements
  314. Messages::WebDriverClient::FindElementsResponse WebDriverConnection::find_elements(JsonValue const& payload)
  315. {
  316. // 1. Let location strategy be the result of getting a property called "using".
  317. auto location_strategy_string = TRY(get_property(payload, "using"sv));
  318. auto location_strategy = Web::WebDriver::location_strategy_from_string(location_strategy_string);
  319. // 2. If location strategy is not present as a keyword in the table of location strategies, return error with error code invalid argument.
  320. if (!location_strategy.has_value())
  321. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, String::formatted("Location strategy '{}' is invalid", location_strategy_string));
  322. // 3. Let selector be the result of getting a property called "value".
  323. // 4. If selector is undefined, return error with error code invalid argument.
  324. auto selector = TRY(get_property(payload, "value"sv));
  325. // 5. If the current browsing context is no longer open, return error with error code no such window.
  326. TRY(ensure_open_top_level_browsing_context());
  327. // FIXME: 6. Handle any user prompts and return its value if it is an error.
  328. // 7. Let start node be the current browsing context’s document element.
  329. auto* start_node = m_page_host.page().top_level_browsing_context().active_document();
  330. // 8. If start node is null, return error with error code no such element.
  331. if (!start_node)
  332. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchElement, "document element does not exist"sv);
  333. // 9. Return the result of trying to Find with start node, location strategy, and selector.
  334. auto result = TRY(find(*start_node, *location_strategy, selector));
  335. return make_success_response(move(result));
  336. }
  337. // 12.3.4 Find Element From Element, https://w3c.github.io/webdriver/#dfn-find-element-from-element
  338. Messages::WebDriverClient::FindElementFromElementResponse WebDriverConnection::find_element_from_element(JsonValue const& payload, String const& element_id)
  339. {
  340. // 1. Let location strategy be the result of getting a property called "using".
  341. auto location_strategy_string = TRY(get_property(payload, "using"sv));
  342. auto location_strategy = Web::WebDriver::location_strategy_from_string(location_strategy_string);
  343. // 2. If location strategy is not present as a keyword in the table of location strategies, return error with error code invalid argument.
  344. if (!location_strategy.has_value())
  345. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, String::formatted("Location strategy '{}' is invalid", location_strategy_string));
  346. // 3. Let selector be the result of getting a property called "value".
  347. // 4. If selector is undefined, return error with error code invalid argument.
  348. auto selector = TRY(get_property(payload, "value"sv));
  349. // 5. If the current browsing context is no longer open, return error with error code no such window.
  350. TRY(ensure_open_top_level_browsing_context());
  351. // FIXME: 6. Handle any user prompts and return its value if it is an error.
  352. // 7. Let start node be the result of trying to get a known connected element with url variable element id.
  353. auto* start_node = TRY(get_known_connected_element(element_id));
  354. // 8. Let result be the value of trying to Find with start node, location strategy, and selector.
  355. auto result = TRY(find(*start_node, *location_strategy, selector));
  356. // 9. If result is empty, return error with error code no such element. Otherwise, return the first element of result.
  357. if (result.is_empty())
  358. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchElement, "The requested element does not exist"sv);
  359. return make_success_response(result.at(0));
  360. }
  361. // 12.3.5 Find Elements From Element, https://w3c.github.io/webdriver/#dfn-find-elements-from-element
  362. Messages::WebDriverClient::FindElementsFromElementResponse WebDriverConnection::find_elements_from_element(JsonValue const& payload, String const& element_id)
  363. {
  364. // 1. Let location strategy be the result of getting a property called "using".
  365. auto location_strategy_string = TRY(get_property(payload, "using"sv));
  366. auto location_strategy = Web::WebDriver::location_strategy_from_string(location_strategy_string);
  367. // 2. If location strategy is not present as a keyword in the table of location strategies, return error with error code invalid argument.
  368. if (!location_strategy.has_value())
  369. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, String::formatted("Location strategy '{}' is invalid", location_strategy_string));
  370. // 3. Let selector be the result of getting a property called "value".
  371. // 4. If selector is undefined, return error with error code invalid argument.
  372. auto selector = TRY(get_property(payload, "value"sv));
  373. // 5. If the current browsing context is no longer open, return error with error code no such window.
  374. TRY(ensure_open_top_level_browsing_context());
  375. // FIXME: 6. Handle any user prompts and return its value if it is an error.
  376. // 7. Let start node be the result of trying to get a known connected element with url variable element id.
  377. auto* start_node = TRY(get_known_connected_element(element_id));
  378. // 8. Return the result of trying to Find with start node, location strategy, and selector.
  379. auto result = TRY(find(*start_node, *location_strategy, selector));
  380. return make_success_response(move(result));
  381. }
  382. // 12.4.1 Is Element Selected, https://w3c.github.io/webdriver/#dfn-is-element-selected
  383. Messages::WebDriverClient::IsElementSelectedResponse WebDriverConnection::is_element_selected(String const& element_id)
  384. {
  385. // 1. If the current browsing context is no longer open, return error with error code no such window.
  386. TRY(ensure_open_top_level_browsing_context());
  387. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  388. // 3. Let element be the result of trying to get a known connected element with url variable element id.
  389. auto* element = TRY(get_known_connected_element(element_id));
  390. // 4. Let selected be the value corresponding to the first matching statement:
  391. bool selected = false;
  392. // element is an input element with a type attribute in the Checkbox- or Radio Button state
  393. if (is<Web::HTML::HTMLInputElement>(*element)) {
  394. // -> The result of element’s checkedness.
  395. auto& input = static_cast<Web::HTML::HTMLInputElement&>(*element);
  396. using enum Web::HTML::HTMLInputElement::TypeAttributeState;
  397. if (input.type_state() == Checkbox || input.type_state() == RadioButton)
  398. selected = input.checked();
  399. }
  400. // element is an option element
  401. else if (is<Web::HTML::HTMLOptionElement>(*element)) {
  402. // -> The result of element’s selectedness.
  403. selected = static_cast<Web::HTML::HTMLOptionElement&>(*element).selected();
  404. }
  405. // Otherwise
  406. // -> False.
  407. // 5. Return success with data selected.
  408. return make_success_response(selected);
  409. }
  410. // 12.4.2 Get Element Attribute, https://w3c.github.io/webdriver/#dfn-get-element-attribute
  411. Messages::WebDriverClient::GetElementAttributeResponse WebDriverConnection::get_element_attribute(String const& element_id, String const& name)
  412. {
  413. // 1. If the current browsing context is no longer open, return error with error code no such window.
  414. TRY(ensure_open_top_level_browsing_context());
  415. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  416. // 3. Let element be the result of trying to get a known connected element with url variable element id.
  417. auto* element = TRY(get_known_connected_element(element_id));
  418. // 4. Let result be the result of the first matching condition:
  419. Optional<String> result;
  420. // -> If name is a boolean attribute
  421. if (Web::HTML::is_boolean_attribute(name)) {
  422. // "true" (string) if the element has the attribute, otherwise null.
  423. if (element->has_attribute(name))
  424. result = "true"sv;
  425. }
  426. // -> Otherwise
  427. else {
  428. // The result of getting an attribute by name name.
  429. result = element->get_attribute(name);
  430. }
  431. // 5. Return success with data result.
  432. if (result.has_value())
  433. return make_success_response(result.release_value());
  434. return make_success_response({});
  435. }
  436. // 12.4.3 Get Element Property, https://w3c.github.io/webdriver/#dfn-get-element-property
  437. Messages::WebDriverClient::GetElementPropertyResponse WebDriverConnection::get_element_property(String const& element_id, String const& name)
  438. {
  439. // 1. If the current browsing context is no longer open, return error with error code no such window.
  440. TRY(ensure_open_top_level_browsing_context());
  441. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  442. // 3. Let element be the result of trying to get a known connected element with url variable element id.
  443. auto* element = TRY(get_known_connected_element(element_id));
  444. Optional<String> result;
  445. // 4. Let property be the result of calling the Object.[[GetProperty]](name) on element.
  446. if (auto property_or_error = element->get(name); !property_or_error.is_throw_completion()) {
  447. auto property = property_or_error.release_value();
  448. // 5. Let result be the value of property if not undefined, or null.
  449. if (!property.is_undefined()) {
  450. if (auto string_or_error = property.to_string(element->vm()); !string_or_error.is_error())
  451. result = string_or_error.release_value();
  452. }
  453. }
  454. // 6. Return success with data result.
  455. if (result.has_value())
  456. return make_success_response(result.release_value());
  457. return make_success_response({});
  458. }
  459. // 12.4.4 Get Element CSS Value, https://w3c.github.io/webdriver/#dfn-get-element-css-value
  460. Messages::WebDriverClient::GetElementCssValueResponse WebDriverConnection::get_element_css_value(String const& element_id, String const& name)
  461. {
  462. // 1. If the current browsing context is no longer open, return error with error code no such window.
  463. TRY(ensure_open_top_level_browsing_context());
  464. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  465. // 3. Let element be the result of trying to get a known connected element with url variable element id.
  466. auto* element = TRY(get_known_connected_element(element_id));
  467. // 4. Let computed value be the result of the first matching condition:
  468. String computed_value;
  469. // -> current browsing context’s active document’s type is not "xml"
  470. if (!m_page_host.page().top_level_browsing_context().active_document()->is_xml_document()) {
  471. // computed value of parameter property name from element’s style declarations. property name is obtained from url variables.
  472. auto property = Web::CSS::property_id_from_string(name);
  473. if (auto* computed_values = element->computed_css_values())
  474. computed_value = computed_values->property(property)->to_string();
  475. }
  476. // -> Otherwise
  477. else {
  478. // "" (empty string)
  479. computed_value = String::empty();
  480. }
  481. // 5. Return success with data computed value.
  482. return make_success_response(move(computed_value));
  483. }
  484. // 12.4.5 Get Element Text, https://w3c.github.io/webdriver/#dfn-get-element-text
  485. Messages::WebDriverClient::GetElementTextResponse WebDriverConnection::get_element_text(String const& element_id)
  486. {
  487. // 1. If the current browsing context is no longer open, return error with error code no such window.
  488. TRY(ensure_open_top_level_browsing_context());
  489. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  490. // 3. Let element be the result of trying to get a known connected element with url variable element id.
  491. auto* element = TRY(get_known_connected_element(element_id));
  492. // 4. Let rendered text be the result of performing implementation-specific steps whose result is exactly the same as the result of a Function.[[Call]](null, element) with bot.dom.getVisibleText as the this value.
  493. auto rendered_text = element->text_content();
  494. // 5. Return success with data rendered text.
  495. return make_success_response(move(rendered_text));
  496. }
  497. // 12.4.6 Get Element Tag Name, https://w3c.github.io/webdriver/#dfn-get-element-tag-name
  498. Messages::WebDriverClient::GetElementTagNameResponse WebDriverConnection::get_element_tag_name(String const& element_id)
  499. {
  500. // 1. If the current browsing context is no longer open, return error with error code no such window.
  501. TRY(ensure_open_top_level_browsing_context());
  502. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  503. // 3. Let element be the result of trying to get a known connected element with url variable element id.
  504. auto* element = TRY(get_known_connected_element(element_id));
  505. // 4. Let qualified name be the result of getting element’s tagName IDL attribute.
  506. auto qualified_name = element->tag_name();
  507. // 5. Return success with data qualified name.
  508. return make_success_response(move(qualified_name));
  509. }
  510. // 12.4.7 Get Element Rect, https://w3c.github.io/webdriver/#dfn-get-element-rect
  511. Messages::WebDriverClient::GetElementRectResponse WebDriverConnection::get_element_rect(String const& element_id)
  512. {
  513. // 1. If the current browsing context is no longer open, return error with error code no such window.
  514. TRY(ensure_open_top_level_browsing_context());
  515. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  516. // 3. Let element be the result of trying to get a known connected element with url variable element id.
  517. auto* element = TRY(get_known_connected_element(element_id));
  518. // 4. Calculate the absolute position of element and let it be coordinates.
  519. // 5. Let rect be element’s bounding rectangle.
  520. auto rect = calculate_absolute_rect_of_element(m_page_host.page(), *element);
  521. // 6. Let body be a new JSON Object initialized with:
  522. // "x"
  523. // The first value of coordinates.
  524. // "y"
  525. // The second value of coordinates.
  526. // "width"
  527. // Value of rect’s width dimension.
  528. // "height"
  529. // Value of rect’s height dimension.
  530. auto body = serialize_rect(rect);
  531. // 7. Return success with data body.
  532. return body;
  533. }
  534. // https://w3c.github.io/webdriver/#dfn-no-longer-open
  535. ErrorOr<void, Web::WebDriver::Error> WebDriverConnection::ensure_open_top_level_browsing_context()
  536. {
  537. // A browsing context is said to be no longer open if it has been discarded.
  538. if (m_page_host.page().top_level_browsing_context().has_been_discarded())
  539. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchWindow, "Window not found"sv);
  540. return {};
  541. }
  542. // https://w3c.github.io/webdriver/#dfn-restore-the-window
  543. void WebDriverConnection::restore_the_window()
  544. {
  545. // To restore the window, given an operating system level window with an associated top-level browsing context, run implementation-specific steps to restore or unhide the window to the visible screen.
  546. m_web_content_client.async_did_request_restore_window();
  547. // Do not return from this operation until the visibility state of the top-level browsing context’s active document has reached the visible state, or until the operation times out.
  548. // FIXME: Implement timeouts.
  549. Web::Platform::EventLoopPlugin::the().spin_until([this]() {
  550. auto state = m_page_host.page().top_level_browsing_context().system_visibility_state();
  551. return state == Web::HTML::VisibilityState::Visible;
  552. });
  553. }
  554. // https://w3c.github.io/webdriver/#dfn-maximize-the-window
  555. Gfx::IntRect WebDriverConnection::maximize_the_window()
  556. {
  557. // To maximize the window, given an operating system level window with an associated top-level browsing context, run the implementation-specific steps to transition the operating system level window into the maximized window state.
  558. auto rect = m_web_content_client.did_request_maximize_window();
  559. // Return when the window has completed the transition, or within an implementation-defined timeout.
  560. return rect;
  561. }
  562. // https://w3c.github.io/webdriver/#dfn-iconify-the-window
  563. Gfx::IntRect WebDriverConnection::iconify_the_window()
  564. {
  565. // To iconify the window, given an operating system level window with an associated top-level browsing context, run implementation-specific steps to iconify, minimize, or hide the window from the visible screen.
  566. auto rect = m_web_content_client.did_request_minimize_window();
  567. // Do not return from this operation until the visibility state of the top-level browsing context’s active document has reached the hidden state, or until the operation times out.
  568. // FIXME: Implement timeouts.
  569. Web::Platform::EventLoopPlugin::the().spin_until([this]() {
  570. auto state = m_page_host.page().top_level_browsing_context().system_visibility_state();
  571. return state == Web::HTML::VisibilityState::Hidden;
  572. });
  573. return rect;
  574. }
  575. // https://w3c.github.io/webdriver/#dfn-find
  576. ErrorOr<JsonArray, Web::WebDriver::Error> WebDriverConnection::find(Web::DOM::ParentNode& start_node, Web::WebDriver::LocationStrategy using_, StringView value)
  577. {
  578. // FIXME: 1. Let end time be the current time plus the session implicit wait timeout.
  579. // 2. Let location strategy be equal to using.
  580. auto location_strategy = using_;
  581. // 3. Let selector be equal to value.
  582. auto selector = value;
  583. // 4. Let elements returned be the result of trying to call the relevant element location strategy with arguments start node, and selector.
  584. auto elements = Web::WebDriver::invoke_location_strategy(location_strategy, start_node, selector);
  585. // 5. If a DOMException, SyntaxError, XPathException, or other error occurs during the execution of the element location strategy, return error invalid selector.
  586. if (elements.is_error())
  587. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidSelector, String::formatted("The location strategy could not finish: {}", elements.error().message));
  588. // FIXME: 6. If elements returned is empty and the current time is less than end time return to step 4. Otherwise, continue to the next step.
  589. // 7. Let result be an empty JSON List.
  590. JsonArray result;
  591. result.ensure_capacity(elements.value()->length());
  592. // 8. For each element in elements returned, append the web element reference object for element, to result.
  593. for (size_t i = 0; i < elements.value()->length(); ++i)
  594. result.append(web_element_reference_object(*elements.value()->item(i)));
  595. // 9. Return success with data result.
  596. return result;
  597. }
  598. }