summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/core/page/pointer_lock_controller.cc
blob: 112818927265de0c5f1b950e4ff704020d37cb2b (plain)
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
/*
 * Copyright (C) 2012 Google 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 "third_party/blink/renderer/core/page/pointer_lock_controller.h"

#include "services/network/public/mojom/web_sandbox_flags.mojom-blink.h"
#include "third_party/blink/public/common/input/web_mouse_event.h"
#include "third_party/blink/public/mojom/input/pointer_lock_result.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_pointer_lock_options.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/input/event_handler.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/platform/heap/heap.h"

namespace blink {

PointerLockController::PointerLockController(Page* page)
    : page_(page), lock_pending_(false) {}

ScriptPromise PointerLockController::RequestPointerLock(
    ScriptPromiseResolver* resolver,
    Element* target,
    ExceptionState& exception_state,
    const PointerLockOptions* options) {
  ScriptPromise promise = resolver->Promise();

  if (!target || !target->isConnected() ||
      document_of_removed_element_while_waiting_for_unlock_) {
    EnqueueEvent(event_type_names::kPointerlockerror, target);
    exception_state.ThrowDOMException(DOMExceptionCode::kWrongDocumentError,
                                      "Target Element removed from DOM");
    return promise;
  }

  target->GetDocument().CountUseOnlyInCrossOriginIframe(
      WebFeature::kElementRequestPointerLockIframe);
  if (target->IsInShadowTree()) {
    UseCounter::Count(target->GetDocument(),
                      WebFeature::kElementRequestPointerLockInShadow);
  }
  if (options && options->unadjustedMovement()) {
    UseCounter::Count(target->GetDocument(),
                      WebFeature::kPointerLockUnadjustedMovement);
  }

  if (target->GetDocument().IsSandboxed(
          network::mojom::blink::WebSandboxFlags::kPointerLock)) {
    // FIXME: This message should be moved off the console once a solution to
    // https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
    target->GetDocument().AddConsoleMessage(
        MakeGarbageCollected<ConsoleMessage>(
            mojom::ConsoleMessageSource::kSecurity,
            mojom::ConsoleMessageLevel::kError,
            "Blocked pointer lock on an element because the element's frame is "
            "sandboxed and the 'allow-pointer-lock' permission is not set."));
    EnqueueEvent(event_type_names::kPointerlockerror, target);
    exception_state.ThrowSecurityError(
        "Blocked pointer lock on an element because the element's frame is "
        "sandboxed and the 'allow-pointer-lock' permission is not set.",
        "");
    return promise;
  }

  bool unadjusted_movement_requested =
      options ? options->unadjustedMovement() : false;
  if (element_) {
    if (element_->GetDocument() != target->GetDocument()) {
      EnqueueEvent(event_type_names::kPointerlockerror, target);
      exception_state.ThrowDOMException(
          DOMExceptionCode::kWrongDocumentError,
          "The new element is not in the same shadow-root document as the "
          "element that currently holds the lock.");
      return promise;
    }

    // Attempt to change options if necessary.
    if (unadjusted_movement_requested != current_unadjusted_movement_setting_) {
      if (!page_->GetChromeClient().RequestPointerLockChange(
              target->GetDocument().GetFrame(),
              WTF::Bind(&PointerLockController::ChangeLockRequestCallback,
                        WrapWeakPersistent(this), WrapWeakPersistent(target),
                        WrapPersistent(resolver),
                        unadjusted_movement_requested),
              unadjusted_movement_requested)) {
        EnqueueEvent(event_type_names::kPointerlockerror, target);
        exception_state.ThrowDOMException(
            DOMExceptionCode::kInUseAttributeError, "Pointer lock pending.");
      }
      return promise;
    }

    EnqueueEvent(event_type_names::kPointerlockchange, target);
    element_ = target;
    resolver->Resolve();

    // Subsequent steps are handled in the browser process.
  } else if (page_->GetChromeClient().RequestPointerLock(
                 target->GetDocument().GetFrame(),
                 WTF::Bind(&PointerLockController::LockRequestCallback,
                           WrapWeakPersistent(this), WrapPersistent(resolver),
                           unadjusted_movement_requested),
                 unadjusted_movement_requested)) {
    lock_pending_ = true;
    element_ = target;
  } else {
    EnqueueEvent(event_type_names::kPointerlockerror, target);
    exception_state.ThrowDOMException(DOMExceptionCode::kInUseAttributeError,
                                      "Pointer lock pending.");
  }

  return promise;
}

void PointerLockController::ChangeLockRequestCallback(
    Element* target,
    ScriptPromiseResolver* resolver,
    bool unadjusted_movement_requested,
    mojom::blink::PointerLockResult result) {
  if (result == mojom::blink::PointerLockResult::kSuccess)
    element_ = target;

  LockRequestCallback(resolver, unadjusted_movement_requested, result);
}

void PointerLockController::LockRequestCallback(
    ScriptPromiseResolver* resolver,
    bool unadjusted_movement_requested,
    mojom::blink::PointerLockResult result) {
  if (result == mojom::blink::PointerLockResult::kSuccess) {
    current_unadjusted_movement_setting_ = unadjusted_movement_requested;
    resolver->Resolve();
    return;
  }
  DOMException* exception = ConvertResultToException(result);
  RejectIfPromiseEnabled(resolver, exception);
}

DOMException* PointerLockController::ConvertResultToException(
    mojom::blink::PointerLockResult result) {
  switch (result) {
    case mojom::blink::PointerLockResult::kUnsupportedOptions:
      return MakeGarbageCollected<DOMException>(
          DOMExceptionCode::kNotSupportedError,
          "The options asked for in this request are not supported on this "
          "platform.");
    case mojom::blink::PointerLockResult::kRequiresUserGesture:
      return MakeGarbageCollected<DOMException>(
          DOMExceptionCode::kNotAllowedError,
          "A user gesture is required to request Pointer Lock.");
    case mojom::blink::PointerLockResult::kAlreadyLocked:
      return MakeGarbageCollected<DOMException>(
          DOMExceptionCode::kInUseAttributeError, "Pointer is already locked.");
    case mojom::blink::PointerLockResult::kWrongDocument:
      return MakeGarbageCollected<DOMException>(
          DOMExceptionCode::kWrongDocumentError,
          "The root document of this element is not valid for pointer lock.");
    case mojom::blink::PointerLockResult::kPermissionDenied:
      return MakeGarbageCollected<DOMException>(
          DOMExceptionCode::kSecurityError,
          "The root document of this element is not valid for pointer lock.");
    case mojom::blink::PointerLockResult::kElementDestroyed:
      return MakeGarbageCollected<DOMException>(
          DOMExceptionCode::kWrongDocumentError,
          "The element has been destroyed while making this request.");
    case mojom::blink::PointerLockResult::kUserRejected:
      return MakeGarbageCollected<DOMException>(
          DOMExceptionCode::kSecurityError,
          "The user has exited the lock before this request was completed.");
    case mojom::blink::PointerLockResult::kSuccess:
    case mojom::blink::PointerLockResult::kUnknownError:
      return MakeGarbageCollected<DOMException>(
          DOMExceptionCode::kUnknownError,
          "If you see this error we have a bug. Please report this bug to "
          "chromium.");
  }
}

void PointerLockController::RejectIfPromiseEnabled(
    ScriptPromiseResolver* resolver,
    DOMException* exception) {
  if (RuntimeEnabledFeatures::PointerLockOptionsEnabled(
          resolver->GetExecutionContext())) {
    resolver->Reject(exception);
  }
}

void PointerLockController::RequestPointerUnlock() {
  return page_->GetChromeClient().RequestPointerUnlock(
      element_->GetDocument().GetFrame());
}

void PointerLockController::ElementRemoved(Element* element) {
  if (element_ == element) {
    document_of_removed_element_while_waiting_for_unlock_ =
        &element_->GetDocument();
    RequestPointerUnlock();
    // Set element null immediately to block any future interaction with it
    // including mouse events received before the unlock completes.
    ClearElement();
  }
}

void PointerLockController::DocumentDetached(Document* document) {
  if (element_ && element_->GetDocument() == document) {
    RequestPointerUnlock();
    ClearElement();
  }
}

bool PointerLockController::LockPending() const {
  return lock_pending_;
}

Element* PointerLockController::GetElement() const {
  return element_.Get();
}

void PointerLockController::DidAcquirePointerLock() {
  EnqueueEvent(event_type_names::kPointerlockchange, element_.Get());
  lock_pending_ = false;
  if (element_) {
    LocalFrame* frame = element_->GetDocument().GetFrame();
    pointer_lock_position_ = frame->LocalFrameRoot()
                                 .GetEventHandler()
                                 .LastKnownMousePositionInRootFrame();
    pointer_lock_screen_position_ = frame->LocalFrameRoot()
                                        .GetEventHandler()
                                        .LastKnownMouseScreenPosition();
  }
}

void PointerLockController::DidNotAcquirePointerLock() {
  EnqueueEvent(event_type_names::kPointerlockerror, element_.Get());
  ClearElement();
}

void PointerLockController::DidLosePointerLock() {
  Document* pointer_lock_document =
      element_ ? &element_->GetDocument()
               : document_of_removed_element_while_waiting_for_unlock_.Get();
  EnqueueEvent(event_type_names::kPointerlockchange, pointer_lock_document);

  // Set the last mouse position back the locked position.
  if (pointer_lock_document && pointer_lock_document->GetFrame()) {
    pointer_lock_document->GetFrame()
        ->GetEventHandler()
        .ResetMousePositionForPointerUnlock();
  }

  ClearElement();
  document_of_removed_element_while_waiting_for_unlock_ = nullptr;
}

void PointerLockController::DispatchLockedMouseEvent(
    const WebMouseEvent& event,
    const Vector<WebMouseEvent>& coalesced_events,
    const Vector<WebMouseEvent>& predicted_events,
    const AtomicString& event_type) {
  if (!element_ || !element_->GetDocument().GetFrame())
    return;

  if (LocalFrame* frame = element_->GetDocument().GetFrame()) {
    frame->GetEventHandler().HandleTargetedMouseEvent(
        element_, event, event_type, coalesced_events, predicted_events);

    // Event handlers may remove element.
    if (!element_)
      return;

    // Create click events
    if (event_type == event_type_names::kMouseup) {
      frame->GetEventHandler().HandleTargetedMouseEvent(
          element_, event, event_type_names::kClick, Vector<WebMouseEvent>(),
          Vector<WebMouseEvent>());
    }
  }
}

void PointerLockController::GetPointerLockPosition(
    FloatPoint* lock_position,
    FloatPoint* lock_screen_position) {
  if (element_ && !lock_pending_) {
    DCHECK(lock_position);
    DCHECK(lock_screen_position);
    *lock_position = pointer_lock_position_;
    *lock_screen_position = pointer_lock_screen_position_;
  }
}

void PointerLockController::ClearElement() {
  lock_pending_ = false;
  element_ = nullptr;
}

void PointerLockController::EnqueueEvent(const AtomicString& type,
                                         Element* element) {
  if (element)
    EnqueueEvent(type, &element->GetDocument());
}

void PointerLockController::EnqueueEvent(const AtomicString& type,
                                         Document* document) {
  if (document && document->domWindow()) {
    document->domWindow()->EnqueueDocumentEvent(*Event::Create(type),
                                                TaskType::kMiscPlatformAPI);
  }
}

void PointerLockController::Trace(Visitor* visitor) {
  visitor->Trace(page_);
  visitor->Trace(element_);
  visitor->Trace(document_of_removed_element_while_waiting_for_unlock_);
}

}  // namespace blink