File: PlatformXRSystem.cpp

package info (click to toggle)
webkit2gtk 2.51.3-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 477,912 kB
  • sloc: cpp: 3,898,343; javascript: 198,215; ansic: 165,229; python: 50,371; asm: 21,819; ruby: 18,095; perl: 16,953; xml: 4,623; sh: 2,398; yacc: 2,356; java: 2,019; lex: 1,358; pascal: 372; makefile: 197
file content (437 lines) | stat: -rw-r--r-- 17,889 bytes parent folder | download | duplicates (2)
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
/*
 * Copyright (C) 2021 Apple Inc. 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 "PlatformXRSystem.h"

#if ENABLE(WEBXR)

#include "GPUProcessProxy.h"
#include "MessageSenderInlines.h"
#include "PlatformXRSystemMessages.h"
#include "PlatformXRSystemProxyMessages.h"
#include "WebPageProxy.h"
#include "WebProcessProxy.h"
#include <WebCore/ExceptionData.h>
#include <WebCore/GPUTextureFormat.h>
#include <WebCore/SecurityOriginData.h>
#include <WebCore/XRCanvasConfiguration.h>
#include <wtf/TZoneMallocInlines.h>

#define MESSAGE_CHECK(assertion, connection) MESSAGE_CHECK_BASE(assertion, connection)
#define MESSAGE_CHECK_COMPLETION(assertion, connection, completion) MESSAGE_CHECK_COMPLETION_BASE(assertion, connection, completion)

namespace WebKit {

WTF_MAKE_TZONE_ALLOCATED_IMPL(PlatformXRSystem);

PlatformXRSystem::PlatformXRSystem(WebPageProxy& page)
    : m_page(page)
{
    page.protectedLegacyMainFrameProcess()->addMessageReceiver(Messages::PlatformXRSystem::messageReceiverName(), page.webPageIDInMainFrameProcess(), *this);
}

PlatformXRSystem::~PlatformXRSystem()
{
    RefPtr page = m_page.get();
    if (!page)
        return;

    page->protectedLegacyMainFrameProcess()->removeMessageReceiver(Messages::PlatformXRSystem::messageReceiverName(), page->webPageIDInMainFrameProcess());
}

std::optional<SharedPreferencesForWebProcess> PlatformXRSystem::sharedPreferencesForWebProcess(IPC::Connection& connection) const
{
    return WebProcessProxy::fromConnection(connection)->sharedPreferencesForWebProcess();
}

void PlatformXRSystem::invalidate(InvalidationReason reason)
{
    ASSERT(RunLoop::isMain());
    RefPtr page = m_page.get();
    if (!page)
        return;

    if (m_immersiveSessionState == ImmersiveSessionState::Idle)
        return;

    if (xrCoordinator())
        xrCoordinator()->endSessionIfExists(*page);

    invalidateImmersiveSessionState(reason == InvalidationReason::Client ? ImmersiveSessionState::SessionEndingFromSystem : ImmersiveSessionState::Idle);
}

void PlatformXRSystem::ensureImmersiveSessionActivity()
{
    ASSERT(RunLoop::isMain());

    RefPtr page = m_page.get();
    if (!page)
        return;

    if (m_immersiveSessionActivity && m_immersiveSessionActivity->isValid())
        return;

    m_immersiveSessionActivity = page->protectedLegacyMainFrameProcess()->protectedThrottler()->foregroundActivity("XR immersive session"_s);
}

void PlatformXRSystem::enumerateImmersiveXRDevices(CompletionHandler<void(Vector<XRDeviceInfo>&&)>&& completionHandler)
{
    RefPtr page = m_page.get();
    if (!page) {
        completionHandler({ });
        return;
    }

    auto* xrCoordinator = PlatformXRSystem::xrCoordinator();
    if (!xrCoordinator) {
        completionHandler({ });
        return;
    }

    xrCoordinator->getPrimaryDeviceInfo(*page, [completionHandler = WTFMove(completionHandler)](std::optional<XRDeviceInfo> deviceInfo) mutable {
        RunLoop::mainSingleton().dispatch([completionHandler = WTFMove(completionHandler), deviceInfo = WTFMove(deviceInfo)]() mutable {
            if (!deviceInfo) {
                completionHandler({ });
                return;
            }

            completionHandler({ deviceInfo.value() });
        });
    });
}

static bool checkFeaturesConsent(const std::optional<PlatformXR::Device::FeatureList>& requestedFeatures, const std::optional<PlatformXR::Device::FeatureList>& grantedFeatures)
{
    if (!grantedFeatures || !requestedFeatures)
        return false;

    bool result = true;
    for (auto requestedFeature : *requestedFeatures) {
        if (!grantedFeatures->contains(requestedFeature)) {
            result = false;
            break;
        }
    }
    return result;
}

void PlatformXRSystem::requestPermissionOnSessionFeatures(IPC::Connection& connection, const WebCore::SecurityOriginData& securityOriginData, PlatformXR::SessionMode mode, const PlatformXR::Device::FeatureList& granted, const PlatformXR::Device::FeatureList& consentRequired, const PlatformXR::Device::FeatureList& consentOptional, const PlatformXR::Device::FeatureList& requiredFeaturesRequested, const PlatformXR::Device::FeatureList& optionalFeaturesRequested, CompletionHandler<void(std::optional<PlatformXR::Device::FeatureList>&&)>&& completionHandler)
{
    ASSERT(RunLoop::isMain());

    RefPtr page = m_page.get();
    if (!page) {
        completionHandler(granted);
        return;
    }

    if (!PlatformXR::isImmersive(mode)) {
        completionHandler(granted);
        return;
    }

    auto* xrCoordinator = PlatformXRSystem::xrCoordinator();
    if (!xrCoordinator) {
        completionHandler(granted);
        return;
    }

    MESSAGE_CHECK_COMPLETION(m_immersiveSessionState == ImmersiveSessionState::Idle || m_immersiveSessionState == ImmersiveSessionState::SessionEndingFromWebContent, connection, completionHandler({ }));
    setImmersiveSessionState(ImmersiveSessionState::RequestingPermissions, [](bool) mutable { });
    m_immersiveSessionGrantedFeatures = std::nullopt;

    xrCoordinator->requestPermissionOnSessionFeatures(*page, securityOriginData, mode, granted, consentRequired, consentOptional, requiredFeaturesRequested, optionalFeaturesRequested, [weakThis = WeakPtr { *this }, mode, securityOriginData, consentRequired, completionHandler = WTFMove(completionHandler)](std::optional<PlatformXR::Device::FeatureList>&& grantedFeatures) mutable {
        ASSERT(RunLoop::isMain());
        auto protectedThis = weakThis.get();
        if (protectedThis && PlatformXR::isImmersive(mode)) {
            if (checkFeaturesConsent(consentRequired, grantedFeatures)) {
                protectedThis->m_immersiveSessionMode = mode;
                protectedThis->m_immersiveSessionGrantedFeatures = grantedFeatures;
                protectedThis->m_immersiveSessionSecurityOriginData = securityOriginData;
                protectedThis->setImmersiveSessionState(ImmersiveSessionState::PermissionsGranted, [grantedFeatures = WTFMove(grantedFeatures), completionHandler = WTFMove(completionHandler)](bool) mutable {
                    completionHandler(WTFMove(grantedFeatures));
                });
            } else {
                protectedThis->invalidateImmersiveSessionState();
                completionHandler(WTFMove(grantedFeatures));
            }
        } else
            completionHandler(WTFMove(grantedFeatures));
    });
}

void PlatformXRSystem::initializeTrackingAndRendering(IPC::Connection& connection, std::optional<WebCore::WebGPU::TextureFormat> colorFormat, std::optional<WebCore::WebGPU::TextureFormat> depthStencilFormat)
{
    ASSERT(RunLoop::isMain());
    MESSAGE_CHECK(m_immersiveSessionMode, connection);
    MESSAGE_CHECK(m_immersiveSessionState == ImmersiveSessionState::PermissionsGranted, connection);
    MESSAGE_CHECK(m_immersiveSessionSecurityOriginData, connection);
    MESSAGE_CHECK(m_immersiveSessionGrantedFeatures && !m_immersiveSessionGrantedFeatures->isEmpty(), connection);

    RefPtr page = m_page.get();
    if (!page)
        return;

    auto* xrCoordinator = PlatformXRSystem::xrCoordinator();
    if (!xrCoordinator)
        return;

    setImmersiveSessionState(ImmersiveSessionState::SessionRunning, [](bool) mutable { });

    ensureImmersiveSessionActivity();

    WeakPtr weakThis { *this };
    std::optional<WebCore::XRCanvasConfiguration> init;
    if (colorFormat) {
        init = WebCore::XRCanvasConfiguration();
        init->colorFormat = colorFormat;
        init->depthStencilFormat = depthStencilFormat;
    }
    xrCoordinator->startSession(*page, weakThis, *m_immersiveSessionSecurityOriginData, *m_immersiveSessionMode, *m_immersiveSessionGrantedFeatures, WTFMove(init));
}

void PlatformXRSystem::shutDownTrackingAndRendering(IPC::Connection& connection)
{
    ASSERT(RunLoop::isMain());
    MESSAGE_CHECK(m_immersiveSessionState == ImmersiveSessionState::SessionRunning, connection);

    RefPtr page = m_page.get();
    if (!page)
        return;

    if (auto* xrCoordinator = PlatformXRSystem::xrCoordinator())
        xrCoordinator->endSessionIfExists(*page);
    setImmersiveSessionState(ImmersiveSessionState::SessionEndingFromWebContent, [](bool) mutable { });
}

void PlatformXRSystem::requestFrame(IPC::Connection& connection, std::optional<PlatformXR::RequestData>&& requestData, CompletionHandler<void(PlatformXR::FrameData&&)>&& completionHandler)
{
    ASSERT(RunLoop::isMain());
    MESSAGE_CHECK_COMPLETION(m_immersiveSessionState == ImmersiveSessionState::SessionRunning || m_immersiveSessionState == ImmersiveSessionState::SessionEndingFromSystem, connection, completionHandler({ }));
    if (m_immersiveSessionState != ImmersiveSessionState::SessionRunning) {
        completionHandler({ });
        return;
    }

    RefPtr page = m_page.get();
    if (!page) {
        completionHandler({ });
        return;
    }

    if (auto* xrCoordinator = PlatformXRSystem::xrCoordinator())
        xrCoordinator->scheduleAnimationFrame(*page, WTFMove(requestData), WTFMove(completionHandler));
    else
        completionHandler({ });
}

#if USE(OPENXR)
void PlatformXRSystem::submitFrame(IPC::Connection& connection, Vector<XRDeviceLayer>&& layers)
#else
void PlatformXRSystem::submitFrame(IPC::Connection& connection)
#endif
{
    ASSERT(RunLoop::isMain());
    MESSAGE_CHECK(m_immersiveSessionState == ImmersiveSessionState::SessionRunning || m_immersiveSessionState == ImmersiveSessionState::SessionEndingFromSystem, connection);
    if (m_immersiveSessionState != ImmersiveSessionState::SessionRunning)
        return;

    RefPtr page = m_page.get();
    if (!page)
        return;

    if (auto* xrCoordinator = PlatformXRSystem::xrCoordinator()) {
#if USE(OPENXR)
        xrCoordinator->submitFrame(*page, WTFMove(layers));
#else
        xrCoordinator->submitFrame(*page);
#endif
    }
}

#if ENABLE(WEBXR_HIT_TEST)
void PlatformXRSystem::requestHitTestSource(const PlatformXR::HitTestOptions& hitTestOptions, CompletionHandler<void(Expected<PlatformXR::HitTestSource, WebCore::ExceptionData>)>&& passedCompletionHandler)
{
    auto completionHandler = [passedCompletionHandler = WTFMove(passedCompletionHandler)](WebCore::ExceptionOr<PlatformXR::HitTestSource> exceptionOrValue) mutable {
        if (exceptionOrValue.hasException()) {
            auto exception = exceptionOrValue.releaseException();
            passedCompletionHandler(makeUnexpected(WebCore::ExceptionData { exception.code(), exception.releaseMessage() }));
        } else
            passedCompletionHandler(exceptionOrValue.releaseReturnValue());
    };
    RefPtr page = m_page.get();
    if (!page) {
        completionHandler(WebCore::Exception { WebCore::ExceptionCode::InvalidStateError });
        return;
    }
    auto* xrCoordinator = PlatformXRSystem::xrCoordinator();
    if (!xrCoordinator) {
        completionHandler(WebCore::Exception { WebCore::ExceptionCode::InvalidStateError });
        return;
    }
    xrCoordinator->requestHitTestSource(*page, hitTestOptions, WTFMove(completionHandler));
}

void PlatformXRSystem::deleteHitTestSource(PlatformXR::HitTestSource source)
{
    RefPtr page = m_page.get();
    if (!page)
        return;
    if (auto* xrCoordinator = PlatformXRSystem::xrCoordinator())
        xrCoordinator->deleteHitTestSource(*page, source);
}

void PlatformXRSystem::requestTransientInputHitTestSource(const PlatformXR::TransientInputHitTestOptions& hitTestOptions, CompletionHandler<void(Expected<PlatformXR::TransientInputHitTestSource, WebCore::ExceptionData>)>&& passedCompletionHandler)
{
    auto completionHandler = [passedCompletionHandler = WTFMove(passedCompletionHandler)](WebCore::ExceptionOr<PlatformXR::TransientInputHitTestSource> exceptionOrValue) mutable {
        if (exceptionOrValue.hasException()) {
            auto exception = exceptionOrValue.releaseException();
            passedCompletionHandler(makeUnexpected(WebCore::ExceptionData { exception.code(), exception.releaseMessage() }));
        } else
            passedCompletionHandler(exceptionOrValue.releaseReturnValue());
    };
    RefPtr page = m_page.get();
    if (!page) {
        completionHandler(WebCore::Exception { WebCore::ExceptionCode::InvalidStateError });
        return;
    }
    auto* xrCoordinator = PlatformXRSystem::xrCoordinator();
    if (!xrCoordinator) {
        completionHandler(WebCore::Exception { WebCore::ExceptionCode::InvalidStateError });
        return;
    }
    xrCoordinator->requestTransientInputHitTestSource(*page, hitTestOptions, WTFMove(completionHandler));
}

void PlatformXRSystem::deleteTransientInputHitTestSource(PlatformXR::TransientInputHitTestSource source)
{
    RefPtr page = m_page.get();
    if (!page)
        return;
    if (auto* xrCoordinator = PlatformXRSystem::xrCoordinator())
        xrCoordinator->deleteTransientInputHitTestSource(*page, source);
}
#endif

void PlatformXRSystem::didCompleteShutdownTriggeredBySystem(IPC::Connection& connection)
{
    ASSERT(RunLoop::isMain());
    MESSAGE_CHECK(m_immersiveSessionState == ImmersiveSessionState::SessionEndingFromSystem, connection);
    setImmersiveSessionState(ImmersiveSessionState::Idle, [](bool) mutable { });
}

void PlatformXRSystem::sessionDidEnd(XRDeviceIdentifier deviceIdentifier)
{
    ensureOnMainRunLoop([weakThis = WeakPtr { *this }, deviceIdentifier]() mutable {
        RefPtr protectedThis = weakThis.get();
        if (!protectedThis)
            return;

        RefPtr page = protectedThis->m_page.get();
        if (!page)
            return;

        page->protectedLegacyMainFrameProcess()->send(Messages::PlatformXRSystemProxy::SessionDidEnd(deviceIdentifier), page->webPageIDInMainFrameProcess());
        protectedThis->m_immersiveSessionActivity = nullptr;
        // If this is called when the session is running, the ending of the session is triggered by the system side
        // and we should set the state to SessionEndingFromSystem. We expect the web process to send a
        // didCompleteShutdownTriggeredBySystem message later when it has ended the XRSession, which will
        // reset the session state to Idle.
        protectedThis->invalidateImmersiveSessionState(protectedThis->m_immersiveSessionState == ImmersiveSessionState::SessionRunning ? ImmersiveSessionState::SessionEndingFromSystem : ImmersiveSessionState::Idle);
    });
}

void PlatformXRSystem::sessionDidUpdateVisibilityState(XRDeviceIdentifier deviceIdentifier, PlatformXR::VisibilityState visibilityState)
{
    ensureOnMainRunLoop([weakThis = WeakPtr { *this }, deviceIdentifier, visibilityState]() mutable {
        RefPtr protectedThis = weakThis.get();
        if (!protectedThis)
            return;

        RefPtr page = protectedThis->m_page.get();
        if (!page)
            return;

        page->protectedLegacyMainFrameProcess()->send(Messages::PlatformXRSystemProxy::SessionDidUpdateVisibilityState(deviceIdentifier, visibilityState), page->webPageIDInMainFrameProcess());
    });
}

void PlatformXRSystem::setImmersiveSessionState(ImmersiveSessionState state, CompletionHandler<void(bool)>&& completion)
{
    m_immersiveSessionState = state;
#if PLATFORM(COCOA)
    RefPtr page = m_page.get();
    if (!page || page->isClosed()) {
        completion(false);
        return;
    }

    switch (state) {
    case ImmersiveSessionState::Idle:
    case ImmersiveSessionState::RequestingPermissions:
        break;
    case ImmersiveSessionState::PermissionsGranted:
        return GPUProcessProxy::getOrCreate()->webXRPromptAccepted(page->ensureRunningProcess().processIdentity(), WTFMove(completion));
    case ImmersiveSessionState::SessionRunning:
    case ImmersiveSessionState::SessionEndingFromWebContent:
    case ImmersiveSessionState::SessionEndingFromSystem:
        break;
    }
#endif
    completion(true);
}

void PlatformXRSystem::invalidateImmersiveSessionState(ImmersiveSessionState nextSessionState)
{
    ASSERT(RunLoop::isMain());

    m_immersiveSessionMode = std::nullopt;
    m_immersiveSessionSecurityOriginData = std::nullopt;
    m_immersiveSessionGrantedFeatures = std::nullopt;
    setImmersiveSessionState(nextSessionState, [](bool) mutable { });
}

bool PlatformXRSystem::webXREnabled() const
{
    RefPtr page = m_page.get();
    return page && page->protectedPreferences()->webXREnabled();
}

#if !USE(APPLE_INTERNAL_SDK) && !USE(OPENXR)

PlatformXRCoordinator* PlatformXRSystem::xrCoordinator()
{
    return nullptr;
}

#endif // !USE(APPLE_INTERNAL_SDK) && !USE(OPENXR)

} // namespace WebKit

#undef MESSAGE_CHECK_COMPLETION
#undef MESSAGE_CHECK

#endif // ENABLE(WEBXR)