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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
|
/* 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 { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
const {require} = Cu.import("resource://devtools/shared/Loader.jsm", {});
const {XPCOMUtils} = require("resource://gre/modules/XPCOMUtils.jsm");
const {SideMenuWidget} = require("resource://devtools/client/shared/widgets/SideMenuWidget.jsm");
const promise = require("promise");
const Services = require("Services");
const EventEmitter = require("devtools/shared/event-emitter");
const Tooltip = require("devtools/client/shared/widgets/tooltip/Tooltip");
const Editor = require("devtools/client/sourceeditor/editor");
const {LocalizationHelper} = require("devtools/shared/l10n");
const {Heritage, WidgetMethods, setNamedTimeout} =
require("devtools/client/shared/widgets/view-helpers");
const {Task} = require("devtools/shared/task");
// The panel's window global is an EventEmitter firing the following events:
const EVENTS = {
// When new programs are received from the server.
NEW_PROGRAM: "ShaderEditor:NewProgram",
PROGRAMS_ADDED: "ShaderEditor:ProgramsAdded",
// When the vertex and fragment sources were shown in the editor.
SOURCES_SHOWN: "ShaderEditor:SourcesShown",
// When a shader's source was edited and compiled via the editor.
SHADER_COMPILED: "ShaderEditor:ShaderCompiled",
// When the UI is reset from tab navigation
UI_RESET: "ShaderEditor:UIReset",
// When the editor's error markers are all removed
EDITOR_ERROR_MARKERS_REMOVED: "ShaderEditor:EditorCleaned"
};
XPCOMUtils.defineConstant(this, "EVENTS", EVENTS);
const STRINGS_URI = "devtools/client/locales/shadereditor.properties";
const HIGHLIGHT_TINT = [1, 0, 0.25, 1]; // rgba
const TYPING_MAX_DELAY = 500; // ms
const SHADERS_AUTOGROW_ITEMS = 4;
const GUTTER_ERROR_PANEL_OFFSET_X = 7; // px
const GUTTER_ERROR_PANEL_DELAY = 100; // ms
const DEFAULT_EDITOR_CONFIG = {
gutters: ["errors"],
lineNumbers: true,
showAnnotationRuler: true
};
/**
* The current target and the WebGL Editor front, set by this tool's host.
*/
var gToolbox, gTarget, gFront;
/**
* Initializes the shader editor controller and views.
*/
function startupShaderEditor() {
return promise.all([
EventsHandler.initialize(),
ShadersListView.initialize(),
ShadersEditorsView.initialize()
]);
}
/**
* Destroys the shader editor controller and views.
*/
function shutdownShaderEditor() {
return promise.all([
EventsHandler.destroy(),
ShadersListView.destroy(),
ShadersEditorsView.destroy()
]);
}
/**
* Functions handling target-related lifetime events.
*/
var EventsHandler = {
/**
* Listen for events emitted by the current tab target.
*/
initialize: function () {
this._onHostChanged = this._onHostChanged.bind(this);
this._onTabNavigated = this._onTabNavigated.bind(this);
this._onProgramLinked = this._onProgramLinked.bind(this);
this._onProgramsAdded = this._onProgramsAdded.bind(this);
gToolbox.on("host-changed", this._onHostChanged);
gTarget.on("will-navigate", this._onTabNavigated);
gTarget.on("navigate", this._onTabNavigated);
gFront.on("program-linked", this._onProgramLinked);
this.reloadButton = $("#requests-menu-reload-notice-button");
this.reloadButton.addEventListener("command", this._onReloadCommand);
},
/**
* Remove events emitted by the current tab target.
*/
destroy: function () {
gToolbox.off("host-changed", this._onHostChanged);
gTarget.off("will-navigate", this._onTabNavigated);
gTarget.off("navigate", this._onTabNavigated);
gFront.off("program-linked", this._onProgramLinked);
this.reloadButton.removeEventListener("command", this._onReloadCommand);
},
/**
* Handles a command event on reload button
*/
_onReloadCommand() {
gFront.setup({ reload: true });
},
/**
* Handles a host change event on the parent toolbox.
*/
_onHostChanged: function () {
if (gToolbox.hostType == "side") {
$("#shaders-pane").removeAttribute("height");
}
},
/**
* Called for each location change in the debugged tab.
*/
_onTabNavigated: function (event, {isFrameSwitching}) {
switch (event) {
case "will-navigate": {
// Make sure the backend is prepared to handle WebGL contexts.
if (!isFrameSwitching) {
gFront.setup({ reload: false });
}
// Reset UI.
ShadersListView.empty();
// When switching to an iframe, ensure displaying the reload button.
// As the document has already been loaded without being hooked.
if (isFrameSwitching) {
$("#reload-notice").hidden = false;
$("#waiting-notice").hidden = true;
} else {
$("#reload-notice").hidden = true;
$("#waiting-notice").hidden = false;
}
$("#content").hidden = true;
window.emit(EVENTS.UI_RESET);
break;
}
case "navigate": {
// Manually retrieve the list of program actors known to the server,
// because the backend won't emit "program-linked" notifications
// in the case of a bfcache navigation (since no new programs are
// actually linked).
gFront.getPrograms().then(this._onProgramsAdded);
break;
}
}
},
/**
* Called every time a program was linked in the debugged tab.
*/
_onProgramLinked: function (programActor) {
this._addProgram(programActor);
window.emit(EVENTS.NEW_PROGRAM);
},
/**
* Callback for the front's getPrograms() method.
*/
_onProgramsAdded: function (programActors) {
programActors.forEach(this._addProgram);
window.emit(EVENTS.PROGRAMS_ADDED);
},
/**
* Adds a program to the shaders list and unhides any modal notices.
*/
_addProgram: function (programActor) {
$("#waiting-notice").hidden = true;
$("#reload-notice").hidden = true;
$("#content").hidden = false;
ShadersListView.addProgram(programActor);
}
};
/**
* Functions handling the sources UI.
*/
var ShadersListView = Heritage.extend(WidgetMethods, {
/**
* Initialization function, called when the tool is started.
*/
initialize: function () {
this.widget = new SideMenuWidget(this._pane = $("#shaders-pane"), {
showArrows: true,
showItemCheckboxes: true
});
this._onProgramSelect = this._onProgramSelect.bind(this);
this._onProgramCheck = this._onProgramCheck.bind(this);
this._onProgramMouseOver = this._onProgramMouseOver.bind(this);
this._onProgramMouseOut = this._onProgramMouseOut.bind(this);
this.widget.addEventListener("select", this._onProgramSelect, false);
this.widget.addEventListener("check", this._onProgramCheck, false);
this.widget.addEventListener("mouseover", this._onProgramMouseOver, true);
this.widget.addEventListener("mouseout", this._onProgramMouseOut, true);
},
/**
* Destruction function, called when the tool is closed.
*/
destroy: function () {
this.widget.removeEventListener("select", this._onProgramSelect, false);
this.widget.removeEventListener("check", this._onProgramCheck, false);
this.widget.removeEventListener("mouseover", this._onProgramMouseOver, true);
this.widget.removeEventListener("mouseout", this._onProgramMouseOut, true);
},
/**
* Adds a program to this programs container.
*
* @param object programActor
* The program actor coming from the active thread.
*/
addProgram: function (programActor) {
if (this.hasProgram(programActor)) {
return;
}
// Currently, there's no good way of differentiating between programs
// in a way that helps humans. It will be a good idea to implement a
// standard of allowing debuggees to add some identifiable metadata to their
// program sources or instances.
let label = L10N.getFormatStr("shadersList.programLabel", this.itemCount);
let contents = document.createElement("label");
contents.className = "plain program-item";
contents.setAttribute("value", label);
contents.setAttribute("crop", "start");
contents.setAttribute("flex", "1");
// Append a program item to this container.
this.push([contents], {
index: -1, /* specifies on which position should the item be appended */
attachment: {
label: label,
programActor: programActor,
checkboxState: true,
checkboxTooltip: L10N.getStr("shadersList.blackboxLabel")
}
});
// Make sure there's always a selected item available.
if (!this.selectedItem) {
this.selectedIndex = 0;
}
// Prevent this container from growing indefinitely in height when the
// toolbox is docked to the side.
if (gToolbox.hostType == "side" && this.itemCount == SHADERS_AUTOGROW_ITEMS) {
this._pane.setAttribute("height", this._pane.getBoundingClientRect().height);
}
},
/**
* Returns whether a program was already added to this programs container.
*
* @param object programActor
* The program actor coming from the active thread.
* @param boolean
* True if the program was added, false otherwise.
*/
hasProgram: function (programActor) {
return !!this.attachments.filter(e => e.programActor == programActor).length;
},
/**
* The select listener for the programs container.
*/
_onProgramSelect: function ({ detail: sourceItem }) {
if (!sourceItem) {
return;
}
// The container is not empty and an actual item was selected.
let attachment = sourceItem.attachment;
function getShaders() {
return promise.all([
attachment.vs || (attachment.vs = attachment.programActor.getVertexShader()),
attachment.fs || (attachment.fs = attachment.programActor.getFragmentShader())
]);
}
function getSources([vertexShaderActor, fragmentShaderActor]) {
return promise.all([
vertexShaderActor.getText(),
fragmentShaderActor.getText()
]);
}
function showSources([vertexShaderText, fragmentShaderText]) {
return ShadersEditorsView.setText({
vs: vertexShaderText,
fs: fragmentShaderText
});
}
getShaders()
.then(getSources)
.then(showSources)
.then(null, e => console.error(e));
},
/**
* The check listener for the programs container.
*/
_onProgramCheck: function ({ detail: { checked }, target }) {
let sourceItem = this.getItemForElement(target);
let attachment = sourceItem.attachment;
attachment.isBlackBoxed = !checked;
attachment.programActor[checked ? "unblackbox" : "blackbox"]();
},
/**
* The mouseover listener for the programs container.
*/
_onProgramMouseOver: function (e) {
let sourceItem = this.getItemForElement(e.target, { noSiblings: true });
if (sourceItem && !sourceItem.attachment.isBlackBoxed) {
sourceItem.attachment.programActor.highlight(HIGHLIGHT_TINT);
if (e instanceof Event) {
e.preventDefault();
e.stopPropagation();
}
}
},
/**
* The mouseout listener for the programs container.
*/
_onProgramMouseOut: function (e) {
let sourceItem = this.getItemForElement(e.target, { noSiblings: true });
if (sourceItem && !sourceItem.attachment.isBlackBoxed) {
sourceItem.attachment.programActor.unhighlight();
if (e instanceof Event) {
e.preventDefault();
e.stopPropagation();
}
}
}
});
/**
* Functions handling the editors displaying the vertex and fragment shaders.
*/
var ShadersEditorsView = {
/**
* Initialization function, called when the tool is started.
*/
initialize: function () {
XPCOMUtils.defineLazyGetter(this, "_editorPromises", () => new Map());
this._vsFocused = this._onFocused.bind(this, "vs", "fs");
this._fsFocused = this._onFocused.bind(this, "fs", "vs");
this._vsChanged = this._onChanged.bind(this, "vs");
this._fsChanged = this._onChanged.bind(this, "fs");
},
/**
* Destruction function, called when the tool is closed.
*/
destroy: Task.async(function* () {
this._destroyed = true;
yield this._toggleListeners("off");
for (let p of this._editorPromises.values()) {
let editor = yield p;
editor.destroy();
}
}),
/**
* Sets the text displayed in the vertex and fragment shader editors.
*
* @param object sources
* An object containing the following properties
* - vs: the vertex shader source code
* - fs: the fragment shader source code
* @return object
* A promise resolving upon completion of text setting.
*/
setText: function (sources) {
let view = this;
function setTextAndClearHistory(editor, text) {
editor.setText(text);
editor.clearHistory();
}
return Task.spawn(function* () {
yield view._toggleListeners("off");
yield promise.all([
view._getEditor("vs").then(e => setTextAndClearHistory(e, sources.vs)),
view._getEditor("fs").then(e => setTextAndClearHistory(e, sources.fs))
]);
yield view._toggleListeners("on");
}).then(() => window.emit(EVENTS.SOURCES_SHOWN, sources));
},
/**
* Lazily initializes and returns a promise for an Editor instance.
*
* @param string type
* Specifies for which shader type should an editor be retrieved,
* either are "vs" for a vertex, or "fs" for a fragment shader.
* @return object
* Returns a promise that resolves to an editor instance
*/
_getEditor: function (type) {
if (this._editorPromises.has(type)) {
return this._editorPromises.get(type);
}
let deferred = promise.defer();
this._editorPromises.set(type, deferred.promise);
// Initialize the source editor and store the newly created instance
// in the ether of a resolved promise's value.
let parent = $("#" + type + "-editor");
let editor = new Editor(DEFAULT_EDITOR_CONFIG);
editor.config.mode = Editor.modes[type];
if (this._destroyed) {
deferred.resolve(editor);
} else {
editor.appendTo(parent).then(() => deferred.resolve(editor));
}
return deferred.promise;
},
/**
* Toggles all the event listeners for the editors either on or off.
*
* @param string flag
* Either "on" to enable the event listeners, "off" to disable them.
* @return object
* A promise resolving upon completion of toggling the listeners.
*/
_toggleListeners: function (flag) {
return promise.all(["vs", "fs"].map(type => {
return this._getEditor(type).then(editor => {
editor[flag]("focus", this["_" + type + "Focused"]);
editor[flag]("change", this["_" + type + "Changed"]);
});
}));
},
/**
* The focus listener for a source editor.
*
* @param string focused
* The corresponding shader type for the focused editor (e.g. "vs").
* @param string focused
* The corresponding shader type for the other editor (e.g. "fs").
*/
_onFocused: function (focused, unfocused) {
$("#" + focused + "-editor-label").setAttribute("selected", "");
$("#" + unfocused + "-editor-label").removeAttribute("selected");
},
/**
* The change listener for a source editor.
*
* @param string type
* The corresponding shader type for the focused editor (e.g. "vs").
*/
_onChanged: function (type) {
setNamedTimeout("gl-typed", TYPING_MAX_DELAY, () => this._doCompile(type));
// Remove all the gutter markers and line classes from the editor.
this._cleanEditor(type);
},
/**
* Recompiles the source code for the shader being edited.
* This function is fired at a certain delay after the user stops typing.
*
* @param string type
* The corresponding shader type for the focused editor (e.g. "vs").
*/
_doCompile: function (type) {
Task.spawn(function* () {
let editor = yield this._getEditor(type);
let shaderActor = yield ShadersListView.selectedAttachment[type];
try {
yield shaderActor.compile(editor.getText());
this._onSuccessfulCompilation();
} catch (e) {
this._onFailedCompilation(type, editor, e);
}
}.bind(this));
},
/**
* Called uppon a successful shader compilation.
*/
_onSuccessfulCompilation: function () {
// Signal that the shader was compiled successfully.
window.emit(EVENTS.SHADER_COMPILED, null);
},
/**
* Called uppon an unsuccessful shader compilation.
*/
_onFailedCompilation: function (type, editor, errors) {
let lineCount = editor.lineCount();
let currentLine = editor.getCursor().line;
let listeners = { mouseover: this._onMarkerMouseOver };
function matchLinesAndMessages(string) {
return {
// First number that is not equal to 0.
lineMatch: string.match(/\d{2,}|[1-9]/),
// The string after all the numbers, semicolons and spaces.
textMatch: string.match(/[^\s\d:][^\r\n|]*/)
};
}
function discardInvalidMatches(e) {
// Discard empty line and text matches.
return e.lineMatch && e.textMatch;
}
function sanitizeValidMatches(e) {
return {
// Drivers might yield confusing line numbers under some obscure
// circumstances. Don't throw the errors away in those cases,
// just display them on the currently edited line.
line: e.lineMatch[0] > lineCount ? currentLine : e.lineMatch[0] - 1,
// Trim whitespace from the beginning and the end of the message,
// and replace all other occurences of double spaces to a single space.
text: e.textMatch[0].trim().replace(/\s{2,}/g, " ")
};
}
function sortByLine(first, second) {
// Sort all the errors ascending by their corresponding line number.
return first.line > second.line ? 1 : -1;
}
function groupSameLineMessages(accumulator, current) {
// Group errors corresponding to the same line number to a single object.
let previous = accumulator[accumulator.length - 1];
if (!previous || previous.line != current.line) {
return [...accumulator, {
line: current.line,
messages: [current.text]
}];
} else {
previous.messages.push(current.text);
return accumulator;
}
}
function displayErrors({ line, messages }) {
// Add gutter markers and line classes for every error in the source.
editor.addMarker(line, "errors", "error");
editor.setMarkerListeners(line, "errors", "error", listeners, messages);
editor.addLineClass(line, "error-line");
}
(this._errors[type] = errors.link
.split("ERROR")
.map(matchLinesAndMessages)
.filter(discardInvalidMatches)
.map(sanitizeValidMatches)
.sort(sortByLine)
.reduce(groupSameLineMessages, []))
.forEach(displayErrors);
// Signal that the shader wasn't compiled successfully.
window.emit(EVENTS.SHADER_COMPILED, errors);
},
/**
* Event listener for the 'mouseover' event on a marker in the editor gutter.
*/
_onMarkerMouseOver: function (line, node, messages) {
if (node._markerErrorsTooltip) {
return;
}
let tooltip = node._markerErrorsTooltip = new Tooltip(document);
tooltip.defaultOffsetX = GUTTER_ERROR_PANEL_OFFSET_X;
tooltip.setTextContent({ messages: messages });
tooltip.startTogglingOnHover(node, () => true, {
toggleDelay: GUTTER_ERROR_PANEL_DELAY
});
},
/**
* Removes all the gutter markers and line classes from the editor.
*/
_cleanEditor: function (type) {
this._getEditor(type).then(editor => {
editor.removeAllMarkers("errors");
this._errors[type].forEach(e => editor.removeLineClass(e.line));
this._errors[type].length = 0;
window.emit(EVENTS.EDITOR_ERROR_MARKERS_REMOVED);
});
},
_errors: {
vs: [],
fs: []
}
};
/**
* Localization convenience methods.
*/
var L10N = new LocalizationHelper(STRINGS_URI);
/**
* Convenient way of emitting events from the panel window.
*/
EventEmitter.decorate(this);
/**
* DOM query helper.
*/
var $ = (selector, target = document) => target.querySelector(selector);
|