summaryrefslogtreecommitdiffstats
path: root/devtools/client/shadereditor/test/head.js
blob: 754a0605d9f1ae34c5894799f02416c2e2548ee0 (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
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";

var { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;

var { require } = Cu.import("resource://devtools/shared/Loader.jsm", {});
var { Task } = require("devtools/shared/task");

var Services = require("Services");
var promise = require("promise");
var { gDevTools } = require("devtools/client/framework/devtools");
var { DebuggerClient } = require("devtools/shared/client/main");
var { DebuggerServer } = require("devtools/server/main");
var { WebGLFront } = require("devtools/shared/fronts/webgl");
var DevToolsUtils = require("devtools/shared/DevToolsUtils");
var flags = require("devtools/shared/flags");
var { TargetFactory } = require("devtools/client/framework/target");
var { Toolbox } = require("devtools/client/framework/toolbox");
var { isWebGLSupported } = require("devtools/client/shared/webgl-utils");
var mm = null;

const FRAME_SCRIPT_UTILS_URL = "chrome://devtools/content/shared/frame-script-utils.js";
const EXAMPLE_URL = "http://example.com/browser/devtools/client/shadereditor/test/";
const SIMPLE_CANVAS_URL = EXAMPLE_URL + "doc_simple-canvas.html";
const SHADER_ORDER_URL = EXAMPLE_URL + "doc_shader-order.html";
const MULTIPLE_CONTEXTS_URL = EXAMPLE_URL + "doc_multiple-contexts.html";
const OVERLAPPING_GEOMETRY_CANVAS_URL = EXAMPLE_URL + "doc_overlapping-geometry.html";
const BLENDED_GEOMETRY_CANVAS_URL = EXAMPLE_URL + "doc_blended-geometry.html";

var gEnableLogging = Services.prefs.getBoolPref("devtools.debugger.log");
// To enable logging for try runs, just set the pref to true.
Services.prefs.setBoolPref("devtools.debugger.log", false);

// All tests are asynchronous.
waitForExplicitFinish();

var gToolEnabled = Services.prefs.getBoolPref("devtools.shadereditor.enabled");

flags.testing = true;

registerCleanupFunction(() => {
  info("finish() was called, cleaning up...");
  flags.testing = false;
  Services.prefs.setBoolPref("devtools.debugger.log", gEnableLogging);
  Services.prefs.setBoolPref("devtools.shadereditor.enabled", gToolEnabled);

  // These tests use a lot of memory due to GL contexts, so force a GC to help
  // fragmentation.
  info("Forcing GC after shadereditor test.");
  Cu.forceGC();
});

/**
 * Call manually in tests that use frame script utils after initializing
 * the shader editor. Must be called after initializing so we can detect
 * whether or not `content` is a CPOW or not. Call after init but before navigating
 * to different pages, as bfcache and thus shader caching gets really strange if
 * frame script attached in the middle of the test.
 */
function loadFrameScripts() {
  if (Cu.isCrossProcessWrapper(content)) {
    mm = gBrowser.selectedBrowser.messageManager;
    mm.loadFrameScript(FRAME_SCRIPT_UTILS_URL, false);
  }
}

function addTab(aUrl, aWindow) {
  info("Adding tab: " + aUrl);

  let deferred = promise.defer();
  let targetWindow = aWindow || window;
  let targetBrowser = targetWindow.gBrowser;

  targetWindow.focus();
  let tab = targetBrowser.selectedTab = targetBrowser.addTab(aUrl);
  let linkedBrowser = tab.linkedBrowser;

  BrowserTestUtils.browserLoaded(linkedBrowser).then(function () {
    info("Tab added and finished loading: " + aUrl);
    deferred.resolve(tab);
  });

  return deferred.promise;
}

function removeTab(aTab, aWindow) {
  info("Removing tab.");

  let deferred = promise.defer();
  let targetWindow = aWindow || window;
  let targetBrowser = targetWindow.gBrowser;
  let tabContainer = targetBrowser.tabContainer;

  tabContainer.addEventListener("TabClose", function onClose(aEvent) {
    tabContainer.removeEventListener("TabClose", onClose, false);
    info("Tab removed and finished closing.");
    deferred.resolve();
  }, false);

  targetBrowser.removeTab(aTab);
  return deferred.promise;
}

function handleError(aError) {
  ok(false, "Got an error: " + aError.message + "\n" + aError.stack);
  finish();
}

function ifWebGLSupported() {
  ok(false, "You need to define a 'ifWebGLSupported' function.");
  finish();
}

function ifWebGLUnsupported() {
  todo(false, "Skipping test because WebGL isn't supported.");
  finish();
}

function test() {
  let generator = isWebGLSupported(document) ? ifWebGLSupported : ifWebGLUnsupported;
  Task.spawn(generator).then(null, handleError);
}

function createCanvas() {
  return document.createElementNS("http://www.w3.org/1999/xhtml", "canvas");
}

function once(aTarget, aEventName, aUseCapture = false) {
  info("Waiting for event: '" + aEventName + "' on " + aTarget + ".");

  let deferred = promise.defer();

  for (let [add, remove] of [
    ["on", "off"], // Use event emitter before DOM events for consistency
    ["addEventListener", "removeEventListener"],
    ["addListener", "removeListener"]
  ]) {
    if ((add in aTarget) && (remove in aTarget)) {
      aTarget[add](aEventName, function onEvent(...aArgs) {
        aTarget[remove](aEventName, onEvent, aUseCapture);
        deferred.resolve(...aArgs);
      }, aUseCapture);
      break;
    }
  }

  return deferred.promise;
}

// Hack around `once`, as that only resolves to a single (first) argument
// and discards the rest. `onceSpread` is similar, except resolves to an
// array of all of the arguments in the handler. These should be consolidated
// into the same function, but many tests will need to be changed.
function onceSpread(aTarget, aEvent) {
  let deferred = promise.defer();
  aTarget.once(aEvent, (...args) => deferred.resolve(args));
  return deferred.promise;
}

function observe(aNotificationName, aOwnsWeak = false) {
  info("Waiting for observer notification: '" + aNotificationName + ".");

  let deferred = promise.defer();

  Services.obs.addObserver(function onNotification(...aArgs) {
    Services.obs.removeObserver(onNotification, aNotificationName);
    deferred.resolve.apply(deferred, aArgs);
  }, aNotificationName, aOwnsWeak);

  return deferred.promise;
}

function isApprox(aFirst, aSecond, aMargin = 1) {
  return Math.abs(aFirst - aSecond) <= aMargin;
}

function isApproxColor(aFirst, aSecond, aMargin) {
  return isApprox(aFirst.r, aSecond.r, aMargin) &&
    isApprox(aFirst.g, aSecond.g, aMargin) &&
    isApprox(aFirst.b, aSecond.b, aMargin) &&
    isApprox(aFirst.a, aSecond.a, aMargin);
}

function ensurePixelIs(aFront, aPosition, aColor, aWaitFlag = false, aSelector = "canvas") {
  return Task.spawn(function* () {
    let pixel = yield aFront.getPixel({ selector: aSelector, position: aPosition });
    if (isApproxColor(pixel, aColor)) {
      ok(true, "Expected pixel is shown at: " + aPosition.toSource());
      return;
    }

    if (aWaitFlag) {
      yield aFront.waitForFrame();
      return ensurePixelIs(aFront, aPosition, aColor, aWaitFlag, aSelector);
    }

    ok(false, "Expected pixel was not already shown at: " + aPosition.toSource());
    throw new Error("Expected pixel was not already shown at: " + aPosition.toSource());
  });
}

function navigateInHistory(aTarget, aDirection, aWaitForTargetEvent = "navigate") {
  if (Cu.isCrossProcessWrapper(content)) {
    if (!mm) {
      throw new Error("`loadFrameScripts()` must be called before attempting to navigate in e10s.");
    }
    mm.sendAsyncMessage("devtools:test:history", { direction: aDirection });
  }
  else {
    executeSoon(() => content.history[aDirection]());
  }
  return once(aTarget, aWaitForTargetEvent);
}

function navigate(aTarget, aUrl, aWaitForTargetEvent = "navigate") {
  executeSoon(() => aTarget.activeTab.navigateTo(aUrl));
  return once(aTarget, aWaitForTargetEvent);
}

function reload(aTarget, aWaitForTargetEvent = "navigate") {
  executeSoon(() => aTarget.activeTab.reload());
  return once(aTarget, aWaitForTargetEvent);
}

function initBackend(aUrl) {
  info("Initializing a shader editor front.");

  if (!DebuggerServer.initialized) {
    DebuggerServer.init();
    DebuggerServer.addBrowserActors();
  }

  return Task.spawn(function* () {
    let tab = yield addTab(aUrl);
    let target = TargetFactory.forTab(tab);

    yield target.makeRemote();

    let front = new WebGLFront(target.client, target.form);
    return { target, front };
  });
}

function initShaderEditor(aUrl) {
  info("Initializing a shader editor pane.");

  return Task.spawn(function* () {
    let tab = yield addTab(aUrl);
    let target = TargetFactory.forTab(tab);

    yield target.makeRemote();

    Services.prefs.setBoolPref("devtools.shadereditor.enabled", true);
    let toolbox = yield gDevTools.showToolbox(target, "shadereditor");
    let panel = toolbox.getCurrentPanel();
    return { target, panel };
  });
}

function teardown(aPanel) {
  info("Destroying the specified shader editor.");

  return promise.all([
    once(aPanel, "destroyed"),
    removeTab(aPanel.target.tab)
  ]);
}

// Due to `program-linked` events firing synchronously, we cannot
// just yield/chain them together, as then we miss all actors after the
// first event since they're fired consecutively. This allows us to capture
// all actors and returns an array containing them.
//
// Takes a `front` object that is an event emitter, the number of
// programs that should be listened to and waited on, and an optional
// `onAdd` function that calls with the entire actors array on program link
function getPrograms(front, count, onAdd) {
  let actors = [];
  let deferred = promise.defer();
  front.on("program-linked", function onLink(actor) {
    if (actors.length !== count) {
      actors.push(actor);
      if (typeof onAdd === "function") onAdd(actors);
    }
    if (actors.length === count) {
      front.off("program-linked", onLink);
      deferred.resolve(actors);
    }
  });
  return deferred.promise;
}