File: xr_system.h

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (502 lines) | stat: -rw-r--r-- 21,206 bytes parent folder | download | duplicates (5)
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
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_XR_XR_SYSTEM_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_XR_XR_SYSTEM_H_

#include "base/time/time.h"
#include "device/vr/public/mojom/vr_service.mojom-blink.h"
#include "device/vr/public/mojom/xr_session.mojom-blink.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "third_party/blink/public/mojom/devtools/console_message.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_xr_dom_overlay_init.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_xr_session_init.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/dom/events/event_target.h"
#include "third_party/blink/renderer/core/dom/events/native_event_listener.h"
#include "third_party/blink/renderer/core/execution_context/execution_context_lifecycle_observer.h"
#include "third_party/blink/renderer/core/page/focus_changed_observer.h"
#include "third_party/blink/renderer/modules/xr/xr_enter_fullscreen_observer.h"
#include "third_party/blink/renderer/modules/xr/xr_exit_fullscreen_observer.h"
#include "third_party/blink/renderer/modules/xr/xr_session.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
#include "third_party/blink/renderer/platform/heap/collection_support/heap_hash_set.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/mojo/heap_mojo_associated_remote.h"
#include "third_party/blink/renderer/platform/mojo/heap_mojo_receiver.h"
#include "third_party/blink/renderer/platform/mojo/heap_mojo_remote.h"
#include "third_party/blink/renderer/platform/mojo/heap_mojo_wrapper_mode.h"
#include "third_party/blink/renderer/platform/scheduler/public/frame_or_worker_scheduler.h"
#include "third_party/blink/renderer/platform/supplementable.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"

