summaryrefslogtreecommitdiffstats
path: root/devtools/shared/touch/simulator.js
blob: 0e6d29282498b6c2a3a258a51f45e1565df809c3 (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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";

var promise = require("promise");
var defer = require("devtools/shared/defer");
var Services = require("Services");

const FRAME_SCRIPT =
  "resource://devtools/shared/touch/simulator-content.js";

var trackedBrowsers = new WeakMap();
var savedTouchEventsEnabled =
  Services.prefs.getIntPref("dom.w3c_touch_events.enabled");

/**
 * Simulate touch events for platforms where they aren't generally available.
 * Defers to the `simulator-content.js` frame script to perform the real work.
 */
function TouchEventSimulator(browser) {
  // Returns an already instantiated simulator for this browser
  let simulator = trackedBrowsers.get(browser);
  if (simulator) {
    return simulator;
  }

  let mm = browser.frameLoader.messageManager;
  mm.loadFrameScript(FRAME_SCRIPT, true);

  simulator = {
    enabled: false,

    start() {
      if (this.enabled) {
        return promise.resolve({ isReloadNeeded: false });
      }
      this.enabled = true;

      let deferred = defer();
      let isReloadNeeded =
        Services.prefs.getIntPref("dom.w3c_touch_events.enabled") != 1;
      Services.prefs.setIntPref("dom.w3c_touch_events.enabled", 1);
      let onStarted = () => {
        mm.removeMessageListener("TouchEventSimulator:Started", onStarted);
        deferred.resolve({ isReloadNeeded });
      };
      mm.addMessageListener("TouchEventSimulator:Started", onStarted);
      mm.sendAsyncMessage("TouchEventSimulator:Start");
      return deferred.promise;
    },

    stop() {
      if (!this.enabled) {
        return promise.resolve();
      }
      this.enabled = false;

      let deferred = defer();
      Services.prefs.setIntPref("dom.w3c_touch_events.enabled",
                                savedTouchEventsEnabled);
      let onStopped = () => {
        mm.removeMessageListener("TouchEventSimulator:Stopped", onStopped);
        deferred.resolve();
      };
      mm.addMessageListener("TouchEventSimulator:Stopped", onStopped);
      mm.sendAsyncMessage("TouchEventSimulator:Stop");
      return deferred.promise;
    }
  };

  trackedBrowsers.set(browser, simulator);

  return simulator;
}

exports.TouchEventSimulator = TouchEventSimulator;