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
|
/*
* Copyright (C) 2025 Apple Inc. All rights reserved.
* Copyright (C) 2025 Microsoft Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "BidiBrowsingContextAgent.h"
#if ENABLE(WEBDRIVER_BIDI)
#include "AutomationProtocolObjects.h"
#include "FrameTreeNodeData.h"
#include "Logging.h"
#include "PageLoadState.h"
#include "WebAutomationSession.h"
#include "WebAutomationSessionMacros.h"
#include "WebDriverBidiProtocolObjects.h"
#include "WebFrameProxy.h"
#include "WebPageProxy.h"
#include "WebProcessPool.h"
#include <JavaScriptCore/MathCommon.h>
#include <wtf/Ref.h>
#include <wtf/Unexpected.h>
#include <wtf/Vector.h>
#include <wtf/text/WTFString.h>
namespace WebKit {
using namespace Inspector;
using BrowsingContext = Inspector::Protocol::BidiBrowsingContext::BrowsingContext;
using ReadinessState = Inspector::Protocol::BidiBrowsingContext::ReadinessState;
using PageLoadStrategy = Inspector::Protocol::Automation::PageLoadStrategy;
using UserPromptType = Inspector::Protocol::BidiBrowsingContext::UserPromptType;
using UserPromptHandlerType = Inspector::Protocol::BidiSession::UserPromptHandlerType;
WTF_MAKE_TZONE_ALLOCATED_IMPL(BidiBrowsingContextAgent);
BidiBrowsingContextAgent::BidiBrowsingContextAgent(WebAutomationSession& session, BackendDispatcher& backendDispatcher)
: m_session(session)
, m_browsingContextDomainDispatcher(BidiBrowsingContextBackendDispatcher::create(backendDispatcher, this))
{
}
BidiBrowsingContextAgent::~BidiBrowsingContextAgent() = default;
void BidiBrowsingContextAgent::activate(const BrowsingContext& browsingContext, CommandCallback<void>&& callback)
{
RefPtr session = m_session.get();
ASYNC_FAIL_WITH_PREDEFINED_ERROR_IF(!session, InternalError);
RefPtr webPageProxy = session->webPageProxyForHandle(browsingContext);
ASYNC_FAIL_WITH_PREDEFINED_ERROR_IF(!webPageProxy, WindowNotFound);
// FIXME: detect non-top level browsing contexts, returning `invalid argument`.
session->switchToBrowsingContext(browsingContext, emptyString(), [callback = WTFMove(callback)](CommandResult<void>&& result) {
if (!result) {
callback(makeUnexpected(result.error()));
return;
}
callback({ });
});
}
void BidiBrowsingContextAgent::close(const BrowsingContext& browsingContext, std::optional<bool>&& optionalPromptUnload, CommandCallback<void>&& callback)
{
RefPtr session = m_session.get();
ASYNC_FAIL_WITH_PREDEFINED_ERROR_IF(!session, InternalError);
// FIXME: implement `promptUnload` option.
// FIXME: raise `invalid argument` if `browsingContext` is not a top-level traversable.
RefPtr webPageProxy = session->webPageProxyForHandle(browsingContext);
ASYNC_FAIL_WITH_PREDEFINED_ERROR_IF(!webPageProxy, FrameNotFound);
session->closeBrowsingContext(browsingContext, WTFMove(callback));
}
static constexpr Inspector::Protocol::Automation::BrowsingContextPresentation defaultBrowsingContextPresentation = Inspector::Protocol::Automation::BrowsingContextPresentation::Tab;
static Inspector::Protocol::Automation::BrowsingContextPresentation browsingContextPresentationFromCreateType(Inspector::Protocol::BidiBrowsingContext::CreateType createType)
{
switch (createType) {
case Inspector::Protocol::BidiBrowsingContext::CreateType::Tab:
return Inspector::Protocol::Automation::BrowsingContextPresentation::Tab;
case Inspector::Protocol::BidiBrowsingContext::CreateType::Window:
return Inspector::Protocol::Automation::BrowsingContextPresentation::Window;
}
ASSERT_NOT_REACHED();
return defaultBrowsingContextPresentation;
}
void BidiBrowsingContextAgent::create(Inspector::Protocol::BidiBrowsingContext::CreateType createType, const BrowsingContext& optionalReferenceContext, std::optional<bool>&& optionalBackground, const String& optionalUserContext, CommandCallback<BrowsingContext>&& callback)
{
RefPtr session = m_session.get();
ASYNC_FAIL_WITH_PREDEFINED_ERROR_IF(!session, InternalError);
// FIXME: implement `referenceContext` option.
// FIXME: implement `background` option.
// FIXME: implement `userContext` option.
session->createBrowsingContext(browsingContextPresentationFromCreateType(createType), [callback = WTFMove(callback)](CommandResultOf<BrowsingContext, Inspector::Protocol::Automation::BrowsingContextPresentation>&& result) {
if (!result) {
callback(makeUnexpected(result.error()));
return;
}
auto [resultContext, resultPresentation] = WTFMove(result.value());
callback(WTFMove(resultContext));
});
}
Inspector::Protocol::BidiBrowsingContext::BrowsingContext BidiBrowsingContextAgent::getBrowsingContextID(const WebCore::FrameIdentifier& frameID) const
{
RefPtr session = m_session.get();
if (!session)
return { };
if (RefPtr frame = WebFrameProxy::webFrame(frameID); frame && frame->isMainFrame()) {
if (RefPtr page = frame->page())
return session->handleForWebPageProxy(*page);
return WTF::emptyString();
}
return session->handleForWebFrameID(frameID);
}
Ref<Inspector::Protocol::BidiBrowsingContext::Info> BidiBrowsingContextAgent::getNavigableInfo(const WebKit::FrameTreeNodeData& tree, std::optional<uint64_t> maxDepth, IncludeParentID includeParentID)
{
// https://w3c.github.io/webdriver-bidi/#get-the-navigable-info
// FIXME: Properly support different user contexts, which will likely map to different WebAutomationSessions.
// https://bugs.webkit.org/show_bug.cgi?id=288104
auto info = Inspector::Protocol::BidiBrowsingContext::Info::create()
.setContext(getBrowsingContextID(tree.info.frameID))
.setUrl(tree.info.request.url().string())
.setClientWindow("placeholder_window"_s)
.setUserContext("default"_s)
.setChildrenIsNull()
.setOriginalOpenerIsNull()
.release();
// FIXME: Support originalOpener attribute.
// https://w3c.github.io/webdriver-bidi/#original-opener
if (includeParentID == IncludeParentID::Yes) {
if (tree.info.parentFrameID)
info->setParent(getBrowsingContextID(tree.info.parentFrameID.value()));
else
info->setParentIsNull();
}
if (maxDepth && !*maxDepth) {
info->setChildrenIsNull();
return info;
}
auto childrenInfo = JSON::ArrayOf<Inspector::Protocol::BidiBrowsingContext::Info>::create();
auto newDepth = maxDepth ? std::optional<uint64_t>(*maxDepth - 1) : std::nullopt;
for (auto& child : tree.children)
childrenInfo->addItem(getNavigableInfo(child, newDepth, IncludeParentID::No));
info->setChildren(WTFMove(childrenInfo));
return info;
}
// Recursively traverses the frame tree of the given pages, one page at a time.
// We need such recursion because we need to wait for the frame tree of the current page to be fully processed before moving on to the next page.
void BidiBrowsingContextAgent::getNextTree(Vector<Ref<WebPageProxy>>&& pagesToProcess, Ref<JSON::ArrayOf<Inspector::Protocol::BidiBrowsingContext::Info>> resultsObject, std::optional<uint64_t> maxDepth, CommandCallback<Ref<JSON::ArrayOf<Inspector::Protocol::BidiBrowsingContext::Info>>>&& callback)
{
if (pagesToProcess.isEmpty()) {
callback(WTFMove(resultsObject));
return;
}
Ref webPageProxy = pagesToProcess.takeLast();
webPageProxy->getAllFrameTrees([this, pagesToProcess = WTFMove(pagesToProcess), resultsObject = WTFMove(resultsObject), callback = WTFMove(callback), maxDepth, protectedPage = Ref { webPageProxy }](Vector<WebKit::FrameTreeNodeData>&& trees) mutable {
for (auto& tree : trees) {
auto infoTree = getNavigableInfo(tree, maxDepth, IncludeParentID::Yes);
resultsObject->addItem(WTFMove(infoTree));
}
getNextTree(WTFMove(pagesToProcess), WTFMove(resultsObject), maxDepth, WTFMove(callback));
});
}
void BidiBrowsingContextAgent::getTree(const BrowsingContext& optionalRoot, std::optional<double>&& optionalMaxDepth, CommandCallback<Ref<JSON::ArrayOf<Inspector::Protocol::BidiBrowsingContext::Info>>>&& callback)
{
// https://w3c.github.io/webdriver-bidi/#command-browsingContext-getTree
RefPtr session = m_session.get();
ASYNC_FAIL_WITH_PREDEFINED_ERROR_IF(!session, InternalError);
std::optional<uint64_t> maxDepth = std::nullopt;
if (optionalMaxDepth) {
ASYNC_FAIL_WITH_PREDEFINED_ERROR_IF(*optionalMaxDepth < 0, InvalidParameter);
ASYNC_FAIL_WITH_PREDEFINED_ERROR_IF(std::floor(*optionalMaxDepth) != *optionalMaxDepth, InvalidParameter);
ASYNC_FAIL_WITH_PREDEFINED_ERROR_IF(*optionalMaxDepth > JSC::maxSafeInteger(), InvalidParameter);
maxDepth = std::optional<uint64_t>(static_cast<uint64_t>(*optionalMaxDepth));
}
Vector<Ref<WebPageProxy>> pagesToProcess;
for (Ref process : session->protectedProcessPool()->processes()) {
for (Ref page : process->pages()) {
if (!page->isControlledByAutomation())
continue;
if (!optionalRoot.isEmpty()) {
if (session->handleForWebPageProxy(page) == optionalRoot) {
pagesToProcess.append(page);
break;
}
} else
pagesToProcess.append(page);
}
}
ASYNC_FAIL_WITH_PREDEFINED_ERROR_IF(!optionalRoot.isEmpty() && pagesToProcess.isEmpty(), FrameNotFound);
if (pagesToProcess.isEmpty()) {
callback({ { JSON::ArrayOf<Inspector::Protocol::BidiBrowsingContext::Info>::create() } });
return;
}
pagesToProcess.reverse();
auto resultsObject = JSON::ArrayOf<Inspector::Protocol::BidiBrowsingContext::Info>::create();
getNextTree(WTFMove(pagesToProcess), WTFMove(resultsObject), WTFMove(maxDepth), [callback = WTFMove(callback)](auto&& result) {
callback({ { result.value() } });
});
}
void BidiBrowsingContextAgent::handleUserPrompt(const BrowsingContext& browsingContext, std::optional<bool>&& optionalShouldAccept, const String&, CommandCallback<void>&& callback)
{
RefPtr session = m_session.get();
ASYNC_FAIL_WITH_PREDEFINED_ERROR_IF(!session, InternalError);
// FIXME: implement `userText` option.
if (optionalShouldAccept && *optionalShouldAccept) {
callback(session->acceptCurrentJavaScriptDialog(browsingContext));
return;
}
// FIXME: this should consider the session's user prompt handler. <https://webkit.org/b/291666>
callback(session->dismissCurrentJavaScriptDialog(browsingContext));
}
// https://www.w3.org/TR/webdriver/#dfn-session-page-load-timeout
static constexpr Seconds defaultPageLoadTimeout = 300_s;
static constexpr ReadinessState defaultReadinessState = ReadinessState::None;
static PageLoadStrategy pageLoadStrategyFromReadinessState(ReadinessState state)
{
switch (state) {
case ReadinessState::None:
return PageLoadStrategy::None;
case ReadinessState::Interactive:
return PageLoadStrategy::Eager;
case ReadinessState::Complete:
return PageLoadStrategy::Normal;
}
ASSERT_NOT_REACHED();
return PageLoadStrategy::Normal;
}
void BidiBrowsingContextAgent::navigate(const BrowsingContext& browsingContext, const String& url, std::optional<ReadinessState>&& optionalReadinessState, CommandCallbackOf<String, Inspector::Protocol::BidiBrowsingContext::Navigation>&& callback)
{
RefPtr session = m_session.get();
ASYNC_FAIL_WITH_PREDEFINED_ERROR_IF(!session, InternalError);
auto pageLoadStrategy = pageLoadStrategyFromReadinessState(optionalReadinessState.value_or(defaultReadinessState));
session->navigateBrowsingContext(browsingContext, url, pageLoadStrategy, defaultPageLoadTimeout.milliseconds(), [url, callback = WTFMove(callback)](CommandResult<void>&& result) {
if (!result) {
callback(makeUnexpected(result.error()));
return;
}
// FIXME: keep track of navigation IDs that we hand out.
callback({ { url, "placeholder_navigation"_s } });
});
}
void BidiBrowsingContextAgent::reload(const BrowsingContext& browsingContext, std::optional<bool>&& optionalIgnoreCache, std::optional<ReadinessState>&& optionalReadinessState, CommandCallbackOf<String, Inspector::Protocol::BidiBrowsingContext::Navigation>&& callback)
{
RefPtr session = m_session.get();
ASYNC_FAIL_WITH_PREDEFINED_ERROR_IF(!session, InternalError);
// FIXME: implement `ignoreCache` option.
auto pageLoadStrategy = pageLoadStrategyFromReadinessState(optionalReadinessState.value_or(defaultReadinessState));
session->reloadBrowsingContext(browsingContext, pageLoadStrategy, defaultPageLoadTimeout.milliseconds(), [session = WTFMove(session), browsingContext, callback = WTFMove(callback)](CommandResult<void>&& result) {
if (!result) {
callback(makeUnexpected(result.error()));
return;
}
ASYNC_FAIL_WITH_PREDEFINED_ERROR_IF(!session, InternalError);
RefPtr webPageProxy = session->webPageProxyForHandle(browsingContext);
ASYNC_FAIL_WITH_PREDEFINED_ERROR_IF(!webPageProxy, WindowNotFound);
// FIXME: keep track of navigation IDs that we hand out.
callback({ { webPageProxy->currentURL(), "placeholder_navigation"_s } });
});
}
} // namespace WebKit
#endif // ENABLE(WEBDRIVER_BIDI)
|