1/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17'use strict';
18
19function trackMouseEvents(dc, mouseElement) {
20  function onMouseDown(evt) {
21    if (!document.pointerLockElement) {
22      mouseElement.requestPointerLock({});
23      return;
24    }
25    dc.sendMouseButton({button: evt.button, down: true});
26  }
27
28  function onMouseUp(evt) {
29    if (document.pointerLockElement) {
30      dc.sendMouseButton({button: evt.button, down: false});
31    }
32  }
33
34  function onMouseMove(evt) {
35    if (document.pointerLockElement) {
36      dc.sendMouseMove({x: evt.movementX, y: evt.movementY});
37      dc.sendMouseButton({button: evt.button, down: evt.buttons > 0});
38    }
39  }
40  mouseElement.addEventListener('mousedown', onMouseDown);
41  mouseElement.addEventListener('mouseup', onMouseUp);
42  mouseElement.addEventListener('mousemove', onMouseMove);
43}
44
45function enableMouseButton(dc) {
46  function onMouseKey(evt) {
47    if (evt.cancelable) {
48      // Some keyboard events cause unwanted side effects, like elements losing
49      // focus, if the default behavior is not prevented.
50      evt.preventDefault();
51    }
52    dc.sendKeyEvent(evt.code, evt.type);
53  }
54  function onMouseWheel(evt) {
55    evt.preventDefault();
56    // Vertical wheel pixel events only
57    if (evt.deltaMode == WheelEvent.DOM_DELTA_PIXEL && evt.deltaY != 0.0) {
58      dc.sendMouseWheelEvent(evt.deltaY);
59    }
60  }
61  let button = document.getElementById("mouse_btn");
62  button.style.display = "";
63  button.disabled = false;
64  trackMouseEvents(dc, button);
65  button.addEventListener('keydown', onMouseKey);
66  button.addEventListener('keyup', onMouseKey);
67  button.addEventListener('wheel', onMouseWheel,
68                                { passive: false });
69  return button;
70}
71
72