namespace blink {

class Navigator;
class V8XRSessionMode;
class XRFrameProvider;
class XRSession;
class XRSessionInit;

// Implementation of the XRSystem interface according to
// https://immersive-web.github.io/webxr/#xrsystem-interface . This is created
// lazily on first access to the navigator.xr attrib,
// and disposed when the execution context is destroyed or on mojo communication
// errors with the browser/device process.
//
// When the XRSystem is used for promises, it uses query objects to store state
// including the associated ScriptPromiseResolverBase. These query objects are
// owned by the XRSystem and remain alive until the promise is resolved or
// rejected. (See comments below for PendingSupportsSessionQuery and
// PendingRequestSessionQuery.) These query objects are destroyed and any
// outstanding promises rejected when the XRSystem is disposed.
//
// The XRSystem owns mojo connections with the Browser process through
// VRService, used for capability queries and session lifetime
// management. The XRSystem is also the receiver for the VRServiceClient.
//
// The XRSystem owns mojo connections with the Device process (either a
// separate utility process, or implemented as part of the Browser process,
// depending on the runtime and options) through XRFrameProvider and
// XREnvironmentIntegrationProvider. These are used to transport per-frame data
// such as image data and input poses. These are lazily created when first
// needed for a sensor-backed session (all except sensorless inline sessions),
// and destroyed when the XRSystem is disposed.
//
// The XRSystem keeps weak references to XRSession objects after they were
// returned through a successful requestSession promise, but does not own them.
class XRSystem final : public EventTarget,
                       public Supplement<Navigator>,
                       public ExecutionContextLifecycleObserver,
                       public device::mojom::blink::VRServiceClient,
                       public FocusChangedObserver {
  DEFINE_WRAPPERTYPEINFO();

 public:
  static const char kSupplementName[];
  static XRSystem* From(Document&);
  static XRSystem* FromIfExists(Document&);

  static XRSystem* xr(Navigator&);

  // TODO(crbug.com/976796): Fix lint errors.
  explicit XRSystem(Navigator&);

  DEFINE_ATTRIBUTE_EVENT_LISTENER(devicechange, kDevicechange)

  ScriptPromise<IDLBoolean> isSessionSupported(ScriptState*,
                                               const V8XRSessionMode&,
                                               ExceptionState& exception_state);
  ScriptPromise<XRSession> requestSession(ScriptState*,
                                          const V8XRSessionMode&,
                                          XRSessionInit*,
                                          ExceptionState& exception_state);

  XRFrameProvider* frameProvider();

  device::mojom::blink::XREnvironmentIntegrationProvider*
  xrEnvironmentProviderRemote();

  device::mojom::blink::VRService* BrowserService();

  // VRServiceClient overrides.
  void OnDeviceChanged() override;

  // EventTarget overrides.
  ExecutionContext* GetExecutionContext() const override;
  const AtomicString& InterfaceName() const override;

  // ExecutionContextLifecycleObserver overrides.
  void ContextDestroyed() override;
  void Trace(Visitor*) const override;

  // FocusChangedObserver overrides.
  void FocusedFrameChanged() override;
  bool IsFrameFocused();

  using EnvironmentProviderErrorCallback = base::OnceCallback<void()>;
  // Registers a callback that'll be invoked when mojo invokes a disconnect
  // handler on the underlying XREnvironmentIntegrationProvider remote.
  void AddEnvironmentProviderErrorHandler(
      EnvironmentProviderErrorCallback callback);

  void ExitPresent(base::OnceClosure on_exited);

  void SetFramesThrottled(const XRSession* session, bool throttled);

  base::TimeTicks NavigationStart() const { return navigation_start_; }

  bool IsContextDestroyed() const { return is_context_destroyed_; }

  void MakeXrCompatibleAsync(
      device::mojom::blink::VRService::MakeXrCompatibleCallback callback);
  void MakeXrCompatibleSync(
      device::mojom::XrCompatibleResult* xr_compatible_result);

  void OnSessionEnded(XRSession* session);

  device::mojom::blink::WebXrInternalsRendererListener*
  GetWebXrInternalsRendererListener();

  void AddWebXrInternalsMessage(const String& message);

 private:
  void DisableBackForwardCache();

  enum SensorRequirement {
    kNone,
    kOptional,
    kRequired,
  };

  // These values are persisted to logs. Entries should not be renumbered and
  // numeric values should never be reused.
  enum class SessionRequestStatus : int {
    // `requestSession` succeeded.
    kSuccess = 0,
    // `requestSession` failed with other (unknown) error.
    kOtherError = 1,
    kMaxValue = kOtherError,
  };

  struct RequestedXRSessionFeatureSet {
    // Set of requested features which are known and valid for the current mode.
    XRSessionFeatureSet valid_features;

    // Whether any requested features were unknown or invalid
    bool invalid_features = false;
  };

  // Encapsulates blink-side `XRSystem::requestSession()` call. It is a wrapper
  // around ScriptPromiseResolverBase that allows us to add additional logic as
  // certain things related to promise's life cycle happen. Instances are owned
  // by the XRSystem, see outstanding_request_queries_ below.
  class PendingRequestSessionQuery final
      : public GarbageCollected<PendingRequestSessionQuery> {
   public:
    PendingRequestSessionQuery(int64_t ukm_source_id,
                               ScriptPromiseResolver<XRSession>* resolver,
                               device::mojom::blink::XRSessionMode mode,
                               RequestedXRSessionFeatureSet required_features,
                               RequestedXRSessionFeatureSet optional_features);

    PendingRequestSessionQuery(const PendingRequestSessionQuery&) = delete;
    PendingRequestSessionQuery& operator=(const PendingRequestSessionQuery&) =
        delete;

    ~PendingRequestSessionQuery() = default;

    // Resolves underlying promise with passed in XR session.
    // If metrics are to be recorded for this session, an
    // |XRSessionMetricsRecorded| may be passed in as well.
    void Resolve(
        XRSession* session,
        mojo::PendingRemote<device::mojom::blink::XRSessionMetricsRecorder>
            metrics_recorder = mojo::NullRemote());

    // Rejects underlying promise with a DOMException.
    // Do not call this with |DOMExceptionCode::kSecurityError|, use
    // |RejectWithSecurityError| for that. If the exception is thrown
    // synchronously, an ExceptionState must be passed in. Otherwise it may be
    // null. Care must be taken when setting |message| - it will be accessible
    // to the application and should not contain any sensitive data.
    void RejectWithDOMException(DOMExceptionCode exception_code,
                                const String& message,
                                ExceptionState* exception_state);

    // Rejects underlying promise with a SecurityError.
    // If the exception is thrown synchronously, an ExceptionState must
    // be passed in. Otherwise it may be null. Care must be taken when setting
    // |message| - it will be accessible to the application and should not
    // contain any sensitive data.
    void RejectWithSecurityError(const String& message,
                                 ExceptionState* exception_state);

    // Rejects underlying promise with a TypeError.
    // If the exception is thrown synchronously, an ExceptionState must
    // be passed in. Otherwise it may be null. Care must be taken when setting
    // |message| - it will be accessible to the application and should not
    // contain any sensitive data.
    void RejectWithTypeError(const String& message,
                             ExceptionState* exception_state);

    device::mojom::blink::XRSessionMode mode() const;
    const XRSessionFeatureSet& RequiredFeatures() const;
    const XRSessionFeatureSet& OptionalFeatures() const;
    bool InvalidRequiredFeatures() const;
    bool InvalidOptionalFeatures() const;
    bool HasFeature(device::mojom::XRSessionFeature) const;

    SensorRequirement GetSensorRequirement() const {
      return sensor_requirement_;
    }

    // Returns underlying resolver's script state.
    ScriptState* GetScriptState() const;

    void SetDOMOverlayElement(Element* element) {
      dom_overlay_element_ = element;
    }
    Element* DOMOverlayElement() { return dom_overlay_element_.Get(); }

    void SetTrackedImages(
        const Vector<device::mojom::blink::XRTrackedImage>& images) {
      tracked_images_ = images;
    }
    Vector<device::mojom::blink::XRTrackedImage> TrackedImages() const {
      return tracked_images_;
    }

    void SetDepthSensingConfiguration(
        const Vector<device::mojom::XRDepthUsage>& preferred_usage,
        const Vector<device::mojom::XRDepthDataFormat>& preferred_format,
        const Vector<device::mojom::XRDepthType>& type_request,
        bool match_depth_view) {
      preferred_usage_ = preferred_usage;
      preferred_format_ = preferred_format;
      depth_type_request_ = type_request;
      match_depth_view_ = match_depth_view;
    }

    const Vector<device::mojom::XRDepthUsage>& PreferredUsage() const {
      return preferred_usage_;
    }

    const Vector<device::mojom::XRDepthDataFormat>& PreferredFormat() const {
      return preferred_format_;
    }

    const Vector<device::mojom::XRDepthType>& DepthTypeRequest() const {
      return depth_type_request_;
    }

    bool MatchDepthView() const { return match_depth_view_; }

    uint64_t TraceId() const { return trace_id_; }

    void Trace(Visitor*) const;

   private:
    void ParseSensorRequirement();
    device::mojom::XRSessionFeatureRequestStatus GetFeatureRequestStatus(
        device::mojom::XRSessionFeature feature,
        const XRSession* session) const;
    void ReportRequestSessionResult(
        SessionRequestStatus status,
        XRSession* session = nullptr,
        mojo::PendingRemote<device::mojom::blink::XRSessionMetricsRecorder>
            metrics_recorder = mojo::NullRemote());

    Member<ScriptPromiseResolver<XRSession>> resolver_;
    const device::mojom::blink::XRSessionMode mode_;
    RequestedXRSessionFeatureSet required_features_;
    RequestedXRSessionFeatureSet optional_features_;
    SensorRequirement sensor_requirement_ = SensorRequirement::kNone;

    const int64_t ukm_source_id_;

    // Used for trace calls in order to correlate this request across processes.
    const uint64_t trace_id_;

    Member<Element> dom_overlay_element_;

    Vector<device::mojom::blink::XRTrackedImage> tracked_images_;

    Vector<device::mojom::XRDepthUsage> preferred_usage_;
    Vector<device::mojom::XRDepthDataFormat> preferred_format_;
    Vector<device::mojom::XRDepthType> depth_type_request_;
    bool match_depth_view_;
  };

  static device::mojom::blink::XRSessionOptionsPtr XRSessionOptionsFromQuery(
      const PendingRequestSessionQuery& query);

  // Encapsulates blink-side `XRSystem::isSessionSupported()` call. It is a
  // wrapper around ScriptPromiseResolverBase that allows us to add additional
  // logic as certain things related to promise's life cycle happen. Instances
  // are owned by the XRSystem, see outstanding_support_queries_ below.
  class PendingSupportsSessionQuery final
      : public GarbageCollected<PendingSupportsSessionQuery> {
   public:
    PendingSupportsSessionQuery(ScriptPromiseResolverBase*,
                                device::mojom::blink::XRSessionMode);

    PendingSupportsSessionQuery(const PendingSupportsSessionQuery&) = delete;
    PendingSupportsSessionQuery& operator=(const PendingSupportsSessionQuery&) =
        delete;

    ~PendingSupportsSessionQuery() = default;

    // Resolves underlying promise.
    void Resolve(bool supported, ExceptionState* exception_state = nullptr);

    // Rejects underlying promise with a DOMException.
    // Do not call this with |DOMExceptionCode::kSecurityError|, use
    // |RejectWithSecurityError| for that. If the exception is thrown
    // synchronously, an ExceptionState must be passed in. Otherwise it may be
    // null. Care must be taken when setting |message| - it will be accessible
    // to the application and should not contain any sensitive data.
    void RejectWithDOMException(DOMExceptionCode exception_code,
                                const String& message,
                                ExceptionState* exception_state);

    // Rejects underlying promise with a SecurityError.
    // If the exception is thrown synchronously, an ExceptionState must
    // be passed in. Otherwise it may be null. Care must be taken when setting
    // |message| - it will be accessible to the application and should not
    // contain any sensitive data.
    void RejectWithSecurityError(const String& message,
                                 ExceptionState* exception_state);

    // Rejects underlying promise with a TypeError.
    // If the exception is thrown synchronously, an ExceptionState must
    // be passed in. Otherwise it may be null. Care must be taken when setting
    // |message| - it will be accessible to the application and should not
    // contain any sensitive data.
    void RejectWithTypeError(const String& message,
                             ExceptionState* exception_state);

    device::mojom::blink::XRSessionMode mode() const;

    uint64_t TraceId() const { return trace_id_; }

    void Trace(Visitor*) const;

   private:
    Member<ScriptPromiseResolverBase> resolver_;
    const device::mojom::blink::XRSessionMode mode_;

    // Used for trace calls in order to correlate this request across processes.
    const uint64_t trace_id_;
  };

  // Helper, logs message to the console as well as DVLOGs.
  void AddConsoleMessage(mojom::blink::ConsoleMessageLevel error_level,
                         const String& message);

  const char* CheckInlineSessionRequestAllowed(
      LocalFrame* frame,
      const PendingRequestSessionQuery& query);

  RequestedXRSessionFeatureSet ParseRequestedFeatures(
      const Vector<String>& features,
      const device::mojom::blink::XRSessionMode& session_mode,
      XRSessionInit* session_init,
      mojom::ConsoleMessageLevel error_level);

  void RequestSessionInternal(device::mojom::blink::XRSessionMode session_mode,
                              PendingRequestSessionQuery* query,
                              ExceptionState* exception_state);

  void RequestImmersiveSession(PendingRequestSessionQuery* query,
                               ExceptionState* exception_state);

  void RequestInlineSession(PendingRequestSessionQuery* query,
                            ExceptionState* exception_state);

  void DoRequestSession(
      PendingRequestSessionQuery* query,
      device::mojom::blink::XRSessionOptionsPtr session_options);
  void OnRequestSessionReturned(
      PendingRequestSessionQuery*,
      device::mojom::blink::RequestSessionResultPtr result);
  void OnFullscreenConfigured(
      PendingRequestSessionQuery* query,
      device::mojom::blink::RequestSessionResultPtr result,
      bool fullscreen_succeeded);
  void FinishSessionCreation(
      PendingRequestSessionQuery*,
      device::mojom::blink::RequestSessionResultPtr result);
  void OnSupportsSessionReturned(PendingSupportsSessionQuery*,
                                 bool supports_session);
  void ResolveSessionRequest(
      PendingRequestSessionQuery*,
      device::mojom::blink::RequestSessionResultPtr result);
  void RejectSessionRequest(PendingRequestSessionQuery*);

  void EnsureDevice();

  void AddedEventListener(const AtomicString& event_type,
                          RegisteredEventListener&) override;

  XRSession* CreateSession(
      device::mojom::blink::XRSessionMode mode,
      device::mojom::blink::XREnvironmentBlendMode blend_mode,
      device::mojom::blink::XRInteractionMode interaction_mode,
      mojo::PendingReceiver<device::mojom::blink::XRSessionClient>
          client_receiver,
      device::mojom::blink::XRSessionDeviceConfigPtr device_config,
      XRSessionFeatureSet enabled_features,
      uint64_t trace_id,
      bool sensorless_session = false);

  XRSession* CreateSensorlessInlineSession();

  enum class DisposeType {
    kContextDestroyed = 0,
    kDisconnected = 1,
  };
  void Dispose(DisposeType);

  void OnEnvironmentProviderDisconnect();

  void TryEnsureService();

  // Helper, returns true if immersive AR session creation is supported.
  // Currently, it checks whether AR is enabled in runtime features, and in web
  // settings (controlled by enterprise policy).
  bool IsImmersiveArAllowed();

  // Indicates whether use of requestDevice has already been logged.
  bool did_log_supports_immersive_ = false;

  // Indicates whether we've already logged a request for an immersive session.
  bool did_log_request_immersive_session_ = false;

  // The XR object owns outstanding pending session queries, these live until
  // the underlying promise is either resolved or rejected.
  HeapHashSet<Member<PendingSupportsSessionQuery>> outstanding_support_queries_;
  HeapHashSet<Member<PendingRequestSessionQuery>> outstanding_request_queries_;
  bool has_outstanding_immersive_request_ = false;

  Vector<EnvironmentProviderErrorCallback>
      environment_provider_error_callbacks_;

  Member<XRFrameProvider> frame_provider_;
  HeapHashSet<WeakMember<XRSession>> sessions_;
  HeapMojoRemote<device::mojom::blink::VRService> service_;
  HeapMojoAssociatedRemote<
      device::mojom::blink::XREnvironmentIntegrationProvider>
      environment_provider_;
  HeapMojoReceiver<device::mojom::blink::VRServiceClient, XRSystem> receiver_;

  // Time at which navigation started. Used as the base for relative timestamps,
  // such as for Gamepad objects.
  base::TimeTicks navigation_start_;

  FrameOrWorkerScheduler::SchedulingAffectingFeatureHandle
      feature_handle_for_scheduler_;

  // In DOM overlay mode, use a fullscreen event listener to detect when
  // transition to fullscreen mode completes or fails, and reject/resolve
  // the pending request session promise accordingly.
  Member<XrEnterFullscreenObserver> fullscreen_enter_observer_;
  // DOM overlay mode uses a separate temporary fullscreen event listener
  // if it needs to wait for fullscreen mode to fully exit when ending
  // the session.
  Member<XrExitFullscreenObserver> fullscreen_exit_observer_;

  bool is_context_destroyed_ = false;
  bool did_service_ever_disconnect_ = false;

  HeapMojoRemote<device::mojom::blink::WebXrInternalsRendererListener>
      webxr_internals_renderer_listener_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_MODULES_XR_XR_SYSTEM_H_