simulator.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. var promise = require("promise");
  6. var defer = require("devtools/shared/defer");
  7. var Services = require("Services");
  8. const FRAME_SCRIPT =
  9. "resource://devtools/shared/touch/simulator-content.js";
  10. var trackedBrowsers = new WeakMap();
  11. var savedTouchEventsEnabled =
  12. Services.prefs.getIntPref("dom.w3c_touch_events.enabled");
  13. /**
  14. * Simulate touch events for platforms where they aren't generally available.
  15. * Defers to the `simulator-content.js` frame script to perform the real work.
  16. */
  17. function TouchEventSimulator(browser) {
  18. // Returns an already instantiated simulator for this browser
  19. let simulator = trackedBrowsers.get(browser);
  20. if (simulator) {
  21. return simulator;
  22. }
  23. let mm = browser.frameLoader.messageManager;
  24. mm.loadFrameScript(FRAME_SCRIPT, true);
  25. simulator = {
  26. enabled: false,
  27. start() {
  28. if (this.enabled) {
  29. return promise.resolve({ isReloadNeeded: false });
  30. }
  31. this.enabled = true;
  32. let deferred = defer();
  33. let isReloadNeeded =
  34. Services.prefs.getIntPref("dom.w3c_touch_events.enabled") != 1;
  35. Services.prefs.setIntPref("dom.w3c_touch_events.enabled", 1);
  36. let onStarted = () => {
  37. mm.removeMessageListener("TouchEventSimulator:Started", onStarted);
  38. deferred.resolve({ isReloadNeeded });
  39. };
  40. mm.addMessageListener("TouchEventSimulator:Started", onStarted);
  41. mm.sendAsyncMessage("TouchEventSimulator:Start");
  42. return deferred.promise;
  43. },
  44. stop() {
  45. if (!this.enabled) {
  46. return promise.resolve();
  47. }
  48. this.enabled = false;
  49. let deferred = defer();
  50. Services.prefs.setIntPref("dom.w3c_touch_events.enabled",
  51. savedTouchEventsEnabled);
  52. let onStopped = () => {
  53. mm.removeMessageListener("TouchEventSimulator:Stopped", onStopped);
  54. deferred.resolve();
  55. };
  56. mm.addMessageListener("TouchEventSimulator:Stopped", onStopped);
  57. mm.sendAsyncMessage("TouchEventSimulator:Stop");
  58. return deferred.promise;
  59. }
  60. };
  61. trackedBrowsers.set(browser, simulator);
  62. return simulator;
  63. }
  64. exports.TouchEventSimulator = TouchEventSimulator;